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/README.md CHANGED
@@ -19,6 +19,32 @@ npm install bitgpu
19
19
 
20
20
  ESM-only, zero runtime dependencies.
21
21
 
22
+ ## Quickstart - no conversion, no hosting
23
+
24
+ Ready-made manifests for all three Bonsai sizes are committed under [`models/`](models/); the
25
+ weights stream straight from the Hugging Face Hub. This runs as-is:
26
+
27
+ ```ts
28
+ import { createEngine } from 'bitgpu'
29
+ import { createChat } from 'bitgpu/chat'
30
+
31
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.7.0/models/bonsai-1.7b'
32
+ const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
33
+ const engine = await createEngine({
34
+ manifestUrl: `${REPO}/manifest.json`,
35
+ auxUrl: `${REPO}/bonsai.aux.bin`,
36
+ dataUrl: `${HF}/onnx/model_q1.onnx_data`,
37
+ })
38
+ const chat = await createChat(engine, {
39
+ tokenizerJsonUrl: `${HF}/tokenizer.json`,
40
+ tokenizerConfigUrl: `${HF}/tokenizer_config.json`,
41
+ })
42
+ await chat.send([{ role: 'user', content: 'Hi!' }], { onText: (t) => process.stdout.write(t) })
43
+ ```
44
+
45
+ Or just open the single-file demo: [`examples/chat.html`](examples/chat.html) - model picker,
46
+ streaming chat, and guaranteed-valid JSON mode, entirely on-device.
47
+
22
48
  ## Usage
23
49
 
24
50
  ```ts
@@ -47,11 +73,67 @@ console.log(result.tokens, result.tokensPerSecond)
47
73
  // Sampling (matches transformers.js v4.2.0 exactly): set a temperature other than 0/1.
48
74
  await engine.generate(promptTokenIds, { temperature: 0.5, topK: 20, repetitionPenalty: 1.15 })
49
75
 
76
+ // Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
77
+ // exactly like transformers.js greedy search:
78
+ await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
79
+
50
80
  engine.dispose()
51
81
  ```
52
82
 
53
- Tokenization is intentionally out of scope: the engine operates on token ids, so you can pair it
54
- with any tokenizer.
83
+ ## Chat (`bitgpu/chat`)
84
+
85
+ The engine is deliberately ids-in/ids-out; `bitgpu/chat` is the batteries-included text layer on
86
+ top of it - messages in, streamed text out, still entirely on-device:
87
+
88
+ ```ts
89
+ import { createEngine } from 'bitgpu'
90
+ import { createChat } from 'bitgpu/chat'
91
+
92
+ const engine = await createEngine({ modelUrl })
93
+ const chat = await createChat(engine, { modelUrl }) // tokenizer files live next to the manifest
94
+
95
+ // Callback streaming:
96
+ const r = await chat.send(
97
+ [{ role: 'user', content: 'Explain WebGPU in one sentence.' }],
98
+ { onText: (delta) => ui.append(delta) },
99
+ )
100
+
101
+ // ...or async-generator streaming (the final result is the generator's return value):
102
+ const it = chat.stream(messages, { temperature: 0.5, topK: 20 })
103
+ for (let n = await it.next(); !n.done; n = await it.next()) ui.append(n.value)
104
+ ```
105
+
106
+ It owns the whole pipeline the engine leaves to the caller: the model's own Jinja chat template,
107
+ tokenization, UTF-8-safe incremental decode streaming, `<think>` block routing (`think: true`
108
+ streams reasoning to `onThink`, never into the reply), EOS handling, and cross-turn KV-cache
109
+ reuse with exact token bookkeeping (a clean follow-up turn prefills only the delta;
110
+ `chat.prewarm(messages)` warms a static system prompt at load). `chat.reset()` forgets the
111
+ conversation.
112
+
113
+ ### Guaranteed-valid JSON (`format: 'json'`)
114
+
115
+ ```ts
116
+ const r = await chat.send(
117
+ [{ role: 'user', content: 'Describe France as JSON: capital (string), population_millions (number).' }],
118
+ { format: 'json' },
119
+ )
120
+ JSON.parse(r.text) // never throws when finishReason === 'stop'
121
+ ```
122
+
123
+ Constrained decoding: every candidate token is validated against an incremental byte-level JSON
124
+ machine before it can be sampled, so the reply is structurally guaranteed to be one complete,
125
+ valid JSON value (object or array root) - small 1-bit models free-form JSON unreliably, and this
126
+ removes that failure class entirely. Generation ends when the root value closes
127
+ (`finishReason: 'length'` means `maxTokens` cut it short - raise it). The constraint is
128
+ structural, not semantic: prompt for the shape you want. Built on the engine's generic
129
+ `candidateFilter` hook (see `GenerateOptions`), which is open for custom grammars.
130
+
131
+ The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
132
+ see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
133
+ engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
134
+ `bitgpu` never loads any chat code. Rendering and encoding are verified byte-exact against
135
+ transformers.js (`npm run test:chat`), and the GPU gate proves the reuse path bit-exact on real
136
+ hardware. Prefer your own tokenizer? Skip `bitgpu/chat` entirely - the engine API is unchanged.
55
137
 
56
138
  ## Bring your own model
57
139
 
@@ -76,9 +158,13 @@ createEngine({
76
158
  ```
77
159
 
78
160
  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).
161
+ recipe (silu/SwiGLU, head_dim <= 128, 128-wide scale blocks, tied or untied lm_head) - the
162
+ engine validates the manifest loudly at load. The reference exports are
163
+ [onnx-community/Bonsai-1.7B-ONNX](https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX),
164
+ [Bonsai-4B-ONNX](https://huggingface.co/onnx-community/Bonsai-4B-ONNX) and
165
+ [Bonsai-8B-ONNX](https://huggingface.co/onnx-community/Bonsai-8B-ONNX) (`onnx/model_q1.onnx` +
166
+ its data file). Format spec: [docs/FORMAT.md](docs/FORMAT.md); the full pipeline including
167
+ regenerating the verification fixtures for a new model: [tools/README.md](tools/README.md).
82
168
 
83
169
  ## API
84
170
 
@@ -128,6 +214,7 @@ npm run build # tsdown -> dist (ESM + .d.ts)
128
214
  npm run typecheck
129
215
  npm run test:sampler # sampler parity vs transformers.js v4.2.0
130
216
  npm run test:pld # prompt-lookup drafter unit checks
217
+ npm run test:chat # bitgpu/chat: stream logic, orchestration, template/encode parity vs transformers.js
131
218
  npm run check:publish # publint + are-the-types-wrong
132
219
  ```
133
220
 
@@ -144,23 +231,27 @@ model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~
144
231
  ```sh
145
232
  ln -s /path/to/bonsai-model examples/model # or copy the files in
146
233
  npm run build
147
- python3 -m http.server 8000 # serve the repo root
148
- npm run verify:headless # drives system Chrome headlessly (WebGPU/Metal)
234
+ npm run verify:headless # serves the repo itself + drives system Chrome headlessly
149
235
  ```
150
236
 
151
- Or open `http://localhost:8000/examples/verify.html` in a WebGPU browser and click Run. Run this
152
- gate on real hardware before every release; CI covers only the CPU-checkable parts (types, sampler
153
- math, drafter, packaging).
237
+ Or serve the repo root (`python3 -m http.server 8000`) and open
238
+ `http://localhost:8000/examples/verify.html` in a WebGPU browser and click Run. Run this gate on
239
+ real hardware before every release; CI covers only the CPU-checkable parts (types, sampler math,
240
+ drafter, chat, packaging). The headless driver also runs the baseline model once with
241
+ `?nosg=1` (the no-subgroup workgroup-reduction fallback used on Firefox and older adapters), so
242
+ that path is release-gated too - it is bit-identical to the subgroup path on the committed
243
+ known-good ids.
154
244
 
155
245
  The gate is model-parametric: `verify.html?model=<tag>` loads `examples/model-<tag>` against
156
246
  `test-fixtures/forward-<tag>`, and the headless driver automatically runs every staged variant.
157
247
  Fixture sets for all three Bonsai sizes are committed - `forward` (1.7B, hidden 2048),
158
248
  `forward-4b` (4B, hidden 2560) and `forward-8b` (8B, hidden 4096, untied lm_head, raised
159
249
  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`.
250
+ weights with `ln -s /path/to/bonsai-<size> examples/model-<size>`. The chat-layer checks need
251
+ `tokenizer.json` + `tokenizer_config.json` in the staged model dir and skip loudly when absent.
252
+ To add fixtures for another model, run `tools/golden.py` then
253
+ `tools/reference.py --dump test-fixtures/forward-<tag>` on the converted work dir and record the
254
+ engine's greedy continuation as `known_good` in that set's `params.json`.
164
255
 
165
256
  ### Releasing
166
257
 
@@ -0,0 +1,19 @@
1
+ # Third-party licenses
2
+
3
+ The `bitgpu/chat` entry point (`dist/chat.js`) bundles the following packages at build
4
+ time so the published package has zero runtime dependencies. The core `bitgpu` entry
5
+ (`dist/index.js`) contains no third-party code.
6
+
7
+ ## @huggingface/tokenizers
8
+
9
+ - Copyright (c) Hugging Face
10
+ - License: Apache License 2.0 — <https://github.com/huggingface/tokenizers-js/blob/main/LICENSE>
11
+ - Source: <https://www.npmjs.com/package/@huggingface/tokenizers>
12
+
13
+ ## @huggingface/jinja
14
+
15
+ - Copyright (c) Hugging Face
16
+ - License: Apache License 2.0 — <https://github.com/huggingface/huggingface.js/blob/main/LICENSE>
17
+ - Source: <https://www.npmjs.com/package/@huggingface/jinja>
18
+
19
+ The full Apache License 2.0 text: <https://www.apache.org/licenses/LICENSE-2.0>
package/dist/chat.d.ts ADDED
@@ -0,0 +1,204 @@
1
+ import { n as Engine, o as GenerateOptions } from "./types-CsoJYJlG.js";
2
+
3
+ //#region src/chat/tokenizer.d.ts
4
+ interface ChatMessage {
5
+ role: 'system' | 'user' | 'assistant' | (string & {});
6
+ content: string;
7
+ }
8
+ /** Incremental decoder for streaming generation: feed token ids as they arrive, get the newly
9
+ * stable visible text each step. Re-decodes the running sequence and emits the delta, holding
10
+ * back a trailing incomplete multi-byte character (which byte-level BPE decodes as U+FFFD)
11
+ * until its remaining tokens arrive. */
12
+ interface DecoderStream {
13
+ push(tokenId: number): string;
14
+ flush(): string;
15
+ }
16
+ declare class ChatTokenizer {
17
+ private readonly tok;
18
+ private readonly template;
19
+ private readonly templateContext;
20
+ /** End-of-sequence token id (e.g. <|im_end|> for Qwen3-family models). */
21
+ readonly eosTokenId: number;
22
+ /** The eos token's string form (used to reconstruct the template's turn terminator). */
23
+ readonly eosToken: string;
24
+ constructor(tokenizerJson: unknown, tokenizerConfig: Record<string, unknown>);
25
+ /** Encode text to token ids. `addSpecialTokens` defaults to false: the chat template already
26
+ * inserts the control tokens, so prompt/delta encoding must not add more. */
27
+ encode(text: string, addSpecialTokens?: boolean): number[];
28
+ /** Decode token ids to text. `skipSpecialTokens` defaults to true (never surface control tokens). */
29
+ decode(ids: number[], skipSpecialTokens?: boolean): string;
30
+ /** The raw vocab string for a token id (byte-alias space for byte-level BPE). */
31
+ idToToken(id: number): string | undefined;
32
+ /** Ids of all added tokens (ChatML markers, <think>, etc.) - never plain content. */
33
+ addedTokenIds(): Set<number>;
34
+ get hasChatTemplate(): boolean;
35
+ /** Render a message list to a prompt string via the model's own Jinja chat template
36
+ * (matches transformers.js apply_chat_template byte-exactly). */
37
+ applyChatTemplate(messages: ChatMessage[], opts?: {
38
+ addGenerationPrompt?: boolean;
39
+ enableThinking?: boolean;
40
+ }): string;
41
+ createDecoderStream(skipSpecialTokens?: boolean): DecoderStream;
42
+ }
43
+ //#endregion
44
+ //#region src/chat/think.d.ts
45
+ interface SplitChunk {
46
+ /** Visible reply text (outside any tag pair). */
47
+ text: string;
48
+ /** Content inside the tag pair (the model's reasoning), without the tags themselves. */
49
+ think: string;
50
+ }
51
+ declare class ThinkSplitter {
52
+ private readonly open;
53
+ private readonly close;
54
+ private inside;
55
+ private hold;
56
+ constructor(open?: string, close?: string);
57
+ push(chunk: string): SplitChunk;
58
+ /** Emit whatever is held back. An unterminated think block (generation hit maxTokens inside it)
59
+ * flushes to the think channel, never to the visible reply. */
60
+ flush(): SplitChunk;
61
+ }
62
+ /** Stream-safe stop-sequence scanner: emits visible text up to (excluding) the earliest match of
63
+ * any stop string, holding back chunk-edge suffixes that could begin one (stops can straddle
64
+ * token boundaries). Once matched, everything further is swallowed. */
65
+ declare class StopScanner {
66
+ private readonly stops;
67
+ matched: boolean;
68
+ private hold;
69
+ constructor(stops: readonly string[]);
70
+ push(text: string): string;
71
+ flush(): string;
72
+ }
73
+ //#endregion
74
+ //#region src/chat/json.d.ts
75
+ declare class JsonMachine {
76
+ private stack;
77
+ private phase;
78
+ private isKey;
79
+ private uLeft;
80
+ private utf8Left;
81
+ private numSub;
82
+ private litWord;
83
+ private litPos;
84
+ clone(): JsonMachine;
85
+ get complete(): boolean;
86
+ /** Feed bytes; false = the text stopped being a valid JSON prefix (state is then undefined). */
87
+ feed(bytes: Uint8Array): boolean;
88
+ private openValue;
89
+ private closeValue;
90
+ private closeContainer;
91
+ private byte;
92
+ }
93
+ //#endregion
94
+ //#region src/chat/index.d.ts
95
+ /** Options for {@link createChat}. Point it at the model directory (which already hosts
96
+ * tokenizer.json + tokenizer_config.json next to the manifest), at explicit URLs, or at
97
+ * preloaded JSON (bring your own caching, e.g. OPFS). */
98
+ interface ChatOptions {
99
+ /** Directory holding tokenizer.json + tokenizer_config.json (usually the same modelUrl passed
100
+ * to createEngine). */
101
+ modelUrl?: string;
102
+ /** Explicit URLs (when the tokenizer files live elsewhere than the weights). */
103
+ tokenizerJsonUrl?: string;
104
+ tokenizerConfigUrl?: string;
105
+ /** Preloaded tokenizer files (skips fetching entirely). */
106
+ tokenizer?: {
107
+ json: unknown;
108
+ config: Record<string, unknown>;
109
+ };
110
+ /** Override fetching (custom caching / retries). Defaults to fetch + res.json(). */
111
+ fetchJson?: (url: string) => Promise<unknown>;
112
+ }
113
+ /** Per-turn options. Sampling fields pass through to the engine (same semantics as
114
+ * {@link GenerateOptions}); the rest control the chat layer. */
115
+ interface ChatSendOptions {
116
+ maxTokens?: number;
117
+ temperature?: number;
118
+ topK?: number;
119
+ topP?: number;
120
+ repetitionPenalty?: number;
121
+ noRepeatNgramSize?: number;
122
+ seed?: number;
123
+ promptLookup?: GenerateOptions['promptLookup'];
124
+ /** Extra stop token ids, in addition to the model's eos. */
125
+ stopTokens?: number[];
126
+ /** Stop STRINGS: generation ends when the visible reply contains one (matched across token
127
+ * boundaries); the stop text and anything after it is never emitted, and `finishReason` is
128
+ * 'stop'. A stop-sequence turn drops the KV cache afterwards (the cache holds a short token
129
+ * overrun past the cut). */
130
+ stopSequences?: string[];
131
+ /** Called when the prompt alone exceeds the engine's KV window (maxSeqLen). Return a trimmed
132
+ * message list to retry ONCE with (a clean full prefill), or null to rethrow the error. Pair
133
+ * with {@link Chat.countTokens} to implement the trim policy. */
134
+ onOverflow?: (info: {
135
+ promptTokenCount: number;
136
+ maxSeqLen: number;
137
+ }) => ChatMessage[] | null;
138
+ signal?: AbortSignal;
139
+ /** Render the template with enable_thinking and let the model reason. Think content streams to
140
+ * `onThink` and lands in `result.thinkText`; it never appears in the visible reply. A think
141
+ * turn drops the KV cache afterwards (the stripped reply cannot reproduce the cached tokens).
142
+ * Default false. */
143
+ think?: boolean;
144
+ /** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
145
+ onText?: (delta: string) => void;
146
+ /** Streamed think content (only meaningful with `think: true`). */
147
+ onThink?: (delta: string) => void;
148
+ /** Reuse the KV cache when this turn is a clean append to the previous one (the committed
149
+ * conversation plus one new user turn). Default true; set false to force a full prefill. */
150
+ reuseCache?: boolean;
151
+ /** Constrained decoding. `'json'` guarantees the reply is one complete, valid JSON value with
152
+ * an object or array root: every generated token is validated against an incremental JSON
153
+ * machine (invalid candidates are never sampled), and generation ends when the root value
154
+ * closes. Check `finishReason === 'stop'` - `'length'` means maxTokens cut the value short.
155
+ * Forces `think: false` and disables `promptLookup`. Constraint is structural, not semantic:
156
+ * prompt for the shape you want; this makes the output PARSE, not make sense. */
157
+ format?: 'json';
158
+ }
159
+ interface ChatResult {
160
+ /** The visible reply (think blocks removed). */
161
+ text: string;
162
+ /** Content of <think> blocks, when the model emitted any. */
163
+ thinkText: string;
164
+ /** Generated token ids (as returned by the engine; excludes the prompt). */
165
+ tokens: number[];
166
+ /** The exact token ids fed to the engine this turn (the full prompt, or the reuse delta). */
167
+ inputTokenIds: number[];
168
+ /** Why generation ended. */
169
+ finishReason: 'stop' | 'length' | 'abort';
170
+ /** True when this turn extended the KV cache instead of a full prefill. */
171
+ reusedCache: boolean;
172
+ prefillMs: number;
173
+ decodeMs: number;
174
+ tokensPerSecond: number;
175
+ }
176
+ interface Chat {
177
+ /** Generate a reply for the message list. Resolves with the full result; stream text via
178
+ * `onText`. Turns are serialized: overlapping calls queue instead of interleaving. */
179
+ send(messages: ChatMessage[], options?: ChatSendOptions): Promise<ChatResult>;
180
+ /** Generate a reply as an async generator of visible-text deltas; the final {@link ChatResult}
181
+ * is the generator's return value: `const it = chat.stream(msgs); for await (const d of it) ...` */
182
+ stream(messages: ChatMessage[], options?: ChatSendOptions): AsyncGenerator<string, ChatResult>;
183
+ /** Prefill a message prefix (e.g. the static system prompt) into the KV cache without decoding,
184
+ * so the first real turn is a cheap cache-append instead of a cold full prefill. */
185
+ prewarm(messages: ChatMessage[]): Promise<void>;
186
+ /** Token count of the rendered prompt for a message list (chat template applied) - use for
187
+ * window budgeting against `engine.capabilities.maxSeqLen`, e.g. in an onOverflow policy. */
188
+ countTokens(messages: ChatMessage[], opts?: {
189
+ addGenerationPrompt?: boolean;
190
+ think?: boolean;
191
+ }): number;
192
+ /** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
193
+ * Use this (not engine.resetCache()) so the two stay in sync. */
194
+ reset(): void;
195
+ /** The model's end-of-sequence token id. */
196
+ readonly eosTokenId: number;
197
+ /** Escape hatch: encode/decode/applyChatTemplate for callers that need the text boundary. */
198
+ readonly tokenizer: ChatTokenizer;
199
+ }
200
+ /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
201
+ declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
202
+ //#endregion
203
+ export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, StopScanner, ThinkSplitter, createChat };
204
+ //# sourceMappingURL=chat.d.ts.map