bitgpu 0.6.0 → 0.8.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.8.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
@@ -84,6 +110,42 @@ reuse with exact token bookkeeping (a clean follow-up turn prefills only the del
84
110
  `chat.prewarm(messages)` warms a static system prompt at load). `chat.reset()` forgets the
85
111
  conversation.
86
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).
128
+
129
+ Pass a **schema** and the shape is enforced token-by-token too - the model cannot open an object
130
+ where an array is required, stop at 1 item when 5 are demanded, invent keys, drift a type, or
131
+ answer outside an enum:
132
+
133
+ ```ts
134
+ await chat.send(messages, { format: { json: { schema: {
135
+ type: 'array', minItems: 5, maxItems: 5,
136
+ items: { type: 'object', required: ['name', 'population'], additionalProperties: false,
137
+ properties: { name: { type: 'string' }, population: { type: 'number' } } },
138
+ } } } })
139
+ // or guaranteed classification: { properties: { mood: { enum: ['positive', 'negative', 'neutral'] } } }
140
+ ```
141
+
142
+ Enforceable subset: `type` (incl. `integer`), `properties` / `required` /
143
+ `additionalProperties: false`, `items`, `minItems` / `maxItems`, string `enum`, nested to any
144
+ depth. Anything else (`pattern`, `minimum`, `oneOf`, `$ref`, ...) **throws up front** - never
145
+ silently ignored. The guarantee is structural, not semantic: a schema makes the output parse
146
+ into the right shape, not be true. Built on the engine's generic `candidateFilter` hook (see
147
+ `GenerateOptions`), which is open for custom grammars.
148
+
87
149
  The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
88
150
  see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
89
151
  engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
@@ -187,13 +249,16 @@ model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~
187
249
  ```sh
188
250
  ln -s /path/to/bonsai-model examples/model # or copy the files in
189
251
  npm run build
190
- python3 -m http.server 8000 # serve the repo root
191
- npm run verify:headless # drives system Chrome headlessly (WebGPU/Metal)
252
+ npm run verify:headless # serves the repo itself + drives system Chrome headlessly
192
253
  ```
193
254
 
194
- Or open `http://localhost:8000/examples/verify.html` in a WebGPU browser and click Run. Run this
195
- gate on real hardware before every release; CI covers only the CPU-checkable parts (types, sampler
196
- math, drafter, packaging).
255
+ Or serve the repo root (`python3 -m http.server 8000`) and open
256
+ `http://localhost:8000/examples/verify.html` in a WebGPU browser and click Run. Run this gate on
257
+ real hardware before every release; CI covers only the CPU-checkable parts (types, sampler math,
258
+ drafter, chat, packaging). The headless driver also runs the baseline model once with
259
+ `?nosg=1` (the no-subgroup workgroup-reduction fallback used on Firefox and older adapters), so
260
+ that path is release-gated too - it is bit-identical to the subgroup path on the committed
261
+ known-good ids.
197
262
 
198
263
  The gate is model-parametric: `verify.html?model=<tag>` loads `examples/model-<tag>` against
199
264
  `test-fixtures/forward-<tag>`, and the headless driver automatically runs every staged variant.
package/dist/chat.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as Engine, o as GenerateOptions } from "./types-C3FWn4rd.js";
1
+ import { n as Engine, o as GenerateOptions } from "./types-CsoJYJlG.js";
2
2
 
3
3
  //#region src/chat/tokenizer.d.ts
4
4
  interface ChatMessage {
@@ -27,6 +27,10 @@ declare class ChatTokenizer {
27
27
  encode(text: string, addSpecialTokens?: boolean): number[];
28
28
  /** Decode token ids to text. `skipSpecialTokens` defaults to true (never surface control tokens). */
29
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>;
30
34
  get hasChatTemplate(): boolean;
31
35
  /** Render a message list to a prompt string via the model's own Jinja chat template
32
36
  * (matches transformers.js apply_chat_template byte-exactly). */
@@ -37,6 +41,61 @@ declare class ChatTokenizer {
37
41
  createDecoderStream(skipSpecialTokens?: boolean): DecoderStream;
38
42
  }
39
43
  //#endregion
44
+ //#region src/chat/json.d.ts
45
+ /** The enforceable JSON Schema subset (see validateJsonSchema). */
46
+ interface JsonSchema {
47
+ type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
48
+ properties?: Record<string, JsonSchema>;
49
+ required?: string[];
50
+ additionalProperties?: boolean;
51
+ items?: JsonSchema;
52
+ minItems?: number;
53
+ maxItems?: number;
54
+ enum?: string[];
55
+ }
56
+ /** Validate a schema against the enforceable subset; throws listing anything unsupported. */
57
+ declare function validateJsonSchema(schema: JsonSchema, path?: string, isRoot?: boolean): void;
58
+ declare class JsonMachine {
59
+ private readonly root;
60
+ private stack;
61
+ private phase;
62
+ private uLeft;
63
+ private utf8Left;
64
+ private numSub;
65
+ private numInt;
66
+ private litWord;
67
+ private litPos;
68
+ private strKind;
69
+ private strBuf;
70
+ private strTracking;
71
+ private enumCands;
72
+ private pending;
73
+ private wsRun;
74
+ constructor(root?: JsonSchema | null);
75
+ clone(): JsonMachine;
76
+ get complete(): boolean;
77
+ /** Feed bytes; false = the text stopped being a valid schema-conforming prefix (state is then undefined). */
78
+ feed(bytes: Uint8Array): boolean;
79
+ private top;
80
+ /** Byte-space form of a string literal (what strBuf accumulates). */
81
+ private static bytesOf;
82
+ private openValue;
83
+ /** A value just finished; land per the enclosing container and count array items. */
84
+ private closeValue;
85
+ private closeContainer;
86
+ /** Candidate property names for the key being typed (null = unconstrained). */
87
+ private keyCands;
88
+ private startKey;
89
+ /** Structural whitespace is never REQUIRED by JSON, so capping a run cannot make the grammar
90
+ * unsatisfiable - but without a cap, a model denied prose can loop on whitespace forever (the
91
+ * grammar permits it unboundedly) and burn the whole token budget producing "[ ". 16 bytes
92
+ * allows generous pretty-printing indentation while forcing real progress. */
93
+ private ws;
94
+ private byte;
95
+ /** In an enum/key-constrained string, the accumulated bytes must remain a prefix of some candidate. */
96
+ private enumOk;
97
+ }
98
+ //#endregion
40
99
  //#region src/chat/think.d.ts
41
100
  interface SplitChunk {
42
101
  /** Visible reply text (outside any tag pair). */
@@ -55,6 +114,17 @@ declare class ThinkSplitter {
55
114
  * flushes to the think channel, never to the visible reply. */
56
115
  flush(): SplitChunk;
57
116
  }
117
+ /** Stream-safe stop-sequence scanner: emits visible text up to (excluding) the earliest match of
118
+ * any stop string, holding back chunk-edge suffixes that could begin one (stops can straddle
119
+ * token boundaries). Once matched, everything further is swallowed. */
120
+ declare class StopScanner {
121
+ private readonly stops;
122
+ matched: boolean;
123
+ private hold;
124
+ constructor(stops: readonly string[]);
125
+ push(text: string): string;
126
+ flush(): string;
127
+ }
58
128
  //#endregion
59
129
  //#region src/chat/index.d.ts
60
130
  /** Options for {@link createChat}. Point it at the model directory (which already hosts
@@ -88,6 +158,18 @@ interface ChatSendOptions {
88
158
  promptLookup?: GenerateOptions['promptLookup'];
89
159
  /** Extra stop token ids, in addition to the model's eos. */
90
160
  stopTokens?: number[];
161
+ /** Stop STRINGS: generation ends when the visible reply contains one (matched across token
162
+ * boundaries); the stop text and anything after it is never emitted, and `finishReason` is
163
+ * 'stop'. A stop-sequence turn drops the KV cache afterwards (the cache holds a short token
164
+ * overrun past the cut). */
165
+ stopSequences?: string[];
166
+ /** Called when the prompt alone exceeds the engine's KV window (maxSeqLen). Return a trimmed
167
+ * message list to retry ONCE with (a clean full prefill), or null to rethrow the error. Pair
168
+ * with {@link Chat.countTokens} to implement the trim policy. */
169
+ onOverflow?: (info: {
170
+ promptTokenCount: number;
171
+ maxSeqLen: number;
172
+ }) => ChatMessage[] | null;
91
173
  signal?: AbortSignal;
92
174
  /** Render the template with enable_thinking and let the model reason. Think content streams to
93
175
  * `onThink` and lands in `result.thinkText`; it never appears in the visible reply. A think
@@ -101,6 +183,21 @@ interface ChatSendOptions {
101
183
  /** Reuse the KV cache when this turn is a clean append to the previous one (the committed
102
184
  * conversation plus one new user turn). Default true; set false to force a full prefill. */
103
185
  reuseCache?: boolean;
186
+ /** Constrained decoding. `'json'` guarantees the reply is one complete, valid JSON value with
187
+ * an object or array root: every generated token is validated against an incremental JSON
188
+ * machine (invalid candidates are never sampled), and generation ends when the root value
189
+ * closes. `{ json: { schema } }` additionally enforces a JSON Schema SUBSET token-by-token -
190
+ * value types, `properties`/`required`/`additionalProperties: false`, `items`,
191
+ * `minItems`/`maxItems`, string `enum`, `integer` - so the reply cannot even be shaped wrong
192
+ * (an array that must hold 5 items cannot close at 1). Unsupported schema keywords throw
193
+ * loudly up front. Check `finishReason === 'stop'` - `'length'` means maxTokens cut the value
194
+ * short. Forces `think: false` and disables `promptLookup`. The guarantee is structural, not
195
+ * semantic: a schema makes the output parse into the right shape, not be true. */
196
+ format?: 'json' | {
197
+ json: {
198
+ schema?: JsonSchema;
199
+ };
200
+ };
104
201
  }
105
202
  interface ChatResult {
106
203
  /** The visible reply (think blocks removed). */
@@ -129,6 +226,12 @@ interface Chat {
129
226
  /** Prefill a message prefix (e.g. the static system prompt) into the KV cache without decoding,
130
227
  * so the first real turn is a cheap cache-append instead of a cold full prefill. */
131
228
  prewarm(messages: ChatMessage[]): Promise<void>;
229
+ /** Token count of the rendered prompt for a message list (chat template applied) - use for
230
+ * window budgeting against `engine.capabilities.maxSeqLen`, e.g. in an onOverflow policy. */
231
+ countTokens(messages: ChatMessage[], opts?: {
232
+ addGenerationPrompt?: boolean;
233
+ think?: boolean;
234
+ }): number;
132
235
  /** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
133
236
  * Use this (not engine.resetCache()) so the two stay in sync. */
134
237
  reset(): void;
@@ -140,5 +243,5 @@ interface Chat {
140
243
  /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
141
244
  declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
142
245
  //#endregion
143
- export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, ThinkSplitter, createChat };
246
+ export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, createChat, validateJsonSchema };
144
247
  //# sourceMappingURL=chat.d.ts.map