bitgpu 0.5.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.
package/README.md CHANGED
@@ -47,11 +47,49 @@ console.log(result.tokens, result.tokensPerSecond)
47
47
  // Sampling (matches transformers.js v4.2.0 exactly): set a temperature other than 0/1.
48
48
  await engine.generate(promptTokenIds, { temperature: 0.5, topK: 20, repetitionPenalty: 1.15 })
49
49
 
50
+ // Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
51
+ // exactly like transformers.js greedy search:
52
+ await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
53
+
50
54
  engine.dispose()
51
55
  ```
52
56
 
53
- Tokenization is intentionally out of scope: the engine operates on token ids, so you can pair it
54
- with any tokenizer.
57
+ ## Chat (`bitgpu/chat`)
58
+
59
+ The engine is deliberately ids-in/ids-out; `bitgpu/chat` is the batteries-included text layer on
60
+ top of it - messages in, streamed text out, still entirely on-device:
61
+
62
+ ```ts
63
+ import { createEngine } from 'bitgpu'
64
+ import { createChat } from 'bitgpu/chat'
65
+
66
+ const engine = await createEngine({ modelUrl })
67
+ const chat = await createChat(engine, { modelUrl }) // tokenizer files live next to the manifest
68
+
69
+ // Callback streaming:
70
+ const r = await chat.send(
71
+ [{ role: 'user', content: 'Explain WebGPU in one sentence.' }],
72
+ { onText: (delta) => ui.append(delta) },
73
+ )
74
+
75
+ // ...or async-generator streaming (the final result is the generator's return value):
76
+ const it = chat.stream(messages, { temperature: 0.5, topK: 20 })
77
+ for (let n = await it.next(); !n.done; n = await it.next()) ui.append(n.value)
78
+ ```
79
+
80
+ It owns the whole pipeline the engine leaves to the caller: the model's own Jinja chat template,
81
+ tokenization, UTF-8-safe incremental decode streaming, `<think>` block routing (`think: true`
82
+ streams reasoning to `onThink`, never into the reply), EOS handling, and cross-turn KV-cache
83
+ reuse with exact token bookkeeping (a clean follow-up turn prefills only the delta;
84
+ `chat.prewarm(messages)` warms a static system prompt at load). `chat.reset()` forgets the
85
+ conversation.
86
+
87
+ The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
88
+ see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
89
+ engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
90
+ `bitgpu` never loads any chat code. Rendering and encoding are verified byte-exact against
91
+ transformers.js (`npm run test:chat`), and the GPU gate proves the reuse path bit-exact on real
92
+ hardware. Prefer your own tokenizer? Skip `bitgpu/chat` entirely - the engine API is unchanged.
55
93
 
56
94
  ## Bring your own model
57
95
 
@@ -76,9 +114,13 @@ createEngine({
76
114
  ```
77
115
 
78
116
  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).
117
+ recipe (silu/SwiGLU, head_dim <= 128, 128-wide scale blocks, tied or untied lm_head) - the
118
+ engine validates the manifest loudly at load. The reference exports are
119
+ [onnx-community/Bonsai-1.7B-ONNX](https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX),
120
+ [Bonsai-4B-ONNX](https://huggingface.co/onnx-community/Bonsai-4B-ONNX) and
121
+ [Bonsai-8B-ONNX](https://huggingface.co/onnx-community/Bonsai-8B-ONNX) (`onnx/model_q1.onnx` +
122
+ its data file). Format spec: [docs/FORMAT.md](docs/FORMAT.md); the full pipeline including
123
+ regenerating the verification fixtures for a new model: [tools/README.md](tools/README.md).
82
124
 
83
125
  ## API
84
126
 
@@ -128,6 +170,7 @@ npm run build # tsdown -> dist (ESM + .d.ts)
128
170
  npm run typecheck
129
171
  npm run test:sampler # sampler parity vs transformers.js v4.2.0
130
172
  npm run test:pld # prompt-lookup drafter unit checks
173
+ npm run test:chat # bitgpu/chat: stream logic, orchestration, template/encode parity vs transformers.js
131
174
  npm run check:publish # publint + are-the-types-wrong
132
175
  ```
133
176
 
@@ -157,10 +200,11 @@ The gate is model-parametric: `verify.html?model=<tag>` loads `examples/model-<t
157
200
  Fixture sets for all three Bonsai sizes are committed - `forward` (1.7B, hidden 2048),
158
201
  `forward-4b` (4B, hidden 2560) and `forward-8b` (8B, hidden 4096, untied lm_head, raised
159
202
  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`.
203
+ weights with `ln -s /path/to/bonsai-<size> examples/model-<size>`. The chat-layer checks need
204
+ `tokenizer.json` + `tokenizer_config.json` in the staged model dir and skip loudly when absent.
205
+ To add fixtures for another model, run `tools/golden.py` then
206
+ `tools/reference.py --dump test-fixtures/forward-<tag>` on the converted work dir and record the
207
+ engine's greedy continuation as `known_good` in that set's `params.json`.
164
208
 
165
209
  ### Releasing
166
210
 
@@ -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,144 @@
1
+ import { n as Engine, o as GenerateOptions } from "./types-C3FWn4rd.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
+ get hasChatTemplate(): boolean;
31
+ /** Render a message list to a prompt string via the model's own Jinja chat template
32
+ * (matches transformers.js apply_chat_template byte-exactly). */
33
+ applyChatTemplate(messages: ChatMessage[], opts?: {
34
+ addGenerationPrompt?: boolean;
35
+ enableThinking?: boolean;
36
+ }): string;
37
+ createDecoderStream(skipSpecialTokens?: boolean): DecoderStream;
38
+ }
39
+ //#endregion
40
+ //#region src/chat/think.d.ts
41
+ interface SplitChunk {
42
+ /** Visible reply text (outside any tag pair). */
43
+ text: string;
44
+ /** Content inside the tag pair (the model's reasoning), without the tags themselves. */
45
+ think: string;
46
+ }
47
+ declare class ThinkSplitter {
48
+ private readonly open;
49
+ private readonly close;
50
+ private inside;
51
+ private hold;
52
+ constructor(open?: string, close?: string);
53
+ push(chunk: string): SplitChunk;
54
+ /** Emit whatever is held back. An unterminated think block (generation hit maxTokens inside it)
55
+ * flushes to the think channel, never to the visible reply. */
56
+ flush(): SplitChunk;
57
+ }
58
+ //#endregion
59
+ //#region src/chat/index.d.ts
60
+ /** Options for {@link createChat}. Point it at the model directory (which already hosts
61
+ * tokenizer.json + tokenizer_config.json next to the manifest), at explicit URLs, or at
62
+ * preloaded JSON (bring your own caching, e.g. OPFS). */
63
+ interface ChatOptions {
64
+ /** Directory holding tokenizer.json + tokenizer_config.json (usually the same modelUrl passed
65
+ * to createEngine). */
66
+ modelUrl?: string;
67
+ /** Explicit URLs (when the tokenizer files live elsewhere than the weights). */
68
+ tokenizerJsonUrl?: string;
69
+ tokenizerConfigUrl?: string;
70
+ /** Preloaded tokenizer files (skips fetching entirely). */
71
+ tokenizer?: {
72
+ json: unknown;
73
+ config: Record<string, unknown>;
74
+ };
75
+ /** Override fetching (custom caching / retries). Defaults to fetch + res.json(). */
76
+ fetchJson?: (url: string) => Promise<unknown>;
77
+ }
78
+ /** Per-turn options. Sampling fields pass through to the engine (same semantics as
79
+ * {@link GenerateOptions}); the rest control the chat layer. */
80
+ interface ChatSendOptions {
81
+ maxTokens?: number;
82
+ temperature?: number;
83
+ topK?: number;
84
+ topP?: number;
85
+ repetitionPenalty?: number;
86
+ noRepeatNgramSize?: number;
87
+ seed?: number;
88
+ promptLookup?: GenerateOptions['promptLookup'];
89
+ /** Extra stop token ids, in addition to the model's eos. */
90
+ stopTokens?: number[];
91
+ signal?: AbortSignal;
92
+ /** Render the template with enable_thinking and let the model reason. Think content streams to
93
+ * `onThink` and lands in `result.thinkText`; it never appears in the visible reply. A think
94
+ * turn drops the KV cache afterwards (the stripped reply cannot reproduce the cached tokens).
95
+ * Default false. */
96
+ think?: boolean;
97
+ /** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
98
+ onText?: (delta: string) => void;
99
+ /** Streamed think content (only meaningful with `think: true`). */
100
+ onThink?: (delta: string) => void;
101
+ /** Reuse the KV cache when this turn is a clean append to the previous one (the committed
102
+ * conversation plus one new user turn). Default true; set false to force a full prefill. */
103
+ reuseCache?: boolean;
104
+ }
105
+ interface ChatResult {
106
+ /** The visible reply (think blocks removed). */
107
+ text: string;
108
+ /** Content of <think> blocks, when the model emitted any. */
109
+ thinkText: string;
110
+ /** Generated token ids (as returned by the engine; excludes the prompt). */
111
+ tokens: number[];
112
+ /** The exact token ids fed to the engine this turn (the full prompt, or the reuse delta). */
113
+ inputTokenIds: number[];
114
+ /** Why generation ended. */
115
+ finishReason: 'stop' | 'length' | 'abort';
116
+ /** True when this turn extended the KV cache instead of a full prefill. */
117
+ reusedCache: boolean;
118
+ prefillMs: number;
119
+ decodeMs: number;
120
+ tokensPerSecond: number;
121
+ }
122
+ interface Chat {
123
+ /** Generate a reply for the message list. Resolves with the full result; stream text via
124
+ * `onText`. Turns are serialized: overlapping calls queue instead of interleaving. */
125
+ send(messages: ChatMessage[], options?: ChatSendOptions): Promise<ChatResult>;
126
+ /** Generate a reply as an async generator of visible-text deltas; the final {@link ChatResult}
127
+ * is the generator's return value: `const it = chat.stream(msgs); for await (const d of it) ...` */
128
+ stream(messages: ChatMessage[], options?: ChatSendOptions): AsyncGenerator<string, ChatResult>;
129
+ /** Prefill a message prefix (e.g. the static system prompt) into the KV cache without decoding,
130
+ * so the first real turn is a cheap cache-append instead of a cold full prefill. */
131
+ prewarm(messages: ChatMessage[]): Promise<void>;
132
+ /** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
133
+ * Use this (not engine.resetCache()) so the two stay in sync. */
134
+ reset(): void;
135
+ /** The model's end-of-sequence token id. */
136
+ readonly eosTokenId: number;
137
+ /** Escape hatch: encode/decode/applyChatTemplate for callers that need the text boundary. */
138
+ readonly tokenizer: ChatTokenizer;
139
+ }
140
+ /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
141
+ declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
142
+ //#endregion
143
+ export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, ThinkSplitter, createChat };
144
+ //# sourceMappingURL=chat.d.ts.map