bitgpu 0.6.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 +52 -5
- package/dist/chat.d.ts +62 -2
- package/dist/chat.js +383 -10
- package/dist/chat.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +157 -61
- package/dist/index.js.map +1 -1
- package/dist/{types-C3FWn4rd.d.ts → types-CsoJYJlG.d.ts} +29 -8
- package/package.json +1 -1
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
|
|
@@ -84,6 +110,24 @@ 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). 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
|
+
|
|
87
131
|
The two text libraries (`@huggingface/tokenizers`, `@huggingface/jinja` - pure JS, Apache-2.0,
|
|
88
132
|
see THIRD_PARTY_LICENSES.md) are inlined into `dist/chat.js` at build time, the same way the
|
|
89
133
|
engine inlines its WGSL: the package keeps **zero runtime dependencies**, and importing plain
|
|
@@ -187,13 +231,16 @@ model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~
|
|
|
187
231
|
```sh
|
|
188
232
|
ln -s /path/to/bonsai-model examples/model # or copy the files in
|
|
189
233
|
npm run build
|
|
190
|
-
|
|
191
|
-
npm run verify:headless # drives system Chrome headlessly (WebGPU/Metal)
|
|
234
|
+
npm run verify:headless # serves the repo itself + drives system Chrome headlessly
|
|
192
235
|
```
|
|
193
236
|
|
|
194
|
-
Or
|
|
195
|
-
|
|
196
|
-
|
|
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.
|
|
197
244
|
|
|
198
245
|
The gate is model-parametric: `verify.html?model=<tag>` loads `examples/model-<tag>` against
|
|
199
246
|
`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-
|
|
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). */
|
|
@@ -55,6 +59,37 @@ declare class ThinkSplitter {
|
|
|
55
59
|
* flushes to the think channel, never to the visible reply. */
|
|
56
60
|
flush(): SplitChunk;
|
|
57
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
|
+
}
|
|
58
93
|
//#endregion
|
|
59
94
|
//#region src/chat/index.d.ts
|
|
60
95
|
/** Options for {@link createChat}. Point it at the model directory (which already hosts
|
|
@@ -88,6 +123,18 @@ interface ChatSendOptions {
|
|
|
88
123
|
promptLookup?: GenerateOptions['promptLookup'];
|
|
89
124
|
/** Extra stop token ids, in addition to the model's eos. */
|
|
90
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;
|
|
91
138
|
signal?: AbortSignal;
|
|
92
139
|
/** Render the template with enable_thinking and let the model reason. Think content streams to
|
|
93
140
|
* `onThink` and lands in `result.thinkText`; it never appears in the visible reply. A think
|
|
@@ -101,6 +148,13 @@ interface ChatSendOptions {
|
|
|
101
148
|
/** Reuse the KV cache when this turn is a clean append to the previous one (the committed
|
|
102
149
|
* conversation plus one new user turn). Default true; set false to force a full prefill. */
|
|
103
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';
|
|
104
158
|
}
|
|
105
159
|
interface ChatResult {
|
|
106
160
|
/** The visible reply (think blocks removed). */
|
|
@@ -129,6 +183,12 @@ interface Chat {
|
|
|
129
183
|
/** Prefill a message prefix (e.g. the static system prompt) into the KV cache without decoding,
|
|
130
184
|
* so the first real turn is a cheap cache-append instead of a cold full prefill. */
|
|
131
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;
|
|
132
192
|
/** Forget the conversation: clears the engine's KV cache and the chat's committed transcript.
|
|
133
193
|
* Use this (not engine.resetCache()) so the two stay in sync. */
|
|
134
194
|
reset(): void;
|
|
@@ -140,5 +200,5 @@ interface Chat {
|
|
|
140
200
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
141
201
|
declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
|
|
142
202
|
//#endregion
|
|
143
|
-
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, ThinkSplitter, createChat };
|
|
203
|
+
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatTokenizer, type DecoderStream, JsonMachine, StopScanner, ThinkSplitter, createChat };
|
|
144
204
|
//# sourceMappingURL=chat.d.ts.map
|
package/dist/chat.js
CHANGED
|
@@ -4245,6 +4245,14 @@ var ChatTokenizer = class {
|
|
|
4245
4245
|
if (ids.length === 0) return "";
|
|
4246
4246
|
return this.tok.decode(ids, { skip_special_tokens: skipSpecialTokens });
|
|
4247
4247
|
}
|
|
4248
|
+
/** The raw vocab string for a token id (byte-alias space for byte-level BPE). */
|
|
4249
|
+
idToToken(id) {
|
|
4250
|
+
return this.tok.id_to_token(id);
|
|
4251
|
+
}
|
|
4252
|
+
/** Ids of all added tokens (ChatML markers, <think>, etc.) - never plain content. */
|
|
4253
|
+
addedTokenIds() {
|
|
4254
|
+
return new Set(this.tok.get_added_tokens_decoder().keys());
|
|
4255
|
+
}
|
|
4248
4256
|
get hasChatTemplate() {
|
|
4249
4257
|
return this.template !== null;
|
|
4250
4258
|
}
|
|
@@ -4350,6 +4358,338 @@ var ThinkSplitter = class {
|
|
|
4350
4358
|
return r;
|
|
4351
4359
|
}
|
|
4352
4360
|
};
|
|
4361
|
+
/** Stream-safe stop-sequence scanner: emits visible text up to (excluding) the earliest match of
|
|
4362
|
+
* any stop string, holding back chunk-edge suffixes that could begin one (stops can straddle
|
|
4363
|
+
* token boundaries). Once matched, everything further is swallowed. */
|
|
4364
|
+
var StopScanner = class {
|
|
4365
|
+
stops;
|
|
4366
|
+
matched = false;
|
|
4367
|
+
hold = "";
|
|
4368
|
+
constructor(stops) {
|
|
4369
|
+
this.stops = stops;
|
|
4370
|
+
}
|
|
4371
|
+
push(text) {
|
|
4372
|
+
if (this.matched) return "";
|
|
4373
|
+
const s = this.hold + text;
|
|
4374
|
+
let mi = -1;
|
|
4375
|
+
for (const st of this.stops) {
|
|
4376
|
+
const i = s.indexOf(st);
|
|
4377
|
+
if (i !== -1 && (mi === -1 || i < mi)) mi = i;
|
|
4378
|
+
}
|
|
4379
|
+
if (mi !== -1) {
|
|
4380
|
+
this.matched = true;
|
|
4381
|
+
this.hold = "";
|
|
4382
|
+
return s.slice(0, mi);
|
|
4383
|
+
}
|
|
4384
|
+
let safe = s.length;
|
|
4385
|
+
for (const st of this.stops) safe = Math.min(safe, holdback(s, st));
|
|
4386
|
+
this.hold = s.slice(safe);
|
|
4387
|
+
return s.slice(0, safe);
|
|
4388
|
+
}
|
|
4389
|
+
flush() {
|
|
4390
|
+
const r = this.matched ? "" : this.hold;
|
|
4391
|
+
this.hold = "";
|
|
4392
|
+
return r;
|
|
4393
|
+
}
|
|
4394
|
+
};
|
|
4395
|
+
//#endregion
|
|
4396
|
+
//#region src/chat/json.ts
|
|
4397
|
+
const WS = /* @__PURE__ */ new Set([
|
|
4398
|
+
32,
|
|
4399
|
+
9,
|
|
4400
|
+
10,
|
|
4401
|
+
13
|
|
4402
|
+
]);
|
|
4403
|
+
const isDigit = (b) => b >= 48 && b <= 57;
|
|
4404
|
+
const isHex = (b) => isDigit(b) || b >= 65 && b <= 70 || b >= 97 && b <= 102;
|
|
4405
|
+
const numberDone = (s) => s === 1 || s === 2 || s === 4 || s === 7;
|
|
4406
|
+
var JsonMachine = class JsonMachine {
|
|
4407
|
+
stack = [];
|
|
4408
|
+
phase = 0;
|
|
4409
|
+
isKey = false;
|
|
4410
|
+
uLeft = 0;
|
|
4411
|
+
utf8Left = 0;
|
|
4412
|
+
numSub = 2;
|
|
4413
|
+
litWord = "";
|
|
4414
|
+
litPos = 0;
|
|
4415
|
+
clone() {
|
|
4416
|
+
const m = new JsonMachine();
|
|
4417
|
+
m.stack = this.stack.slice();
|
|
4418
|
+
m.phase = this.phase;
|
|
4419
|
+
m.isKey = this.isKey;
|
|
4420
|
+
m.uLeft = this.uLeft;
|
|
4421
|
+
m.utf8Left = this.utf8Left;
|
|
4422
|
+
m.numSub = this.numSub;
|
|
4423
|
+
m.litWord = this.litWord;
|
|
4424
|
+
m.litPos = this.litPos;
|
|
4425
|
+
return m;
|
|
4426
|
+
}
|
|
4427
|
+
get complete() {
|
|
4428
|
+
return this.phase === 12;
|
|
4429
|
+
}
|
|
4430
|
+
/** Feed bytes; false = the text stopped being a valid JSON prefix (state is then undefined). */
|
|
4431
|
+
feed(bytes) {
|
|
4432
|
+
for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
|
|
4433
|
+
return true;
|
|
4434
|
+
}
|
|
4435
|
+
openValue(b) {
|
|
4436
|
+
if (b === 123) {
|
|
4437
|
+
this.stack.push("{");
|
|
4438
|
+
this.phase = 3;
|
|
4439
|
+
} else if (b === 91) {
|
|
4440
|
+
this.stack.push("[");
|
|
4441
|
+
this.phase = 2;
|
|
4442
|
+
} else if (b === 34) {
|
|
4443
|
+
this.isKey = false;
|
|
4444
|
+
this.phase = 7;
|
|
4445
|
+
} else if (b === 45 || isDigit(b)) {
|
|
4446
|
+
this.numSub = b === 45 ? 0 : b === 48 ? 1 : 2;
|
|
4447
|
+
this.phase = 10;
|
|
4448
|
+
} else if (b === 116 || b === 102 || b === 110) {
|
|
4449
|
+
this.litWord = b === 116 ? "true" : b === 102 ? "false" : "null";
|
|
4450
|
+
this.litPos = 1;
|
|
4451
|
+
this.phase = 11;
|
|
4452
|
+
} else return false;
|
|
4453
|
+
return true;
|
|
4454
|
+
}
|
|
4455
|
+
closeValue() {
|
|
4456
|
+
this.phase = this.stack.length === 0 ? 12 : 6;
|
|
4457
|
+
}
|
|
4458
|
+
closeContainer(b) {
|
|
4459
|
+
const want = b === 125 ? "{" : "[";
|
|
4460
|
+
if (this.stack.pop() !== want) return false;
|
|
4461
|
+
this.closeValue();
|
|
4462
|
+
return true;
|
|
4463
|
+
}
|
|
4464
|
+
byte(b) {
|
|
4465
|
+
switch (this.phase) {
|
|
4466
|
+
case 0:
|
|
4467
|
+
if (WS.has(b)) return true;
|
|
4468
|
+
if (b === 123 || b === 91) return this.openValue(b);
|
|
4469
|
+
return false;
|
|
4470
|
+
case 1:
|
|
4471
|
+
if (WS.has(b)) return true;
|
|
4472
|
+
return this.openValue(b);
|
|
4473
|
+
case 2:
|
|
4474
|
+
if (WS.has(b)) return true;
|
|
4475
|
+
if (b === 93) return this.closeContainer(b);
|
|
4476
|
+
return this.openValue(b);
|
|
4477
|
+
case 3:
|
|
4478
|
+
if (WS.has(b)) return true;
|
|
4479
|
+
if (b === 125) return this.closeContainer(b);
|
|
4480
|
+
if (b === 34) {
|
|
4481
|
+
this.isKey = true;
|
|
4482
|
+
this.phase = 7;
|
|
4483
|
+
return true;
|
|
4484
|
+
}
|
|
4485
|
+
return false;
|
|
4486
|
+
case 4:
|
|
4487
|
+
if (WS.has(b)) return true;
|
|
4488
|
+
if (b === 34) {
|
|
4489
|
+
this.isKey = true;
|
|
4490
|
+
this.phase = 7;
|
|
4491
|
+
return true;
|
|
4492
|
+
}
|
|
4493
|
+
return false;
|
|
4494
|
+
case 5:
|
|
4495
|
+
if (WS.has(b)) return true;
|
|
4496
|
+
if (b === 58) {
|
|
4497
|
+
this.phase = 1;
|
|
4498
|
+
return true;
|
|
4499
|
+
}
|
|
4500
|
+
return false;
|
|
4501
|
+
case 6: {
|
|
4502
|
+
if (WS.has(b)) return true;
|
|
4503
|
+
const top = this.stack[this.stack.length - 1];
|
|
4504
|
+
if (b === 44) {
|
|
4505
|
+
this.phase = top === "{" ? 4 : 1;
|
|
4506
|
+
return true;
|
|
4507
|
+
}
|
|
4508
|
+
if (b === 125 && top === "{" || b === 93 && top === "[") return this.closeContainer(b);
|
|
4509
|
+
return false;
|
|
4510
|
+
}
|
|
4511
|
+
case 7:
|
|
4512
|
+
if (this.utf8Left > 0) {
|
|
4513
|
+
if (b >= 128 && b <= 191) {
|
|
4514
|
+
this.utf8Left--;
|
|
4515
|
+
return true;
|
|
4516
|
+
}
|
|
4517
|
+
return false;
|
|
4518
|
+
}
|
|
4519
|
+
if (b === 34) {
|
|
4520
|
+
if (this.isKey) {
|
|
4521
|
+
this.isKey = false;
|
|
4522
|
+
this.phase = 5;
|
|
4523
|
+
} else this.closeValue();
|
|
4524
|
+
return true;
|
|
4525
|
+
}
|
|
4526
|
+
if (b === 92) {
|
|
4527
|
+
this.phase = 8;
|
|
4528
|
+
return true;
|
|
4529
|
+
}
|
|
4530
|
+
if (b < 32) return false;
|
|
4531
|
+
if (b < 128) return true;
|
|
4532
|
+
if (b >= 194 && b <= 223) this.utf8Left = 1;
|
|
4533
|
+
else if (b >= 224 && b <= 239) this.utf8Left = 2;
|
|
4534
|
+
else if (b >= 240 && b <= 244) this.utf8Left = 3;
|
|
4535
|
+
else return false;
|
|
4536
|
+
return true;
|
|
4537
|
+
case 8:
|
|
4538
|
+
if (b === 117) {
|
|
4539
|
+
this.uLeft = 4;
|
|
4540
|
+
this.phase = 9;
|
|
4541
|
+
return true;
|
|
4542
|
+
}
|
|
4543
|
+
if ([
|
|
4544
|
+
34,
|
|
4545
|
+
92,
|
|
4546
|
+
47,
|
|
4547
|
+
98,
|
|
4548
|
+
102,
|
|
4549
|
+
110,
|
|
4550
|
+
114,
|
|
4551
|
+
116
|
|
4552
|
+
].includes(b)) {
|
|
4553
|
+
this.phase = 7;
|
|
4554
|
+
return true;
|
|
4555
|
+
}
|
|
4556
|
+
return false;
|
|
4557
|
+
case 9:
|
|
4558
|
+
if (!isHex(b)) return false;
|
|
4559
|
+
if (--this.uLeft === 0) this.phase = 7;
|
|
4560
|
+
return true;
|
|
4561
|
+
case 10:
|
|
4562
|
+
switch (this.numSub) {
|
|
4563
|
+
case 0:
|
|
4564
|
+
if (!isDigit(b)) return false;
|
|
4565
|
+
this.numSub = b === 48 ? 1 : 2;
|
|
4566
|
+
return true;
|
|
4567
|
+
case 1:
|
|
4568
|
+
case 2:
|
|
4569
|
+
if (isDigit(b)) {
|
|
4570
|
+
if (this.numSub === 1) return false;
|
|
4571
|
+
return true;
|
|
4572
|
+
}
|
|
4573
|
+
break;
|
|
4574
|
+
case 3:
|
|
4575
|
+
if (!isDigit(b)) return false;
|
|
4576
|
+
this.numSub = 4;
|
|
4577
|
+
return true;
|
|
4578
|
+
case 4:
|
|
4579
|
+
if (isDigit(b)) return true;
|
|
4580
|
+
break;
|
|
4581
|
+
case 5:
|
|
4582
|
+
if (b === 43 || b === 45) {
|
|
4583
|
+
this.numSub = 6;
|
|
4584
|
+
return true;
|
|
4585
|
+
}
|
|
4586
|
+
if (!isDigit(b)) return false;
|
|
4587
|
+
this.numSub = 7;
|
|
4588
|
+
return true;
|
|
4589
|
+
case 6:
|
|
4590
|
+
if (!isDigit(b)) return false;
|
|
4591
|
+
this.numSub = 7;
|
|
4592
|
+
return true;
|
|
4593
|
+
case 7:
|
|
4594
|
+
if (isDigit(b)) return true;
|
|
4595
|
+
break;
|
|
4596
|
+
}
|
|
4597
|
+
if (b === 46 && (this.numSub === 1 || this.numSub === 2)) {
|
|
4598
|
+
this.numSub = 3;
|
|
4599
|
+
return true;
|
|
4600
|
+
}
|
|
4601
|
+
if ((b === 101 || b === 69) && numberDone(this.numSub) && this.numSub !== 7) {
|
|
4602
|
+
this.numSub = 5;
|
|
4603
|
+
return true;
|
|
4604
|
+
}
|
|
4605
|
+
if (numberDone(this.numSub)) {
|
|
4606
|
+
this.closeValue();
|
|
4607
|
+
return this.byte(b);
|
|
4608
|
+
}
|
|
4609
|
+
return false;
|
|
4610
|
+
case 11:
|
|
4611
|
+
if (b !== this.litWord.charCodeAt(this.litPos)) return false;
|
|
4612
|
+
if (++this.litPos === this.litWord.length) this.closeValue();
|
|
4613
|
+
return true;
|
|
4614
|
+
case 12: return WS.has(b);
|
|
4615
|
+
}
|
|
4616
|
+
}
|
|
4617
|
+
};
|
|
4618
|
+
function aliasToByte() {
|
|
4619
|
+
const bs = [];
|
|
4620
|
+
for (let i = 33; i <= 126; i++) bs.push(i);
|
|
4621
|
+
for (let i = 161; i <= 172; i++) bs.push(i);
|
|
4622
|
+
for (let i = 174; i <= 255; i++) bs.push(i);
|
|
4623
|
+
const cs = [...bs];
|
|
4624
|
+
let n = 0;
|
|
4625
|
+
for (let b = 0; b < 256; b++) if (!bs.includes(b)) {
|
|
4626
|
+
bs.push(b);
|
|
4627
|
+
cs.push(256 + n);
|
|
4628
|
+
n++;
|
|
4629
|
+
}
|
|
4630
|
+
return new Map(bs.map((b, i) => [cs[i], b]));
|
|
4631
|
+
}
|
|
4632
|
+
/** Precomputed id -> raw bytes lookup (lazy per id; added/special tokens map to null). */
|
|
4633
|
+
var TokenByteTable = class {
|
|
4634
|
+
tk;
|
|
4635
|
+
cache = /* @__PURE__ */ new Map();
|
|
4636
|
+
inv = aliasToByte();
|
|
4637
|
+
added;
|
|
4638
|
+
constructor(tk) {
|
|
4639
|
+
this.tk = tk;
|
|
4640
|
+
this.added = tk.addedTokenIds();
|
|
4641
|
+
}
|
|
4642
|
+
bytes(id) {
|
|
4643
|
+
const hit = this.cache.get(id);
|
|
4644
|
+
if (hit !== void 0) return hit;
|
|
4645
|
+
let out = null;
|
|
4646
|
+
if (!this.added.has(id)) {
|
|
4647
|
+
const s = this.tk.idToToken(id);
|
|
4648
|
+
if (s !== void 0) {
|
|
4649
|
+
const b = new Uint8Array(s.length);
|
|
4650
|
+
let ok = true;
|
|
4651
|
+
for (let i = 0; i < s.length; i++) {
|
|
4652
|
+
const v = this.inv.get(s.charCodeAt(i));
|
|
4653
|
+
if (v === void 0) {
|
|
4654
|
+
ok = false;
|
|
4655
|
+
break;
|
|
4656
|
+
}
|
|
4657
|
+
b[i] = v;
|
|
4658
|
+
}
|
|
4659
|
+
out = ok ? b : null;
|
|
4660
|
+
}
|
|
4661
|
+
}
|
|
4662
|
+
this.cache.set(id, out);
|
|
4663
|
+
return out;
|
|
4664
|
+
}
|
|
4665
|
+
};
|
|
4666
|
+
/** The per-step candidate filter for format:'json': permit candidates whose bytes keep the text
|
|
4667
|
+
* a valid JSON prefix; once the root value is complete, permit ONLY eos so generation ends
|
|
4668
|
+
* naturally. Call advance() with each chosen token to move the real machine forward. */
|
|
4669
|
+
function makeJsonFilter(table, eosTokenId) {
|
|
4670
|
+
const machine = new JsonMachine();
|
|
4671
|
+
return {
|
|
4672
|
+
machine,
|
|
4673
|
+
filter: (ids) => {
|
|
4674
|
+
const out = [];
|
|
4675
|
+
for (const id of ids) {
|
|
4676
|
+
if (machine.complete) {
|
|
4677
|
+
if (id === eosTokenId) out.push(Number(id));
|
|
4678
|
+
continue;
|
|
4679
|
+
}
|
|
4680
|
+
const bytes = table.bytes(Number(id));
|
|
4681
|
+
if (!bytes || bytes.length === 0) continue;
|
|
4682
|
+
if (machine.clone().feed(bytes)) out.push(Number(id));
|
|
4683
|
+
}
|
|
4684
|
+
return out;
|
|
4685
|
+
},
|
|
4686
|
+
advance: (id) => {
|
|
4687
|
+
if (machine.complete) return;
|
|
4688
|
+
const bytes = table.bytes(id);
|
|
4689
|
+
if (bytes) machine.feed(bytes);
|
|
4690
|
+
}
|
|
4691
|
+
};
|
|
4692
|
+
}
|
|
4353
4693
|
//#endregion
|
|
4354
4694
|
//#region src/chat/index.ts
|
|
4355
4695
|
function deriveChatWrap(tk) {
|
|
@@ -4426,9 +4766,11 @@ async function createChat(engine, options) {
|
|
|
4426
4766
|
return run;
|
|
4427
4767
|
};
|
|
4428
4768
|
};
|
|
4769
|
+
let byteTable = null;
|
|
4429
4770
|
async function sendImpl(messages, o = {}) {
|
|
4430
4771
|
if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
|
|
4431
|
-
const
|
|
4772
|
+
const json = o.format === "json";
|
|
4773
|
+
const think = !json && (o.think ?? false);
|
|
4432
4774
|
const canReuse = (o.reuseCache ?? true) && !think && wrap !== null && isCleanAppend(committed, messages);
|
|
4433
4775
|
let inputTokenIds;
|
|
4434
4776
|
if (canReuse) {
|
|
@@ -4445,12 +4787,19 @@ async function createChat(engine, options) {
|
|
|
4445
4787
|
}
|
|
4446
4788
|
const decoder = tk.createDecoderStream(true);
|
|
4447
4789
|
const splitter = new ThinkSplitter();
|
|
4790
|
+
const stops = o.stopSequences?.length ? new StopScanner(o.stopSequences) : null;
|
|
4791
|
+
const stopCtl = stops ? new AbortController() : null;
|
|
4792
|
+
const signal = stopCtl ? o.signal ? AbortSignal.any([o.signal, stopCtl.signal]) : stopCtl.signal : o.signal;
|
|
4448
4793
|
let text = "";
|
|
4449
4794
|
let thinkText = "";
|
|
4450
4795
|
const emit = (chunk) => {
|
|
4451
4796
|
if (chunk.text) {
|
|
4452
|
-
text
|
|
4453
|
-
|
|
4797
|
+
const visible = stops ? stops.push(chunk.text) : chunk.text;
|
|
4798
|
+
if (visible) {
|
|
4799
|
+
text += visible;
|
|
4800
|
+
o.onText?.(visible);
|
|
4801
|
+
}
|
|
4802
|
+
if (stops?.matched) stopCtl?.abort();
|
|
4454
4803
|
}
|
|
4455
4804
|
if (chunk.think) {
|
|
4456
4805
|
thinkText += chunk.think;
|
|
@@ -4459,6 +4808,7 @@ async function createChat(engine, options) {
|
|
|
4459
4808
|
};
|
|
4460
4809
|
const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
|
|
4461
4810
|
const epoch0 = resetEpoch;
|
|
4811
|
+
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId) : null;
|
|
4462
4812
|
let result;
|
|
4463
4813
|
try {
|
|
4464
4814
|
result = await engine.generate(inputTokenIds, {
|
|
@@ -4469,20 +4819,39 @@ async function createChat(engine, options) {
|
|
|
4469
4819
|
repetitionPenalty: o.repetitionPenalty,
|
|
4470
4820
|
noRepeatNgramSize: o.noRepeatNgramSize,
|
|
4471
4821
|
seed: o.seed,
|
|
4472
|
-
promptLookup: o.promptLookup,
|
|
4822
|
+
promptLookup: json ? false : o.promptLookup,
|
|
4473
4823
|
stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
|
|
4474
4824
|
reuseCache: canReuse,
|
|
4475
|
-
signal
|
|
4476
|
-
|
|
4825
|
+
signal,
|
|
4826
|
+
candidateFilter: jf ? (ids) => jf.filter(ids) : void 0,
|
|
4827
|
+
onToken: (id) => {
|
|
4828
|
+
jf?.advance(id);
|
|
4829
|
+
emit(splitter.push(decoder.push(id)));
|
|
4830
|
+
}
|
|
4477
4831
|
});
|
|
4478
4832
|
} catch (err) {
|
|
4479
|
-
if (
|
|
4833
|
+
if (/maxSeqLen/.test(err.message)) {
|
|
4834
|
+
if (o.onOverflow) {
|
|
4835
|
+
const trimmed = o.onOverflow({
|
|
4836
|
+
promptTokenCount: inputTokenIds.length,
|
|
4837
|
+
maxSeqLen: engine.capabilities.maxSeqLen
|
|
4838
|
+
});
|
|
4839
|
+
if (trimmed && trimmed.length > 0) {
|
|
4840
|
+
dropCache();
|
|
4841
|
+
return await sendImpl(trimmed, {
|
|
4842
|
+
...o,
|
|
4843
|
+
onOverflow: void 0,
|
|
4844
|
+
reuseCache: false
|
|
4845
|
+
});
|
|
4846
|
+
}
|
|
4847
|
+
}
|
|
4848
|
+
} else dropCache();
|
|
4480
4849
|
throw err;
|
|
4481
4850
|
}
|
|
4482
4851
|
emit(splitter.push(decoder.flush()));
|
|
4483
4852
|
emit(splitter.flush());
|
|
4484
4853
|
const aborted = o.signal?.aborted ?? false;
|
|
4485
|
-
if (aborted) dropCache();
|
|
4854
|
+
if (aborted || stops?.matched) dropCache();
|
|
4486
4855
|
else if (think) dropCache();
|
|
4487
4856
|
else if (wrap !== null && text.trim() && resetEpoch === epoch0) {
|
|
4488
4857
|
committed = [...messages, {
|
|
@@ -4496,7 +4865,7 @@ async function createChat(engine, options) {
|
|
|
4496
4865
|
thinkText,
|
|
4497
4866
|
tokens: result.tokens,
|
|
4498
4867
|
inputTokenIds,
|
|
4499
|
-
finishReason: aborted ? "abort" : result.tokens.length >= maxTokens ? "length" : "stop",
|
|
4868
|
+
finishReason: aborted ? "abort" : stops?.matched ? "stop" : result.tokens.length >= maxTokens ? "length" : "stop",
|
|
4500
4869
|
reusedCache: canReuse,
|
|
4501
4870
|
prefillMs: result.prefillMs,
|
|
4502
4871
|
decodeMs: result.decodeMs,
|
|
@@ -4559,6 +4928,10 @@ async function createChat(engine, options) {
|
|
|
4559
4928
|
return gen();
|
|
4560
4929
|
},
|
|
4561
4930
|
prewarm: serialize(prewarmImpl),
|
|
4931
|
+
countTokens: (messages, opts) => tk.encode(tk.applyChatTemplate(messages, {
|
|
4932
|
+
addGenerationPrompt: opts?.addGenerationPrompt ?? true,
|
|
4933
|
+
enableThinking: opts?.think ?? false
|
|
4934
|
+
}), false).length,
|
|
4562
4935
|
reset: () => {
|
|
4563
4936
|
resetEpoch++;
|
|
4564
4937
|
dropCache();
|
|
@@ -4568,6 +4941,6 @@ async function createChat(engine, options) {
|
|
|
4568
4941
|
};
|
|
4569
4942
|
}
|
|
4570
4943
|
//#endregion
|
|
4571
|
-
export { ChatTokenizer, ThinkSplitter, createChat };
|
|
4944
|
+
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, createChat };
|
|
4572
4945
|
|
|
4573
4946
|
//# sourceMappingURL=chat.js.map
|