bitgpu 0.15.0 → 0.17.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 +39 -11
- package/dist/chat.d.ts +55 -4
- package/dist/chat.js +281 -15
- package/dist/chat.js.map +1 -1
- package/dist/gguf.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +94 -39
- package/dist/index.js.map +1 -1
- package/dist/{types-Wg8VrdrL.d.ts → types-BkfIJ42d.d.ts} +13 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
|
|
|
53
53
|
import { createEngine } from 'bitgpu'
|
|
54
54
|
import { createChat } from 'bitgpu/chat'
|
|
55
55
|
|
|
56
|
-
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.
|
|
56
|
+
const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.17.0/models/bonsai-1.7b-gguf'
|
|
57
57
|
const TOK = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
|
|
58
58
|
const engine = await createEngine({
|
|
59
59
|
manifestUrl: `${REPO}/manifest.json`,
|
|
@@ -100,6 +100,11 @@ console.log(result.tokens, result.tokensPerSecond)
|
|
|
100
100
|
// Sampling (matches transformers.js v4.2.0 exactly): set a temperature other than 0/1.
|
|
101
101
|
await engine.generate(promptTokenIds, { temperature: 0.5, topK: 20, repetitionPenalty: 1.15 })
|
|
102
102
|
|
|
103
|
+
// Extra warpers, all off by default (the draw is bit-identical to the plain sampler when unset):
|
|
104
|
+
// topP (nucleus over the top-K), minP (>= minP * top prob - robust for low-precision models),
|
|
105
|
+
// presencePenalty (flat subtraction on seen tokens - the Qwen3.5 family's anti-repetition knob).
|
|
106
|
+
await engine.generate(promptTokenIds, { temperature: 0.5, topP: 0.85, topK: 20, minP: 0.05, presencePenalty: 1.5 })
|
|
107
|
+
|
|
103
108
|
// Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
|
|
104
109
|
// exactly like transformers.js greedy search:
|
|
105
110
|
await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
|
|
@@ -136,6 +141,21 @@ Reach for `'q8'` to run a 4x longer window in the same VRAM (or the same window
|
|
|
136
141
|
GPUs); keep the default `'f32'` when bit-exact reproducibility is the point.
|
|
137
142
|
`engine.capabilities.kvCache` reports what is actually active.
|
|
138
143
|
|
|
144
|
+
### f16 activation-compute (`activation: 'f16'`)
|
|
145
|
+
|
|
146
|
+
`activation: 'f16'` runs the decode matmuls with **f16 activations** (the 1-bit weights stay packed,
|
|
147
|
+
the accumulator and residual stream stay f32). It needs `shader-f16` + the subgroup path and silently
|
|
148
|
+
falls back to f32 without them, so it is always safe to request. On GPUs with **packed-f16 throughput
|
|
149
|
+
(NVIDIA / AMD)** it is a real decode win; on Apple it is ~neutral (the 1-bit GEMV is unpack- not
|
|
150
|
+
dot-bound), which is why it is opt-in rather than the default. It is measured **greedy-exact** against
|
|
151
|
+
f32 on every model - dense **and** the qwen3.5 hybrid. If your users run NVIDIA/AMD, turn it on:
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
const engine = await createEngine({ modelUrl, activation: 'f16', kvCache: 'q8', maxSeqLen: 4096 })
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
`engine.capabilities.activation` reports whether it engaged.
|
|
158
|
+
|
|
139
159
|
### Unbounded conversations (`overflow: 'sinks'`)
|
|
140
160
|
|
|
141
161
|
By default a conversation that outgrows `maxSeqLen` throws. `overflow: 'sinks'` switches to a
|
|
@@ -272,11 +292,13 @@ with or without it; `promptLookup` is disabled for the turn.
|
|
|
272
292
|
|
|
273
293
|
### Tool calling (`tools`)
|
|
274
294
|
|
|
275
|
-
The model's own protocol
|
|
276
|
-
`<tool_call>` blocks), with the same enforcement guarantee as schema mode: a bitgpu tool call
|
|
295
|
+
The model's own protocol, with the same enforcement guarantee as schema mode: a bitgpu tool call
|
|
277
296
|
**cannot be malformed** - once the model opens a call, the name is forced to one of your
|
|
278
297
|
declared tools and the arguments are forced through that tool's `parameters` schema,
|
|
279
|
-
token-by-token.
|
|
298
|
+
token-by-token. Both Qwen wire formats are supported and auto-detected from the chat template:
|
|
299
|
+
the Qwen3 JSON shape (`<tool_call>{"name": …, "arguments": …}</tool_call>` - the dense Bonsai
|
|
300
|
+
models) and the Qwen3.5 XML shape (`<tool_call><function=…><parameter=…>` - the hybrid
|
|
301
|
+
Bonsai-27B), so the same `tools` array works across all of them.
|
|
280
302
|
|
|
281
303
|
```ts
|
|
282
304
|
const tools = [{
|
|
@@ -358,14 +380,20 @@ const engine = await createEngine({
|
|
|
358
380
|
})
|
|
359
381
|
```
|
|
360
382
|
|
|
361
|
-
The Qwen3.5 hybrid **Bonsai-27B** loads exactly the same way - `fromGguf`
|
|
362
|
-
no offline converter for the hybrid yet), so point at
|
|
383
|
+
The Qwen3.5 hybrid **Bonsai-27B** loads exactly the same way - `fromGguf` on
|
|
363
384
|
`prism-ml/Bonsai-27B-gguf/resolve/main/Bonsai-27B-Q1_0.gguf` with `kvCache: 'q8'` and, say,
|
|
364
|
-
`maxSeqLen: 4096
|
|
365
|
-
|
|
366
|
-
`
|
|
367
|
-
|
|
368
|
-
|
|
385
|
+
`maxSeqLen: 4096` - or via its [committed manifest](models/) like the dense models. bitgpu runs its
|
|
386
|
+
**text trunk** (the model is multimodal; the vision path is out of scope). Text chat AND tool calling
|
|
387
|
+
work through `bitgpu/chat` unchanged - the Qwen3.5 template's XML tool protocol is auto-detected and
|
|
388
|
+
enforced like the dense models' JSON protocol (verified end-to-end on the real 27B) - but the GGUF
|
|
389
|
+
repo ships no tokenizer, so point `createChat` at
|
|
390
|
+
[prism-ml/Bonsai-27B-unpacked](https://huggingface.co/prism-ml/Bonsai-27B-unpacked)
|
|
391
|
+
for `tokenizer.json` + `tokenizer_config.json`. Recommended sampling (per the model card):
|
|
392
|
+
`temperature: 0.5, topP: 0.85, topK: 20`. It is a ~3.8 GB download and comfortably wants a 16 GB
|
|
393
|
+
(or larger) GPU budget - on an 8 GB laptop it runs but the weights spill to swap, so decode is slow.
|
|
394
|
+
A hybrid upside: its 48 gated-DeltaNet layers cost O(1) per token, so decode throughput stays nearly
|
|
395
|
+
flat as context grows (only the 16 full-attention layers scale with length) - a long-context
|
|
396
|
+
durability edge over a same-size pure-attention model.
|
|
369
397
|
|
|
370
398
|
The in-browser parse is gated: it must deep-equal the offline converter's manifest AND an
|
|
371
399
|
engine built from it must reproduce the known-good greedy ids bit-exactly on GPU. Prefer the
|
package/dist/chat.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as KvSnapshot, m as TokenLogprobs, n as Engine, o as GenerateOptions } from "./types-
|
|
1
|
+
import { c as KvSnapshot, m as TokenLogprobs, n as Engine, o as GenerateOptions } from "./types-BkfIJ42d.js";
|
|
2
2
|
|
|
3
3
|
//#region src/chat/tokenizer.d.ts
|
|
4
4
|
interface ChatMessage {
|
|
@@ -216,6 +216,44 @@ declare class ToolBodyMachine {
|
|
|
216
216
|
feed(bytes: Uint8Array): boolean;
|
|
217
217
|
private byte;
|
|
218
218
|
}
|
|
219
|
+
/** The subset of ToolBodyMachine the candidate filter relies on (both format machines implement it). */
|
|
220
|
+
interface ToolBody {
|
|
221
|
+
readonly complete: boolean;
|
|
222
|
+
readonly name: string;
|
|
223
|
+
feed(bytes: Uint8Array): boolean;
|
|
224
|
+
clone(): ToolBody;
|
|
225
|
+
/** When the machine sits at a DETERMINISTIC single-byte scaffold position (the '>' that commits a
|
|
226
|
+
* name/key, the canonical scaffold '\n'), the byte that must come next - the filter then permits
|
|
227
|
+
* ONLY the exact single-byte token, pinning the token boundaries to the model's canonical
|
|
228
|
+
* tokenization (merged tokens like '>\n' produce identical text but off-distribution token ids,
|
|
229
|
+
* which a 1-bit model cannot recover from). -1 = free position. */
|
|
230
|
+
forcedNext?(): number;
|
|
231
|
+
}
|
|
232
|
+
declare class ToolBodyMachineXml implements ToolBody {
|
|
233
|
+
private readonly cands;
|
|
234
|
+
private readonly props;
|
|
235
|
+
private phase;
|
|
236
|
+
private lit;
|
|
237
|
+
private nameBuf;
|
|
238
|
+
private wsRun;
|
|
239
|
+
private elem;
|
|
240
|
+
private keyBuf;
|
|
241
|
+
private keyCands;
|
|
242
|
+
private reqLeft;
|
|
243
|
+
private valTail;
|
|
244
|
+
private valStarted;
|
|
245
|
+
complete: boolean;
|
|
246
|
+
name: string;
|
|
247
|
+
/** byte-space tool names, and per name its byte-space property keys + required subset */
|
|
248
|
+
constructor(cands: readonly string[], props: ReadonlyMap<string, {
|
|
249
|
+
keys: readonly string[];
|
|
250
|
+
required: readonly string[];
|
|
251
|
+
}>);
|
|
252
|
+
clone(): ToolBodyMachineXml;
|
|
253
|
+
feed(bytes: Uint8Array): boolean;
|
|
254
|
+
forcedNext(): number;
|
|
255
|
+
private byte;
|
|
256
|
+
}
|
|
219
257
|
interface ToolMarkerIds {
|
|
220
258
|
open: number;
|
|
221
259
|
close: number;
|
|
@@ -228,13 +266,15 @@ interface PreparedTools {
|
|
|
228
266
|
ids: ToolMarkerIds;
|
|
229
267
|
/** null = 'auto'; a name = forced single call */
|
|
230
268
|
forced: string | null;
|
|
269
|
+
/** the tool-call wire format the model's template uses: 'json' (Qwen3) or 'xml' (Qwen3.5) */
|
|
270
|
+
format: 'json' | 'xml';
|
|
231
271
|
}
|
|
232
272
|
/** Per-step candidate filter for tool turns. Auto mode: free text (everything permitted) until
|
|
233
273
|
* the model opens <tool_call>, then the body grammar takes over until </tool_call>, then free
|
|
234
274
|
* text again (another call, prose, or eos). Forced mode: the FIRST token must be <tool_call>,
|
|
235
275
|
* the body is constrained to the named tool, and after </tool_call> only eos is permitted.
|
|
236
276
|
* Call advance() with each emitted token to move the real machine. */
|
|
237
|
-
declare function makeToolFilter(table: TokenByteTable, prep: PreparedTools): {
|
|
277
|
+
declare function makeToolFilter(table: TokenByteTable, prep: PreparedTools, startInThink?: boolean): {
|
|
238
278
|
filter: (ids: Uint32Array | number[]) => number[];
|
|
239
279
|
advance: (id: number) => void;
|
|
240
280
|
};
|
|
@@ -263,6 +303,11 @@ declare class ToolCallSplitter {
|
|
|
263
303
|
/** Parse one block's content into a ToolCall. With enforcement on this cannot fail for a
|
|
264
304
|
* completed block; a failure (unenforced or truncated content) yields name '' and the raw text. */
|
|
265
305
|
declare function parseToolCall(raw: string): ToolCall;
|
|
306
|
+
/** Parse one XML block's content into a ToolCall (the Qwen3.5 `<function=…><parameter=…>` protocol).
|
|
307
|
+
* Values are coerced by the tool's schema - string params keep their raw text, everything else is
|
|
308
|
+
* JSON.parse'd. Returns name '' if the block names an unknown tool/property, a required property is
|
|
309
|
+
* missing, or a non-string value is not valid JSON (so a surfaced call always conforms). */
|
|
310
|
+
declare function parseToolCallXml(raw: string, tools: readonly ChatTool[]): ToolCall;
|
|
266
311
|
//#endregion
|
|
267
312
|
//#region src/chat/think.d.ts
|
|
268
313
|
interface SplitChunk {
|
|
@@ -276,7 +321,11 @@ declare class ThinkSplitter {
|
|
|
276
321
|
private readonly close;
|
|
277
322
|
private inside;
|
|
278
323
|
private hold;
|
|
279
|
-
constructor(open?: string, close?: string
|
|
324
|
+
constructor(open?: string, close?: string,
|
|
325
|
+
/** Start already inside a think block - for templates whose generation prompt PRE-OPENS `<think>`
|
|
326
|
+
* (e.g. Qwen3.5 thinking mode), so the opening tag is in the prompt, not the generated stream. */
|
|
327
|
+
|
|
328
|
+
startInside?: boolean);
|
|
280
329
|
push(chunk: string): SplitChunk;
|
|
281
330
|
/** Emit whatever is held back. An unterminated think block (generation hit maxTokens inside it)
|
|
282
331
|
* flushes to the think channel, never to the visible reply. */
|
|
@@ -320,7 +369,9 @@ interface ChatSendOptions {
|
|
|
320
369
|
temperature?: number;
|
|
321
370
|
topK?: number;
|
|
322
371
|
topP?: number;
|
|
372
|
+
minP?: number;
|
|
323
373
|
repetitionPenalty?: number;
|
|
374
|
+
presencePenalty?: number;
|
|
324
375
|
noRepeatNgramSize?: number;
|
|
325
376
|
seed?: number;
|
|
326
377
|
promptLookup?: GenerateOptions['promptLookup'];
|
|
@@ -475,5 +526,5 @@ interface Chat {
|
|
|
475
526
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
476
527
|
declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
|
|
477
528
|
//#endregion
|
|
478
|
-
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatSnapshot, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, ToolBodyMachine, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
|
|
529
|
+
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatSnapshot, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
|
|
479
530
|
//# sourceMappingURL=chat.d.ts.map
|
package/dist/chat.js
CHANGED
|
@@ -4308,11 +4308,12 @@ function holdback$1(s, tag) {
|
|
|
4308
4308
|
var ThinkSplitter = class {
|
|
4309
4309
|
open;
|
|
4310
4310
|
close;
|
|
4311
|
-
inside
|
|
4311
|
+
inside;
|
|
4312
4312
|
hold = "";
|
|
4313
|
-
constructor(open = "<think>", close = "</think>") {
|
|
4313
|
+
constructor(open = "<think>", close = "</think>", startInside = false) {
|
|
4314
4314
|
this.open = open;
|
|
4315
4315
|
this.close = close;
|
|
4316
|
+
this.inside = startInside;
|
|
4316
4317
|
}
|
|
4317
4318
|
push(chunk) {
|
|
4318
4319
|
let s = this.hold + chunk;
|
|
@@ -5181,18 +5182,176 @@ var ToolBodyMachine = class ToolBodyMachine {
|
|
|
5181
5182
|
}
|
|
5182
5183
|
}
|
|
5183
5184
|
};
|
|
5185
|
+
const X_FUNC = utf8.encode("<function=");
|
|
5186
|
+
const X_PARAM = utf8.encode("<parameter=");
|
|
5187
|
+
const X_FCLOSE = utf8.encode("</function>");
|
|
5188
|
+
const X_PCLOSE = utf8.encode("</parameter>");
|
|
5189
|
+
const litPrefix = (buf, lit) => {
|
|
5190
|
+
if (buf.length > lit.length) return false;
|
|
5191
|
+
for (let i = 0; i < buf.length; i++) if (buf[i] !== lit[i]) return false;
|
|
5192
|
+
return true;
|
|
5193
|
+
};
|
|
5194
|
+
const litEq = (buf, lit) => buf.length === lit.length && litPrefix(buf, lit);
|
|
5195
|
+
var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
5196
|
+
cands;
|
|
5197
|
+
props;
|
|
5198
|
+
phase = 0;
|
|
5199
|
+
lit = 0;
|
|
5200
|
+
nameBuf = "";
|
|
5201
|
+
wsRun = 0;
|
|
5202
|
+
elem = [];
|
|
5203
|
+
keyBuf = "";
|
|
5204
|
+
keyCands = [];
|
|
5205
|
+
reqLeft = [];
|
|
5206
|
+
valTail = [];
|
|
5207
|
+
valStarted = false;
|
|
5208
|
+
complete = false;
|
|
5209
|
+
name = "";
|
|
5210
|
+
/** byte-space tool names, and per name its byte-space property keys + required subset */
|
|
5211
|
+
constructor(cands, props) {
|
|
5212
|
+
this.cands = cands;
|
|
5213
|
+
this.props = props;
|
|
5214
|
+
}
|
|
5215
|
+
clone() {
|
|
5216
|
+
const m = new ToolBodyMachineXml(this.cands, this.props);
|
|
5217
|
+
m.phase = this.phase;
|
|
5218
|
+
m.lit = this.lit;
|
|
5219
|
+
m.nameBuf = this.nameBuf;
|
|
5220
|
+
m.wsRun = this.wsRun;
|
|
5221
|
+
m.elem = [...this.elem];
|
|
5222
|
+
m.keyBuf = this.keyBuf;
|
|
5223
|
+
m.keyCands = [...this.keyCands];
|
|
5224
|
+
m.reqLeft = [...this.reqLeft];
|
|
5225
|
+
m.valTail = [...this.valTail];
|
|
5226
|
+
m.valStarted = this.valStarted;
|
|
5227
|
+
m.complete = this.complete;
|
|
5228
|
+
m.name = this.name;
|
|
5229
|
+
return m;
|
|
5230
|
+
}
|
|
5231
|
+
feed(bytes) {
|
|
5232
|
+
for (let i = 0; i < bytes.length; i++) if (!this.byte(bytes[i])) return false;
|
|
5233
|
+
return true;
|
|
5234
|
+
}
|
|
5235
|
+
forcedNext() {
|
|
5236
|
+
switch (this.phase) {
|
|
5237
|
+
case 2: return this.cands.includes(this.nameBuf) && !this.cands.some((c) => c !== this.nameBuf && c.startsWith(this.nameBuf)) ? 62 : -1;
|
|
5238
|
+
case 4: return this.keyCands.length > 0 && this.keyCands.includes(this.keyBuf) && !this.keyCands.some((c) => c !== this.keyBuf && c.startsWith(this.keyBuf)) ? 62 : -1;
|
|
5239
|
+
case 3: return this.elem.length === 0 && this.wsRun === 0 ? 10 : -1;
|
|
5240
|
+
case 5: return this.wsRun === 0 ? 10 : -1;
|
|
5241
|
+
default: return -1;
|
|
5242
|
+
}
|
|
5243
|
+
}
|
|
5244
|
+
byte(b) {
|
|
5245
|
+
switch (this.phase) {
|
|
5246
|
+
case 0:
|
|
5247
|
+
if (WS.has(b)) return ++this.wsRun <= WS_CAP;
|
|
5248
|
+
if (b !== X_FUNC[0]) return false;
|
|
5249
|
+
this.phase = 1;
|
|
5250
|
+
this.lit = 1;
|
|
5251
|
+
return true;
|
|
5252
|
+
case 1:
|
|
5253
|
+
if (b !== X_FUNC[this.lit]) return false;
|
|
5254
|
+
if (++this.lit === X_FUNC.length) {
|
|
5255
|
+
this.phase = 2;
|
|
5256
|
+
this.nameBuf = "";
|
|
5257
|
+
}
|
|
5258
|
+
return true;
|
|
5259
|
+
case 2:
|
|
5260
|
+
if (b === 62) {
|
|
5261
|
+
if (!this.cands.includes(this.nameBuf)) return false;
|
|
5262
|
+
this.name = this.nameBuf;
|
|
5263
|
+
const spec = this.props.get(this.nameBuf);
|
|
5264
|
+
this.keyCands = [...spec?.keys ?? []];
|
|
5265
|
+
this.reqLeft = [...spec?.required ?? []];
|
|
5266
|
+
this.phase = 3;
|
|
5267
|
+
this.elem = [];
|
|
5268
|
+
this.wsRun = 0;
|
|
5269
|
+
return true;
|
|
5270
|
+
}
|
|
5271
|
+
this.nameBuf += String.fromCharCode(b);
|
|
5272
|
+
for (const c of this.cands) if (c.startsWith(this.nameBuf)) return true;
|
|
5273
|
+
return false;
|
|
5274
|
+
case 3: {
|
|
5275
|
+
if (this.elem.length === 0 && this.wsRun === 0) {
|
|
5276
|
+
if (b !== 10) return false;
|
|
5277
|
+
this.wsRun = 1;
|
|
5278
|
+
return true;
|
|
5279
|
+
}
|
|
5280
|
+
this.elem.push(b);
|
|
5281
|
+
if (litEq(this.elem, X_PARAM)) {
|
|
5282
|
+
this.phase = 4;
|
|
5283
|
+
this.keyBuf = "";
|
|
5284
|
+
return true;
|
|
5285
|
+
}
|
|
5286
|
+
if (litEq(this.elem, X_FCLOSE)) {
|
|
5287
|
+
if (this.reqLeft.length) return false;
|
|
5288
|
+
this.phase = 6;
|
|
5289
|
+
this.complete = true;
|
|
5290
|
+
this.wsRun = 0;
|
|
5291
|
+
return true;
|
|
5292
|
+
}
|
|
5293
|
+
const pP = litPrefix(this.elem, X_PARAM);
|
|
5294
|
+
const pF = litPrefix(this.elem, X_FCLOSE);
|
|
5295
|
+
if (pF && !pP && this.reqLeft.length) return false;
|
|
5296
|
+
return pP || pF;
|
|
5297
|
+
}
|
|
5298
|
+
case 4:
|
|
5299
|
+
if (b === 62) {
|
|
5300
|
+
if (this.keyCands.length && !this.keyCands.includes(this.keyBuf)) return false;
|
|
5301
|
+
this.keyCands = this.keyCands.filter((k) => k !== this.keyBuf);
|
|
5302
|
+
this.reqLeft = this.reqLeft.filter((k) => k !== this.keyBuf);
|
|
5303
|
+
this.phase = 5;
|
|
5304
|
+
this.valTail = [];
|
|
5305
|
+
this.wsRun = 0;
|
|
5306
|
+
this.valStarted = false;
|
|
5307
|
+
return true;
|
|
5308
|
+
}
|
|
5309
|
+
this.keyBuf += String.fromCharCode(b);
|
|
5310
|
+
if (!this.keyCands.length) return true;
|
|
5311
|
+
for (const c of this.keyCands) if (c.startsWith(this.keyBuf)) return true;
|
|
5312
|
+
return false;
|
|
5313
|
+
case 5:
|
|
5314
|
+
if (this.wsRun === 0) {
|
|
5315
|
+
if (b !== 10) return false;
|
|
5316
|
+
this.wsRun = 1;
|
|
5317
|
+
return true;
|
|
5318
|
+
}
|
|
5319
|
+
if (!this.valStarted) {
|
|
5320
|
+
if (b === 10) return false;
|
|
5321
|
+
this.valStarted = true;
|
|
5322
|
+
}
|
|
5323
|
+
this.valTail.push(b);
|
|
5324
|
+
if (this.valTail.length > X_PCLOSE.length) this.valTail.shift();
|
|
5325
|
+
if (litEq(this.valTail, X_PCLOSE)) {
|
|
5326
|
+
this.phase = 3;
|
|
5327
|
+
this.elem = [];
|
|
5328
|
+
this.wsRun = 0;
|
|
5329
|
+
}
|
|
5330
|
+
return true;
|
|
5331
|
+
case 6: return WS.has(b) && ++this.wsRun <= WS_CAP;
|
|
5332
|
+
}
|
|
5333
|
+
}
|
|
5334
|
+
};
|
|
5184
5335
|
/** Per-step candidate filter for tool turns. Auto mode: free text (everything permitted) until
|
|
5185
5336
|
* the model opens <tool_call>, then the body grammar takes over until </tool_call>, then free
|
|
5186
5337
|
* text again (another call, prose, or eos). Forced mode: the FIRST token must be <tool_call>,
|
|
5187
5338
|
* the body is constrained to the named tool, and after </tool_call> only eos is permitted.
|
|
5188
5339
|
* Call advance() with each emitted token to move the real machine. */
|
|
5189
|
-
function makeToolFilter(table, prep) {
|
|
5340
|
+
function makeToolFilter(table, prep, startInThink = false) {
|
|
5190
5341
|
const { ids, forced } = prep;
|
|
5191
5342
|
const cands = (forced ? prep.tools.filter((t) => t.function.name === forced) : prep.tools).map((t) => t.function.name).map(ToolBodyMachine.bytesOf);
|
|
5192
5343
|
const schemas = new Map(prep.tools.map((t) => [ToolBodyMachine.bytesOf(t.function.name), argsSchemaOf(t)]));
|
|
5344
|
+
const props = new Map(prep.tools.map((t) => {
|
|
5345
|
+
const p = t.function.parameters;
|
|
5346
|
+
return [ToolBodyMachine.bytesOf(t.function.name), {
|
|
5347
|
+
keys: Object.keys(p?.properties ?? {}).map(ToolBodyMachine.bytesOf),
|
|
5348
|
+
required: (p?.required ?? []).map(ToolBodyMachine.bytesOf)
|
|
5349
|
+
}];
|
|
5350
|
+
}));
|
|
5351
|
+
const newBody = () => prep.format === "xml" ? new ToolBodyMachineXml(cands, props) : new ToolBodyMachine(cands, schemas);
|
|
5193
5352
|
let state = forced ? 1 : 0;
|
|
5194
5353
|
let body = null;
|
|
5195
|
-
let inThink =
|
|
5354
|
+
let inThink = startInThink;
|
|
5196
5355
|
return {
|
|
5197
5356
|
filter: (candidates) => {
|
|
5198
5357
|
if (state === 0 || inThink) return Array.from(candidates, Number);
|
|
@@ -5214,6 +5373,11 @@ function makeToolFilter(table, prep) {
|
|
|
5214
5373
|
}
|
|
5215
5374
|
const bytes = table.bytes(n);
|
|
5216
5375
|
if (!bytes || bytes.length === 0) continue;
|
|
5376
|
+
const fb = m.forcedNext?.() ?? -1;
|
|
5377
|
+
if (fb >= 0) {
|
|
5378
|
+
if (bytes.length === 1 && bytes[0] === fb) out.push(n);
|
|
5379
|
+
continue;
|
|
5380
|
+
}
|
|
5217
5381
|
if (m.clone().feed(bytes)) out.push(n);
|
|
5218
5382
|
}
|
|
5219
5383
|
return out;
|
|
@@ -5233,7 +5397,7 @@ function makeToolFilter(table, prep) {
|
|
|
5233
5397
|
case 1:
|
|
5234
5398
|
if (id === ids.open) {
|
|
5235
5399
|
state = 2;
|
|
5236
|
-
body =
|
|
5400
|
+
body = newBody();
|
|
5237
5401
|
}
|
|
5238
5402
|
return;
|
|
5239
5403
|
case 2:
|
|
@@ -5346,6 +5510,63 @@ function parseToolCall(raw) {
|
|
|
5346
5510
|
raw
|
|
5347
5511
|
};
|
|
5348
5512
|
}
|
|
5513
|
+
/** Parse one XML block's content into a ToolCall (the Qwen3.5 `<function=…><parameter=…>` protocol).
|
|
5514
|
+
* Values are coerced by the tool's schema - string params keep their raw text, everything else is
|
|
5515
|
+
* JSON.parse'd. Returns name '' if the block names an unknown tool/property, a required property is
|
|
5516
|
+
* missing, or a non-string value is not valid JSON (so a surfaced call always conforms). */
|
|
5517
|
+
function parseToolCallXml(raw, tools) {
|
|
5518
|
+
const fn = /<function=([^>]*)>/.exec(raw);
|
|
5519
|
+
if (!fn) return {
|
|
5520
|
+
name: "",
|
|
5521
|
+
arguments: {},
|
|
5522
|
+
raw
|
|
5523
|
+
};
|
|
5524
|
+
const name = fn[1];
|
|
5525
|
+
const tool = tools.find((t) => t.function.name === name);
|
|
5526
|
+
if (!tool) return {
|
|
5527
|
+
name: "",
|
|
5528
|
+
arguments: {},
|
|
5529
|
+
raw
|
|
5530
|
+
};
|
|
5531
|
+
const schema = tool.function.parameters;
|
|
5532
|
+
const props = schema?.properties ?? {};
|
|
5533
|
+
const args = {};
|
|
5534
|
+
const re = /<parameter=([^>]*)>([\s\S]*?)<\/parameter>/g;
|
|
5535
|
+
for (let m = re.exec(raw); m !== null; m = re.exec(raw)) {
|
|
5536
|
+
const key = m[1];
|
|
5537
|
+
const valText = m[2].replace(/^\n/, "").replace(/\n$/, "");
|
|
5538
|
+
const pschema = props[key];
|
|
5539
|
+
if (pschema?.type !== void 0 && pschema.type !== "string") try {
|
|
5540
|
+
args[key] = JSON.parse(valText);
|
|
5541
|
+
} catch {
|
|
5542
|
+
return {
|
|
5543
|
+
name: "",
|
|
5544
|
+
arguments: {},
|
|
5545
|
+
raw
|
|
5546
|
+
};
|
|
5547
|
+
}
|
|
5548
|
+
else args[key] = valText;
|
|
5549
|
+
}
|
|
5550
|
+
if (schema) {
|
|
5551
|
+
for (const req of schema.required ?? []) if (!(req in args)) return {
|
|
5552
|
+
name: "",
|
|
5553
|
+
arguments: {},
|
|
5554
|
+
raw
|
|
5555
|
+
};
|
|
5556
|
+
if (schema.additionalProperties === false) {
|
|
5557
|
+
for (const k of Object.keys(args)) if (!(k in props)) return {
|
|
5558
|
+
name: "",
|
|
5559
|
+
arguments: {},
|
|
5560
|
+
raw
|
|
5561
|
+
};
|
|
5562
|
+
}
|
|
5563
|
+
}
|
|
5564
|
+
return {
|
|
5565
|
+
name,
|
|
5566
|
+
arguments: args,
|
|
5567
|
+
raw
|
|
5568
|
+
};
|
|
5569
|
+
}
|
|
5349
5570
|
//#endregion
|
|
5350
5571
|
//#region src/chat/index.ts
|
|
5351
5572
|
function deriveChatWrap(tk) {
|
|
@@ -5422,6 +5643,21 @@ async function createChat(engine, options) {
|
|
|
5422
5643
|
tk = new ChatTokenizer(json, cfg);
|
|
5423
5644
|
}
|
|
5424
5645
|
const wrap = deriveChatWrap(tk);
|
|
5646
|
+
const thinkPreopened = (() => {
|
|
5647
|
+
if (!tk.hasChatTemplate) return false;
|
|
5648
|
+
try {
|
|
5649
|
+
const r = tk.applyChatTemplate([{
|
|
5650
|
+
role: "user",
|
|
5651
|
+
content: "x"
|
|
5652
|
+
}], {
|
|
5653
|
+
addGenerationPrompt: true,
|
|
5654
|
+
enableThinking: true
|
|
5655
|
+
});
|
|
5656
|
+
return r.lastIndexOf("<think>") > r.lastIndexOf("</think>");
|
|
5657
|
+
} catch {
|
|
5658
|
+
return false;
|
|
5659
|
+
}
|
|
5660
|
+
})();
|
|
5425
5661
|
let committed = null;
|
|
5426
5662
|
let cacheEndsAtEos = false;
|
|
5427
5663
|
let committedToolsKey = null;
|
|
@@ -5434,6 +5670,7 @@ async function createChat(engine, options) {
|
|
|
5434
5670
|
engine.resetCache();
|
|
5435
5671
|
};
|
|
5436
5672
|
let templateToolsOk = null;
|
|
5673
|
+
let toolFormat = "json";
|
|
5437
5674
|
function prepareTools(tools, choice) {
|
|
5438
5675
|
validateTools(tools, choice);
|
|
5439
5676
|
if (templateToolsOk === null) try {
|
|
@@ -5448,6 +5685,7 @@ async function createChat(engine, options) {
|
|
|
5448
5685
|
}]
|
|
5449
5686
|
});
|
|
5450
5687
|
templateToolsOk = probe.includes("bitgpu_probe_tool") && probe.includes("<tool_call>");
|
|
5688
|
+
toolFormat = probe.includes("<function=") ? "xml" : "json";
|
|
5451
5689
|
} catch {
|
|
5452
5690
|
templateToolsOk = false;
|
|
5453
5691
|
}
|
|
@@ -5458,6 +5696,7 @@ async function createChat(engine, options) {
|
|
|
5458
5696
|
return {
|
|
5459
5697
|
tools,
|
|
5460
5698
|
forced: typeof choice === "object" ? choice.name : null,
|
|
5699
|
+
format: toolFormat,
|
|
5461
5700
|
ids: {
|
|
5462
5701
|
open,
|
|
5463
5702
|
close,
|
|
@@ -5489,7 +5728,7 @@ async function createChat(engine, options) {
|
|
|
5489
5728
|
const wantReuse = (o.reuseCache ?? true) && !think && wrap !== null && toolsKey === committedToolsKey;
|
|
5490
5729
|
const userAppend = wantReuse && isCleanAppend(committed, messages);
|
|
5491
5730
|
const toolAppend = wantReuse && !userAppend && isToolAppend(committed, messages);
|
|
5492
|
-
|
|
5731
|
+
let canReuse = userAppend || toolAppend;
|
|
5493
5732
|
let inputTokenIds;
|
|
5494
5733
|
if (userAppend) {
|
|
5495
5734
|
const w = wrap;
|
|
@@ -5498,11 +5737,36 @@ async function createChat(engine, options) {
|
|
|
5498
5737
|
inputTokenIds = tk.encode(deltaStr, false);
|
|
5499
5738
|
} else if (toolAppend) {
|
|
5500
5739
|
const toolMsgs = messages.slice(committed.length);
|
|
5501
|
-
|
|
5502
|
-
|
|
5503
|
-
|
|
5504
|
-
|
|
5505
|
-
|
|
5740
|
+
let deltaStr = null;
|
|
5741
|
+
try {
|
|
5742
|
+
deltaStr = `${cacheEndsAtEos ? "" : tk.eosToken}\n` + tk.applyChatTemplate(toolMsgs, {
|
|
5743
|
+
addGenerationPrompt: true,
|
|
5744
|
+
enableThinking: false
|
|
5745
|
+
});
|
|
5746
|
+
} catch {
|
|
5747
|
+
const tools = prep?.tools;
|
|
5748
|
+
const fullNew = tk.applyChatTemplate(messages, {
|
|
5749
|
+
addGenerationPrompt: true,
|
|
5750
|
+
enableThinking: false,
|
|
5751
|
+
tools
|
|
5752
|
+
});
|
|
5753
|
+
const committedRender = tk.applyChatTemplate(committed, {
|
|
5754
|
+
addGenerationPrompt: false,
|
|
5755
|
+
enableThinking: false,
|
|
5756
|
+
tools
|
|
5757
|
+
}).replace(/\n$/, "");
|
|
5758
|
+
if (fullNew.startsWith(committedRender)) deltaStr = `${cacheEndsAtEos ? "" : tk.eosToken}` + fullNew.slice(committedRender.length);
|
|
5759
|
+
}
|
|
5760
|
+
if (deltaStr !== null) inputTokenIds = tk.encode(deltaStr, false);
|
|
5761
|
+
else {
|
|
5762
|
+
dropCache();
|
|
5763
|
+
canReuse = false;
|
|
5764
|
+
inputTokenIds = tk.encode(tk.applyChatTemplate(messages, {
|
|
5765
|
+
addGenerationPrompt: true,
|
|
5766
|
+
enableThinking: think,
|
|
5767
|
+
tools: prep?.tools
|
|
5768
|
+
}), false);
|
|
5769
|
+
}
|
|
5506
5770
|
} else {
|
|
5507
5771
|
dropCache();
|
|
5508
5772
|
inputTokenIds = tk.encode(tk.applyChatTemplate(messages, {
|
|
@@ -5512,7 +5776,7 @@ async function createChat(engine, options) {
|
|
|
5512
5776
|
}), false);
|
|
5513
5777
|
}
|
|
5514
5778
|
const decoder = tk.createDecoderStream(true);
|
|
5515
|
-
const splitter = new ThinkSplitter();
|
|
5779
|
+
const splitter = new ThinkSplitter("<think>", "</think>", think && thinkPreopened);
|
|
5516
5780
|
const stops = o.stopSequences?.length ? new StopScanner(o.stopSequences) : null;
|
|
5517
5781
|
const stopCtl = stops ? new AbortController() : null;
|
|
5518
5782
|
const signal = stopCtl ? o.signal ? AbortSignal.any([o.signal, stopCtl.signal]) : stopCtl.signal : o.signal;
|
|
@@ -5521,7 +5785,7 @@ async function createChat(engine, options) {
|
|
|
5521
5785
|
const toolSplit = prep ? new ToolCallSplitter() : null;
|
|
5522
5786
|
const toolCalls = [];
|
|
5523
5787
|
const pushBlock = (block) => {
|
|
5524
|
-
const call = parseToolCall(block);
|
|
5788
|
+
const call = prep?.format === "xml" ? parseToolCallXml(block, prep.tools) : parseToolCall(block);
|
|
5525
5789
|
toolCalls.push(call);
|
|
5526
5790
|
if (call.name) o.onToolCall?.(call);
|
|
5527
5791
|
};
|
|
@@ -5548,7 +5812,7 @@ async function createChat(engine, options) {
|
|
|
5548
5812
|
const maxTokens = o.maxTokens ?? (think ? 1024 : 512);
|
|
5549
5813
|
const epoch0 = resetEpoch;
|
|
5550
5814
|
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
|
|
5551
|
-
const tf = prep ? makeToolFilter(byteTable ??= new TokenByteTable(tk), prep) : null;
|
|
5815
|
+
const tf = prep ? makeToolFilter(byteTable ??= new TokenByteTable(tk), prep, think && thinkPreopened) : null;
|
|
5552
5816
|
let result;
|
|
5553
5817
|
try {
|
|
5554
5818
|
result = await engine.generate(inputTokenIds, {
|
|
@@ -5556,7 +5820,9 @@ async function createChat(engine, options) {
|
|
|
5556
5820
|
temperature: o.temperature,
|
|
5557
5821
|
topK: o.topK,
|
|
5558
5822
|
topP: o.topP,
|
|
5823
|
+
minP: o.minP,
|
|
5559
5824
|
repetitionPenalty: o.repetitionPenalty,
|
|
5825
|
+
presencePenalty: o.presencePenalty,
|
|
5560
5826
|
noRepeatNgramSize: o.noRepeatNgramSize,
|
|
5561
5827
|
seed: o.seed,
|
|
5562
5828
|
logprobs: o.logprobs,
|
|
@@ -5727,6 +5993,6 @@ async function createChat(engine, options) {
|
|
|
5727
5993
|
};
|
|
5728
5994
|
}
|
|
5729
5995
|
//#endregion
|
|
5730
|
-
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, ToolBodyMachine, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, validateJsonSchema, validateTools };
|
|
5996
|
+
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
|
|
5731
5997
|
|
|
5732
5998
|
//# sourceMappingURL=chat.js.map
|