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.
- package/README.md +89 -5
- package/THIRD_PARTY_LICENSES.md +19 -0
- package/dist/chat.d.ts +144 -0
- package/dist/chat.js +4573 -0
- package/dist/chat.js.map +1 -0
- package/dist/index.d.ts +2 -185
- package/dist/index.js +160 -37
- package/dist/index.js.map +1 -1
- package/dist/types-C3FWn4rd.d.ts +191 -0
- package/package.json +13 -5
package/README.md
CHANGED
|
@@ -3,10 +3,13 @@
|
|
|
3
3
|
A fast, dependency-free WebGPU runtime for **low-bit LLMs** in the browser.
|
|
4
4
|
|
|
5
5
|
Today it runs **1-bit (binary-weight)** models.
|
|
6
|
-
Reference
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
Reference targets are Bonsai **1.7B, 4B and 8B** (Qwen3 architecture, sign-packed binary linear
|
|
7
|
+
weights + 2/4-bit embeddings, tied or untied lm_head) - every size is gated bit-exact against the
|
|
8
|
+
reference forward on real hardware. GPU-resident decode (greedy or sampled), streaming, EOS stop,
|
|
9
|
+
`AbortSignal`, and cross-turn KV-cache reuse. Runs the fast subgroup path on Apple / NVIDIA /
|
|
9
10
|
recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU is available.
|
|
11
|
+
Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
|
|
12
|
+
only when that model needs it and smaller models keep running at WebGPU's guaranteed minimums.
|
|
10
13
|
|
|
11
14
|
## Install
|
|
12
15
|
|
|
@@ -44,11 +47,80 @@ console.log(result.tokens, result.tokensPerSecond)
|
|
|
44
47
|
// Sampling (matches transformers.js v4.2.0 exactly): set a temperature other than 0/1.
|
|
45
48
|
await engine.generate(promptTokenIds, { temperature: 0.5, topK: 20, repetitionPenalty: 1.15 })
|
|
46
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
|
+
|
|
47
54
|
engine.dispose()
|
|
48
55
|
```
|
|
49
56
|
|
|
50
|
-
|
|
51
|
-
|
|
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.
|
|
93
|
+
|
|
94
|
+
## Bring your own model
|
|
95
|
+
|
|
96
|
+
bitgpu loads its own small format instead of parsing ONNX at runtime: a `manifest.json` (the
|
|
97
|
+
architecture contract + every tensor mapped to a byte range) and a ~30 KB aux file, both
|
|
98
|
+
produced ONCE, offline, from a standard export - while the big weights file is used
|
|
99
|
+
byte-for-byte unchanged, so it can keep streaming from wherever it already lives (e.g. the
|
|
100
|
+
Hugging Face Hub). Same one-time-conversion model as GGUF/llama.cpp or MLX.
|
|
101
|
+
|
|
102
|
+
```sh
|
|
103
|
+
python tools/convert.py --model <dir with config.json + the q1 .onnx + its data file>
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Host the two small files anywhere (they're static), point `createEngine` at them, done:
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
createEngine({
|
|
110
|
+
manifestUrl: 'https://your-site.example/model/manifest.json',
|
|
111
|
+
auxUrl: 'https://your-site.example/model/model_q1.aux.bin',
|
|
112
|
+
dataUrl: 'https://huggingface.co/<repo>/resolve/main/onnx/model_q1.onnx_data',
|
|
113
|
+
})
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Compatibility envelope: Qwen3-family models quantized with the onnx-community 1-bit ("q1")
|
|
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).
|
|
52
124
|
|
|
53
125
|
## API
|
|
54
126
|
|
|
@@ -98,6 +170,7 @@ npm run build # tsdown -> dist (ESM + .d.ts)
|
|
|
98
170
|
npm run typecheck
|
|
99
171
|
npm run test:sampler # sampler parity vs transformers.js v4.2.0
|
|
100
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
|
|
101
174
|
npm run check:publish # publint + are-the-types-wrong
|
|
102
175
|
```
|
|
103
176
|
|
|
@@ -122,6 +195,17 @@ Or open `http://localhost:8000/examples/verify.html` in a WebGPU browser and cli
|
|
|
122
195
|
gate on real hardware before every release; CI covers only the CPU-checkable parts (types, sampler
|
|
123
196
|
math, drafter, packaging).
|
|
124
197
|
|
|
198
|
+
The gate is model-parametric: `verify.html?model=<tag>` loads `examples/model-<tag>` against
|
|
199
|
+
`test-fixtures/forward-<tag>`, and the headless driver automatically runs every staged variant.
|
|
200
|
+
Fixture sets for all three Bonsai sizes are committed - `forward` (1.7B, hidden 2048),
|
|
201
|
+
`forward-4b` (4B, hidden 2560) and `forward-8b` (8B, hidden 4096, untied lm_head, raised
|
|
202
|
+
device limits) - so engine changes are checked against three geometries; stage the extra
|
|
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`.
|
|
208
|
+
|
|
125
209
|
### Releasing
|
|
126
210
|
|
|
127
211
|
Publishing runs through GitHub Actions with npm trusted publishing (OIDC + provenance, no token).
|
|
@@ -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
|