bitgpu 0.9.0 → 0.11.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 +111 -5
- package/dist/chat.d.ts +28 -2
- package/dist/chat.js +21 -0
- package/dist/chat.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +287 -42
- package/dist/index.js.map +1 -1
- package/dist/{types-C5f2IKgm.d.ts → types-DJ61q1gX.d.ts} +79 -14
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,7 +6,10 @@ Today it runs **1-bit (binary-weight)** models.
|
|
|
6
6
|
Reference targets are Bonsai **1.7B, 4B and 8B** (Qwen3 architecture, sign-packed binary linear
|
|
7
7
|
weights + 2/4-bit embeddings, tied or untied lm_head) - every size is gated bit-exact against the
|
|
8
8
|
reference forward on real hardware. GPU-resident decode (greedy or sampled), streaming, EOS stop,
|
|
9
|
-
`AbortSignal`,
|
|
9
|
+
`AbortSignal`, cross-turn KV-cache reuse, optional f16/q8 KV-cache compression for long
|
|
10
|
+
contexts in less VRAM, conversation snapshots (save/restore across page reloads), and an
|
|
11
|
+
optional rolling window with attention sinks for unbounded chats in fixed memory. Runs the
|
|
12
|
+
fast subgroup path on Apple / NVIDIA /
|
|
10
13
|
recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU is available.
|
|
11
14
|
Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
|
|
12
15
|
only when that model needs it and smaller models keep running at WebGPU's guaranteed minimums.
|
|
@@ -31,7 +34,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
|
|
|
31
34
|
import { createEngine } from 'bitgpu'
|
|
32
35
|
import { createChat } from 'bitgpu/chat'
|
|
33
36
|
|
|
34
|
-
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.
|
|
37
|
+
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.11.0/models/bonsai-1.7b'
|
|
35
38
|
const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
|
|
36
39
|
const engine = await createEngine({
|
|
37
40
|
manifestUrl: `${REPO}/manifest.json`,
|
|
@@ -47,7 +50,8 @@ await chat.send([{ role: 'user', content: 'Hi!' }], { onText: (t) => process.std
|
|
|
47
50
|
|
|
48
51
|
The [demo](https://stfurkan.github.io/bitgpu/examples/chat.html) ([source](examples/chat.html))
|
|
49
52
|
is this quickstart as a single HTML file: model picker, streaming chat, JSON mode with a schema
|
|
50
|
-
editor,
|
|
53
|
+
editor, tool calling, cached downloads, and sessions that survive reloads (the KV cache is
|
|
54
|
+
snapshot into IndexedDB and restored - the conversation continues with no re-prefill).
|
|
51
55
|
|
|
52
56
|
## Usage
|
|
53
57
|
|
|
@@ -84,6 +88,78 @@ await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSi
|
|
|
84
88
|
engine.dispose()
|
|
85
89
|
```
|
|
86
90
|
|
|
91
|
+
### KV cache modes (`kvCache`)
|
|
92
|
+
|
|
93
|
+
The KV cache is what grows with conversation length (~224 KB per position at f32 on
|
|
94
|
+
Bonsai-1.7B; `maxSeqLen` caps it). `kvCache` selects its **storage** precision - attention
|
|
95
|
+
arithmetic always stays f32, values are compressed once at cache-write:
|
|
96
|
+
|
|
97
|
+
| Mode | Bytes/value | KV memory | Requires |
|
|
98
|
+
| --- | --- | --- | --- |
|
|
99
|
+
| `'f32'` (default) | 4 | 1x | - |
|
|
100
|
+
| `'f16'` | 2 | 1/2 | `shader-f16` (silently falls back to f32 without it) |
|
|
101
|
+
| `'q8'` | ~1.125 | ~1/4 | nothing - works on every WebGPU adapter |
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
const engine = await createEngine({ modelUrl, kvCache: 'q8', maxSeqLen: 4096 })
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`'q8'` stores 8-bit values with one f32 scale per 32-element block (llama.cpp q8_0-style, the
|
|
108
|
+
tier the wider ecosystem treats as near-lossless). Within any mode decoding stays exact and
|
|
109
|
+
deterministic (same seed -> same tokens, cache reuse == full prefill), but f16/q8 outputs are
|
|
110
|
+
**not guaranteed bit-identical to f32** - they are measured instead: the GPU gate compares
|
|
111
|
+
greedy continuations against f32 on every Bonsai size and both kernel paths, and q8 currently
|
|
112
|
+
agrees 96/96 tokens on short prompts, 24/24 after a 400-token prompt and 48/48 after a
|
|
113
|
+
1500-token prompt (logits cosine >= 0.99997). Long contexts also get *faster* under q8 - decode
|
|
114
|
+
at 1500 tokens of depth measured 37-58% quicker than f32 (attention there is memory-bound and
|
|
115
|
+
reads a quarter of the bytes) - while shallow-context decode measures a few percent slower.
|
|
116
|
+
Reach for `'q8'` to run a 4x longer window in the same VRAM (or the same window on smaller
|
|
117
|
+
GPUs); keep the default `'f32'` when bit-exact reproducibility is the point.
|
|
118
|
+
`engine.capabilities.kvCache` reports what is actually active.
|
|
119
|
+
|
|
120
|
+
### Unbounded conversations (`overflow: 'sinks'`)
|
|
121
|
+
|
|
122
|
+
By default a conversation that outgrows `maxSeqLen` throws. `overflow: 'sinks'` switches to a
|
|
123
|
+
StreamingLLM-style rolling window instead: the first `sinkTokens` positions (default 4, the
|
|
124
|
+
"attention sinks" that anchor the model's attention) plus the most recent window are kept, the
|
|
125
|
+
middle is evicted in batches, and generation or multi-turn chat continues indefinitely in fixed
|
|
126
|
+
memory - `maxTokens` is no longer clamped to the window:
|
|
127
|
+
|
|
128
|
+
```ts
|
|
129
|
+
const engine = await createEngine({ modelUrl, kvCache: 'q8', overflow: 'sinks', maxSeqLen: 4096 })
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Implementation detail that matters: keys are cached **unroped** and rotated at read time by
|
|
133
|
+
their cache-relative position (the StreamingLLM reference scheme), so eviction is a plain
|
|
134
|
+
byte-exact compaction - nothing is ever re-rotated or, under q8, requantized. This is the
|
|
135
|
+
combination llama.cpp cannot offer (its context shift rewrites roped K in place and is
|
|
136
|
+
disabled for quantized K caches); here `q8 + sinks` is the flagship pairing: unbounded chat in
|
|
137
|
+
a quarter of the memory. The guarantees follow the mode philosophy: within-mode decoding is
|
|
138
|
+
exact and deterministic (same seed -> same tokens, across evictions; gated on real hardware),
|
|
139
|
+
and **before the first eviction f32+sinks is bit-identical to default f32** (gated against the
|
|
140
|
+
known-good ids). After an eviction the model genuinely forgets the evicted middle - that is
|
|
141
|
+
the trade, by design: prefer it over hard failure for open-ended chat; prefer `'error'` plus
|
|
142
|
+
prompt-side trimming when every token of context must count. Prompts longer than the window
|
|
143
|
+
still throw (`bitgpu/chat`'s `onOverflow` handles that side). Snapshots keep working - sink
|
|
144
|
+
mode saves version-2 snapshots (restore requires sink mode with the same `sinkTokens`).
|
|
145
|
+
|
|
146
|
+
### Speculative decoding: why only `promptLookup`
|
|
147
|
+
|
|
148
|
+
The engine speculates out of the box where it pays: `promptLookup` drafts from n-gram matches
|
|
149
|
+
in the prompt and verifies them in one batched pass, with auto-probation that measures the
|
|
150
|
+
break-even and bails when speculation does not help (output is bit-identical either way).
|
|
151
|
+
|
|
152
|
+
There is deliberately no draft-model / two-model mode, and the reason is measured, not
|
|
153
|
+
guessed: speculative decoding pays only when verifying k tokens in one batched pass costs
|
|
154
|
+
about one token's time - true for f16 models, whose decode is weight-bandwidth-bound, but not
|
|
155
|
+
for 1-bit models. The weight stream here is so small that batch-1 decode already saturates GPU
|
|
156
|
+
compute, so a k-row verify costs ~k single steps (measured: S=9 verify ~= 9.8x one step, and
|
|
157
|
+
even a perfect zero-cost drafter decoded slower than plain on the subgroup path). A full
|
|
158
|
+
in-engine two-model orchestration was built, gate-proven bit-exact, measured slower, and
|
|
159
|
+
removed - fast single-stream 1-bit decode and profitable speculation are the same budget,
|
|
160
|
+
already spent on the former. Where batching still wins (dispatch-latency-bound setups like the
|
|
161
|
+
no-subgroup fallback path) is exactly where `promptLookup`'s probation keeps it on.
|
|
162
|
+
|
|
87
163
|
## Chat (`bitgpu/chat`)
|
|
88
164
|
|
|
89
165
|
The engine is deliberately ids-in/ids-out; `bitgpu/chat` is the batteries-included text layer on
|
|
@@ -210,6 +286,28 @@ needed, and validate argument *values* in your executor. The engine never execut
|
|
|
210
286
|
never loops, never retries: it returns a validated call and the app stays in charge (there is
|
|
211
287
|
deliberately no agent framework in here).
|
|
212
288
|
|
|
289
|
+
### Conversation snapshots (`save` / `restore`)
|
|
290
|
+
|
|
291
|
+
`chat.save()` captures the whole conversation - the engine's KV cache plus the chat's exact
|
|
292
|
+
token bookkeeping - as one structured-cloneable object; `chat.restore(snapshot)` brings it back,
|
|
293
|
+
so the next turn extends the cache as if the session never ended (no re-prefill of the history):
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
const snapshot = await chat.save() // structured-cloneable: IndexedDB / OPFS / postMessage
|
|
297
|
+
// (NOT JSON.stringify - the KV buffer would be lost)
|
|
298
|
+
// ...page reload: new engine + chat on the same model and kvCache mode...
|
|
299
|
+
await chat.restore(snapshot)
|
|
300
|
+
await chat.send([...savedMessages, { role: 'user', content: 'as I was saying...' }]) // cache reuse
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
Use it for instant conversation switching (save several, restore the active one) and for
|
|
304
|
+
resuming after a reload without re-prefilling a long history. Restore validates the model
|
|
305
|
+
architecture and `kvCache` mode and throws on mismatch; restoring is bit-identical to having
|
|
306
|
+
kept the conversation alive (gated on real hardware). Snapshot size scales with the KV mode
|
|
307
|
+
(~224 / 112 / 63 KB per cached token on Bonsai-1.7B at f32 / f16 / q8), which makes
|
|
308
|
+
`kvCache: 'q8'` the natural companion. The engine-level `engine.saveCache()` /
|
|
309
|
+
`engine.restoreCache()` are the same thing for ids-in/ids-out callers.
|
|
310
|
+
|
|
213
311
|
The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
|
|
214
312
|
see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
|
|
215
313
|
engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
|
|
@@ -261,6 +359,10 @@ regenerating the verification fixtures for a new model: [tools/README.md](tools/
|
|
|
261
359
|
later `generate(delta, { reuseCache: true })` starts from a warm cache (e.g. a static system prompt).
|
|
262
360
|
- `engine.forward(tokenIds)` - single forward pass (hidden states + logits) for correctness checks.
|
|
263
361
|
- `engine.resetCache()` - clear the cross-turn KV cache (start a fresh conversation).
|
|
362
|
+
- `engine.saveCache()` / `engine.restoreCache(snapshot)` - snapshot the conversation (KV cache
|
|
363
|
+
contents + token history) as one structured-cloneable object and bring it back later,
|
|
364
|
+
bit-identically - into this engine or a fresh one on the same model and `kvCache` mode. See
|
|
365
|
+
the chat-layer `save()`/`restore()` below for the batteries-included version.
|
|
264
366
|
- `engine.capabilities` - detected GPU path (`useSubgroups`, `subgroupSize`, adapter info, limits).
|
|
265
367
|
- `engine.lost` - promise that resolves if the GPU device is lost (also via `onDeviceLost` option);
|
|
266
368
|
create a new engine to recover.
|
|
@@ -310,8 +412,11 @@ npm run check:publish # publint + are-the-types-wrong
|
|
|
310
412
|
|
|
311
413
|
`examples/verify.html` re-runs the full bit-exactness + throughput suite (forward cosines vs the
|
|
312
414
|
committed reference fixtures in `test-fixtures/forward/`, known-good greedy ids, sampler kernel
|
|
313
|
-
parity, determinism, KV reuse/growth, prompt-lookup identity
|
|
314
|
-
|
|
415
|
+
parity, determinism, KV reuse/growth, prompt-lookup identity, KV snapshot save/restore round
|
|
416
|
+
trips - including into a fresh engine - the f16/q8 KV-mode sections: within-mode exactness
|
|
417
|
+
plus greedy agreement vs f32 out to a 1500-token prompt, the rolling-window section:
|
|
418
|
+
pre-eviction bit-exactness, 600 tokens through a 192-token window, determinism across
|
|
419
|
+
evictions) against the **built package** and prints `PACKAGE OK` or `REGRESSION`.
|
|
315
420
|
|
|
316
421
|
It needs model weights, which are not committed. Point `examples/model` at a directory holding the
|
|
317
422
|
model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~290 MB):
|
|
@@ -320,6 +425,7 @@ model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~
|
|
|
320
425
|
ln -s /path/to/bonsai-model examples/model # or copy the files in
|
|
321
426
|
npm run build
|
|
322
427
|
npm run verify:headless # serves the repo itself + drives system Chrome headlessly
|
|
428
|
+
FAST=1 npm run verify:headless # dev iteration: baseline model, core sections only (~3 min; NOT a release gate)
|
|
323
429
|
```
|
|
324
430
|
|
|
325
431
|
Or serve the repo root (`python3 -m http.server 8000`) and open
|
package/dist/chat.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { c as KvSnapshot, n as Engine, o as GenerateOptions, u as TokenLogprobs } from "./types-DJ61q1gX.js";
|
|
2
2
|
|
|
3
3
|
//#region src/chat/tokenizer.d.ts
|
|
4
4
|
interface ChatMessage {
|
|
@@ -396,6 +396,22 @@ interface ChatResult {
|
|
|
396
396
|
decodeMs: number;
|
|
397
397
|
tokensPerSecond: number;
|
|
398
398
|
}
|
|
399
|
+
/** A saved conversation from {@link Chat.save}: the engine's {@link KvSnapshot} plus the
|
|
400
|
+
* chat-layer bookkeeping that makes cache reuse safe. Structured-cloneable (store in
|
|
401
|
+
* IndexedDB / OPFS or postMessage as-is; NOT `JSON.stringify`-able - the KV buffer would be
|
|
402
|
+
* lost). Treat the fields as opaque. */
|
|
403
|
+
interface ChatSnapshot {
|
|
404
|
+
/** Snapshot format version (currently `1`). */
|
|
405
|
+
version: 1;
|
|
406
|
+
/** The engine-level KV cache + token history snapshot. */
|
|
407
|
+
engine: KvSnapshot;
|
|
408
|
+
/** The committed transcript the cache holds, as messages. */
|
|
409
|
+
committed: ChatMessage[];
|
|
410
|
+
/** Whether the cached token sequence already ends with the eos token. */
|
|
411
|
+
cacheEndsAtEos: boolean;
|
|
412
|
+
/** Canonical JSON of the tools list the conversation was rendered with (null = no tools). */
|
|
413
|
+
toolsKey: string | null;
|
|
414
|
+
}
|
|
399
415
|
interface Chat {
|
|
400
416
|
/** Generate a reply for the message list. Resolves with the full result; stream text via
|
|
401
417
|
* `onText`. Turns are serialized: overlapping calls queue instead of interleaving. */
|
|
@@ -420,6 +436,16 @@ interface Chat {
|
|
|
420
436
|
/** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
|
|
421
437
|
* Use this (not engine.resetCache()) so the two stay in sync. */
|
|
422
438
|
reset(): void;
|
|
439
|
+
/** Snapshot the conversation - the engine's KV cache plus the chat's committed-transcript
|
|
440
|
+
* bookkeeping - as one structured-cloneable object. Persist it (IndexedDB / OPFS) or ship it
|
|
441
|
+
* to another worker; restoring it into a chat on the same model and `kvCache` mode makes the
|
|
442
|
+
* next clean-append turn extend the cache exactly as if the conversation never stopped (no
|
|
443
|
+
* re-prefill). Returns null when no conversation is committed. Queues behind in-flight turns
|
|
444
|
+
* like send/stream. */
|
|
445
|
+
save(): Promise<ChatSnapshot | null>;
|
|
446
|
+
/** Replace the current conversation with a saved snapshot (see {@link Chat.save}). Throws when
|
|
447
|
+
* the snapshot does not match this engine's model or `kvCache` mode. */
|
|
448
|
+
restore(snapshot: ChatSnapshot): Promise<void>;
|
|
423
449
|
/** The model's end-of-sequence token id. */
|
|
424
450
|
readonly eosTokenId: number;
|
|
425
451
|
/** Escape hatch: encode/decode/applyChatTemplate for callers that need the text boundary. */
|
|
@@ -428,5 +454,5 @@ interface Chat {
|
|
|
428
454
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
429
455
|
declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
|
|
430
456
|
//#endregion
|
|
431
|
-
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, ToolBodyMachine, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
|
|
457
|
+
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatSnapshot, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, ToolBodyMachine, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
|
|
432
458
|
//# sourceMappingURL=chat.d.ts.map
|
package/dist/chat.js
CHANGED
|
@@ -5683,6 +5683,27 @@ async function createChat(engine, options) {
|
|
|
5683
5683
|
resetEpoch++;
|
|
5684
5684
|
dropCache();
|
|
5685
5685
|
},
|
|
5686
|
+
save: serialize(async () => {
|
|
5687
|
+
if (committed === null) return null;
|
|
5688
|
+
const eng = await engine.saveCache();
|
|
5689
|
+
if (!eng) return null;
|
|
5690
|
+
return {
|
|
5691
|
+
version: 1,
|
|
5692
|
+
engine: eng,
|
|
5693
|
+
committed: JSON.parse(JSON.stringify(committed)),
|
|
5694
|
+
cacheEndsAtEos,
|
|
5695
|
+
toolsKey: committedToolsKey
|
|
5696
|
+
};
|
|
5697
|
+
}),
|
|
5698
|
+
restore: serialize(async (snap) => {
|
|
5699
|
+
if (!snap || snap.version !== 1) throw new Error("bitgpu/chat: unsupported chat snapshot version");
|
|
5700
|
+
if (!Array.isArray(snap.committed) || snap.committed.length === 0) throw new Error("bitgpu/chat: chat snapshot holds no committed transcript");
|
|
5701
|
+
await engine.restoreCache(snap.engine);
|
|
5702
|
+
resetEpoch++;
|
|
5703
|
+
committed = JSON.parse(JSON.stringify(snap.committed));
|
|
5704
|
+
committedToolsKey = snap.toolsKey ?? null;
|
|
5705
|
+
cacheEndsAtEos = !!snap.cacheEndsAtEos;
|
|
5706
|
+
}),
|
|
5686
5707
|
eosTokenId: tk.eosTokenId,
|
|
5687
5708
|
tokenizer: tk
|
|
5688
5709
|
};
|