bitgpu 0.9.0 → 0.10.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 +62 -3
- 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 +174 -35
- package/dist/index.js.map +1 -1
- package/dist/{types-C5f2IKgm.d.ts → types-CcgsXirU.d.ts} +54 -12
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -6,7 +6,9 @@ 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, and conversation snapshots (save/restore across page reloads). Runs the
|
|
11
|
+
fast subgroup path on Apple / NVIDIA /
|
|
10
12
|
recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU is available.
|
|
11
13
|
Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
|
|
12
14
|
only when that model needs it and smaller models keep running at WebGPU's guaranteed minimums.
|
|
@@ -31,7 +33,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
|
|
|
31
33
|
import { createEngine } from 'bitgpu'
|
|
32
34
|
import { createChat } from 'bitgpu/chat'
|
|
33
35
|
|
|
34
|
-
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.
|
|
36
|
+
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.10.0/models/bonsai-1.7b'
|
|
35
37
|
const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
|
|
36
38
|
const engine = await createEngine({
|
|
37
39
|
manifestUrl: `${REPO}/manifest.json`,
|
|
@@ -84,6 +86,35 @@ await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSi
|
|
|
84
86
|
engine.dispose()
|
|
85
87
|
```
|
|
86
88
|
|
|
89
|
+
### KV cache modes (`kvCache`)
|
|
90
|
+
|
|
91
|
+
The KV cache is what grows with conversation length (~224 KB per position at f32 on
|
|
92
|
+
Bonsai-1.7B; `maxSeqLen` caps it). `kvCache` selects its **storage** precision - attention
|
|
93
|
+
arithmetic always stays f32, values are compressed once at cache-write:
|
|
94
|
+
|
|
95
|
+
| Mode | Bytes/value | KV memory | Requires |
|
|
96
|
+
| --- | --- | --- | --- |
|
|
97
|
+
| `'f32'` (default) | 4 | 1x | - |
|
|
98
|
+
| `'f16'` | 2 | 1/2 | `shader-f16` (silently falls back to f32 without it) |
|
|
99
|
+
| `'q8'` | ~1.125 | ~1/4 | nothing - works on every WebGPU adapter |
|
|
100
|
+
|
|
101
|
+
```ts
|
|
102
|
+
const engine = await createEngine({ modelUrl, kvCache: 'q8', maxSeqLen: 4096 })
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
`'q8'` stores 8-bit values with one f32 scale per 32-element block (llama.cpp q8_0-style, the
|
|
106
|
+
tier the wider ecosystem treats as near-lossless). Within any mode decoding stays exact and
|
|
107
|
+
deterministic (same seed -> same tokens, cache reuse == full prefill), but f16/q8 outputs are
|
|
108
|
+
**not guaranteed bit-identical to f32** - they are measured instead: the GPU gate compares
|
|
109
|
+
greedy continuations against f32 on every Bonsai size and both kernel paths, and q8 currently
|
|
110
|
+
agrees 96/96 tokens on short prompts, 24/24 after a 400-token prompt and 48/48 after a
|
|
111
|
+
1500-token prompt (logits cosine >= 0.99997). Long contexts also get *faster* under q8 - decode
|
|
112
|
+
at 1500 tokens of depth measured 37-58% quicker than f32 (attention there is memory-bound and
|
|
113
|
+
reads a quarter of the bytes) - while shallow-context decode measures a few percent slower.
|
|
114
|
+
Reach for `'q8'` to run a 4x longer window in the same VRAM (or the same window on smaller
|
|
115
|
+
GPUs); keep the default `'f32'` when bit-exact reproducibility is the point.
|
|
116
|
+
`engine.capabilities.kvCache` reports what is actually active.
|
|
117
|
+
|
|
87
118
|
## Chat (`bitgpu/chat`)
|
|
88
119
|
|
|
89
120
|
The engine is deliberately ids-in/ids-out; `bitgpu/chat` is the batteries-included text layer on
|
|
@@ -210,6 +241,28 @@ needed, and validate argument *values* in your executor. The engine never execut
|
|
|
210
241
|
never loops, never retries: it returns a validated call and the app stays in charge (there is
|
|
211
242
|
deliberately no agent framework in here).
|
|
212
243
|
|
|
244
|
+
### Conversation snapshots (`save` / `restore`)
|
|
245
|
+
|
|
246
|
+
`chat.save()` captures the whole conversation - the engine's KV cache plus the chat's exact
|
|
247
|
+
token bookkeeping - as one structured-cloneable object; `chat.restore(snapshot)` brings it back,
|
|
248
|
+
so the next turn extends the cache as if the session never ended (no re-prefill of the history):
|
|
249
|
+
|
|
250
|
+
```ts
|
|
251
|
+
const snapshot = await chat.save() // structured-cloneable: IndexedDB / OPFS / postMessage
|
|
252
|
+
// (NOT JSON.stringify - the KV buffer would be lost)
|
|
253
|
+
// ...page reload: new engine + chat on the same model and kvCache mode...
|
|
254
|
+
await chat.restore(snapshot)
|
|
255
|
+
await chat.send([...savedMessages, { role: 'user', content: 'as I was saying...' }]) // cache reuse
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Use it for instant conversation switching (save several, restore the active one) and for
|
|
259
|
+
resuming after a reload without re-prefilling a long history. Restore validates the model
|
|
260
|
+
architecture and `kvCache` mode and throws on mismatch; restoring is bit-identical to having
|
|
261
|
+
kept the conversation alive (gated on real hardware). Snapshot size scales with the KV mode
|
|
262
|
+
(~224 / 112 / 63 KB per cached token on Bonsai-1.7B at f32 / f16 / q8), which makes
|
|
263
|
+
`kvCache: 'q8'` the natural companion. The engine-level `engine.saveCache()` /
|
|
264
|
+
`engine.restoreCache()` are the same thing for ids-in/ids-out callers.
|
|
265
|
+
|
|
213
266
|
The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
|
|
214
267
|
see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
|
|
215
268
|
engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
|
|
@@ -261,6 +314,10 @@ regenerating the verification fixtures for a new model: [tools/README.md](tools/
|
|
|
261
314
|
later `generate(delta, { reuseCache: true })` starts from a warm cache (e.g. a static system prompt).
|
|
262
315
|
- `engine.forward(tokenIds)` - single forward pass (hidden states + logits) for correctness checks.
|
|
263
316
|
- `engine.resetCache()` - clear the cross-turn KV cache (start a fresh conversation).
|
|
317
|
+
- `engine.saveCache()` / `engine.restoreCache(snapshot)` - snapshot the conversation (KV cache
|
|
318
|
+
contents + token history) as one structured-cloneable object and bring it back later,
|
|
319
|
+
bit-identically - into this engine or a fresh one on the same model and `kvCache` mode. See
|
|
320
|
+
the chat-layer `save()`/`restore()` below for the batteries-included version.
|
|
264
321
|
- `engine.capabilities` - detected GPU path (`useSubgroups`, `subgroupSize`, adapter info, limits).
|
|
265
322
|
- `engine.lost` - promise that resolves if the GPU device is lost (also via `onDeviceLost` option);
|
|
266
323
|
create a new engine to recover.
|
|
@@ -310,7 +367,9 @@ npm run check:publish # publint + are-the-types-wrong
|
|
|
310
367
|
|
|
311
368
|
`examples/verify.html` re-runs the full bit-exactness + throughput suite (forward cosines vs the
|
|
312
369
|
committed reference fixtures in `test-fixtures/forward/`, known-good greedy ids, sampler kernel
|
|
313
|
-
parity, determinism, KV reuse/growth, prompt-lookup identity
|
|
370
|
+
parity, determinism, KV reuse/growth, prompt-lookup identity, KV snapshot save/restore round
|
|
371
|
+
trips - including into a fresh engine - and the f16/q8 KV-mode sections: within-mode exactness
|
|
372
|
+
plus greedy agreement vs f32 out to a 1500-token prompt) against the **built package** and
|
|
314
373
|
prints `PACKAGE OK` or `REGRESSION`.
|
|
315
374
|
|
|
316
375
|
It needs model weights, which are not committed. Point `examples/model` at a directory holding the
|
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-CcgsXirU.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
|
};
|