bitgpu 0.17.0 → 0.19.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 +35 -2
- package/dist/chat.d.ts +78 -7
- package/dist/chat.js +159 -9
- 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 +189 -32
- package/dist/index.js.map +1 -1
- package/dist/{types-BkfIJ42d.d.ts → types-CBW7T_3s.d.ts} +27 -1
- package/package.json +2 -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.19.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`,
|
|
@@ -105,6 +105,18 @@ await engine.generate(promptTokenIds, { temperature: 0.5, topK: 20, repetitionPe
|
|
|
105
105
|
// presencePenalty (flat subtraction on seen tokens - the Qwen3.5 family's anti-repetition knob).
|
|
106
106
|
await engine.generate(promptTokenIds, { temperature: 0.5, topP: 0.85, topK: 20, minP: 0.05, presencePenalty: 1.5 })
|
|
107
107
|
|
|
108
|
+
// DRY ("don't repeat yourself"): penalizes only tokens that would EXTEND a repeated sequence
|
|
109
|
+
// (exponentially in the repeat length), so verbatim loops break while ordinary word reuse is
|
|
110
|
+
// untouched. Off by default; sequence-breaker token ids exempt structural tokens (bitgpu/chat
|
|
111
|
+
// fills them from the tokenizer automatically). Not combinable with promptLookup.
|
|
112
|
+
await engine.generate(promptTokenIds, { temperature: 0.5, dryMultiplier: 0.8, dryAllowedLength: 2 })
|
|
113
|
+
|
|
114
|
+
// Top-n-sigma (arXiv 2411.07641): keep candidates within n standard deviations of the max logit,
|
|
115
|
+
// with sigma computed ON THE GPU over the full penalized logit vector (not a top-K estimate) -
|
|
116
|
+
// the cutoff adapts to how peaked the distribution actually is, which suits low-precision models.
|
|
117
|
+
// Off by default (bit-identical draw when unset). Typical n: 1.0-1.5.
|
|
118
|
+
await engine.generate(promptTokenIds, { temperature: 0.5, topNSigma: 1.0 })
|
|
119
|
+
|
|
108
120
|
// Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
|
|
109
121
|
// exactly like transformers.js greedy search:
|
|
110
122
|
await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
|
|
@@ -229,6 +241,19 @@ reuse with exact token bookkeeping (a clean follow-up turn prefills only the del
|
|
|
229
241
|
`chat.prewarm(messages)` warms a static system prompt at load). `chat.reset()` forgets the
|
|
230
242
|
conversation.
|
|
231
243
|
|
|
244
|
+
`thinkBudget: N` caps the reasoning phase: after N generated think tokens only `</think>` may be
|
|
245
|
+
emitted, so the model wraps up and answers - "budget forcing", the practical way to run thinking
|
|
246
|
+
mode on-device where every token is slow. `thinkBudget: 0` keeps the thinking template but
|
|
247
|
+
suppresses reasoning entirely. `thinkEarlyStop: true` adds an ADAPTIVE cut that composes with the
|
|
248
|
+
hard cap: when the model has been decisively confident (top-1 vs top-2 logit gap) for a sustained
|
|
249
|
+
run of think tokens - the signature of rote continuation rather than active reasoning - the close
|
|
250
|
+
is forced early. Defaults were calibrated against the real Bonsai-27B on an A100 reference
|
|
251
|
+
(tools/eval-thinkstop-modal.py): unbounded thinking scored WORST there (67% accuracy, ~900 think
|
|
252
|
+
tokens, a third of the problems rambling forever), the adaptive stop reached 75% at ~244 tokens -
|
|
253
|
+
and a plain `thinkBudget: 128` scored best of all (83%). So: reach for the hard cap first; use
|
|
254
|
+
`thinkEarlyStop` (alone or composed with a generous cap) for mixed-difficulty workloads where a
|
|
255
|
+
single cap cannot fit every question. Pass `{ gap, window, minTokens }` to tune.
|
|
256
|
+
|
|
232
257
|
### Guaranteed-valid JSON (`format: 'json'`)
|
|
233
258
|
|
|
234
259
|
```ts
|
|
@@ -298,7 +323,11 @@ declared tools and the arguments are forced through that tool's `parameters` sch
|
|
|
298
323
|
token-by-token. Both Qwen wire formats are supported and auto-detected from the chat template:
|
|
299
324
|
the Qwen3 JSON shape (`<tool_call>{"name": …, "arguments": …}</tool_call>` - the dense Bonsai
|
|
300
325
|
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.
|
|
326
|
+
Bonsai-27B), so the same `tools` array works across all of them. In the XML format each
|
|
327
|
+
parameter's VALUE is constrained by its own schema: a `number`/`integer`/`boolean`/`array`/
|
|
328
|
+
`object` parameter is forced to be exactly that (JSON grammar, including integer bounds and
|
|
329
|
+
array item schemas), a string `enum` is forced onto one of its literals, and plain strings stay
|
|
330
|
+
free text - the model cannot hand your tool `abc` where a number belongs.
|
|
302
331
|
|
|
303
332
|
```ts
|
|
304
333
|
const tools = [{
|
|
@@ -521,6 +550,10 @@ ln -s /path/to/bonsai-model examples/model-1.7b # or copy the files in
|
|
|
521
550
|
npm run build
|
|
522
551
|
npm run verify:headless # serves the repo itself + drives system Chrome headlessly
|
|
523
552
|
FAST=1 npm run verify:headless # dev iteration: baseline model, core sections only (~3 min; NOT a release gate)
|
|
553
|
+
npm run test:27b # LIVE Bonsai-27B gate: streams the real 3.8 GB weights (nothing persisted),
|
|
554
|
+
# proves long-prompt segment parity + typed tool calling at real scale -
|
|
555
|
+
# the classes the tiny synth hybrid cannot catch (silent scratch-VRAM OOM
|
|
556
|
+
# only exists at ~31.5 MB/token). Run before releases touching the hybrid.
|
|
524
557
|
```
|
|
525
558
|
|
|
526
559
|
Or serve the repo root (`python3 -m http.server 8000`) and open
|
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-CBW7T_3s.js";
|
|
2
2
|
|
|
3
3
|
//#region src/chat/tokenizer.d.ts
|
|
4
4
|
interface ChatMessage {
|
|
@@ -229,6 +229,13 @@ interface ToolBody {
|
|
|
229
229
|
* which a 1-bit model cannot recover from). -1 = free position. */
|
|
230
230
|
forcedNext?(): number;
|
|
231
231
|
}
|
|
232
|
+
/** Per-tool spec the XML machine constrains against (all string keys/literals in BYTE space). */
|
|
233
|
+
interface XmlToolProps {
|
|
234
|
+
keys: readonly string[];
|
|
235
|
+
required: readonly string[];
|
|
236
|
+
/** byte-space property key -> that parameter's schema (used to pick the value grammar). */
|
|
237
|
+
schemas?: ReadonlyMap<string, JsonSchema>;
|
|
238
|
+
}
|
|
232
239
|
declare class ToolBodyMachineXml implements ToolBody {
|
|
233
240
|
private readonly cands;
|
|
234
241
|
private readonly props;
|
|
@@ -242,13 +249,15 @@ declare class ToolBodyMachineXml implements ToolBody {
|
|
|
242
249
|
private reqLeft;
|
|
243
250
|
private valTail;
|
|
244
251
|
private valStarted;
|
|
252
|
+
private valMode;
|
|
253
|
+
private valBuf;
|
|
254
|
+
private valEnum;
|
|
255
|
+
private valJson;
|
|
256
|
+
private closeLit;
|
|
245
257
|
complete: boolean;
|
|
246
258
|
name: string;
|
|
247
|
-
/** byte-space tool names, and per name its
|
|
248
|
-
constructor(cands: readonly string[], props: ReadonlyMap<string,
|
|
249
|
-
keys: readonly string[];
|
|
250
|
-
required: readonly string[];
|
|
251
|
-
}>);
|
|
259
|
+
/** byte-space tool names, and per name its property keys / required subset / param schemas */
|
|
260
|
+
constructor(cands: readonly string[], props: ReadonlyMap<string, XmlToolProps>);
|
|
252
261
|
clone(): ToolBodyMachineXml;
|
|
253
262
|
feed(bytes: Uint8Array): boolean;
|
|
254
263
|
forcedNext(): number;
|
|
@@ -342,6 +351,43 @@ declare class StopScanner {
|
|
|
342
351
|
push(text: string): string;
|
|
343
352
|
flush(): string;
|
|
344
353
|
}
|
|
354
|
+
/** Confidence-based early stop for the think channel (training-free, DART-lineage heuristic). */
|
|
355
|
+
interface ThinkEarlyStop {
|
|
356
|
+
/** Logit gap (top1 - top2) that counts as a "confident" step. */
|
|
357
|
+
gap: number;
|
|
358
|
+
/** Consecutive confident steps required before firing. */
|
|
359
|
+
window: number;
|
|
360
|
+
/** Reasoning tokens that must be spent before early stop may fire (don't cut the model off
|
|
361
|
+
* before it has actually reasoned). */
|
|
362
|
+
minTokens: number;
|
|
363
|
+
}
|
|
364
|
+
/** Budget-forcing for the think channel (s1-style "budget forcing", training-free): counts the
|
|
365
|
+
* tokens generated inside a <think> block; once `budget` is spent - or the EARLY-STOP heuristic
|
|
366
|
+
* fires (the model has been decisively confident for `window` consecutive steps after
|
|
367
|
+
* `minTokens`, a signature of rote continuation rather than active reasoning) - `force()` names
|
|
368
|
+
* `</think>` as the only permitted candidate (the engine's constrained pick guarantees it is
|
|
369
|
+
* reachable even when outside the top-K), so the model closes its reasoning and continues
|
|
370
|
+
* straight into the visible answer. `budget: 0` suppresses reasoning entirely while keeping the
|
|
371
|
+
* thinking-mode template. advance() must see every emitted token; observe() should see each
|
|
372
|
+
* step's candidate logits (descending) BEFORE the pick - the filter callback receives exactly
|
|
373
|
+
* that. */
|
|
374
|
+
declare class ThinkBudget {
|
|
375
|
+
private readonly openId;
|
|
376
|
+
private readonly closeId;
|
|
377
|
+
private readonly budget;
|
|
378
|
+
private readonly early;
|
|
379
|
+
private inThink;
|
|
380
|
+
private spent;
|
|
381
|
+
private closed;
|
|
382
|
+
private run;
|
|
383
|
+
private earlyFired;
|
|
384
|
+
constructor(openId: number | undefined, closeId: number | undefined, budget: number, startInside: boolean, early?: ThinkEarlyStop | null);
|
|
385
|
+
advance(id: number): void;
|
|
386
|
+
/** Feed one step's candidate logits (descending). Only meaningful inside think. */
|
|
387
|
+
observe(vals: ArrayLike<number>): void;
|
|
388
|
+
/** The forced token id once the budget is exhausted or early stop fired, else null. */
|
|
389
|
+
force(): number | null;
|
|
390
|
+
}
|
|
345
391
|
//#endregion
|
|
346
392
|
//#region src/chat/index.d.ts
|
|
347
393
|
/** Options for {@link createChat}. Point it at the model directory (which already hosts
|
|
@@ -372,6 +418,15 @@ interface ChatSendOptions {
|
|
|
372
418
|
minP?: number;
|
|
373
419
|
repetitionPenalty?: number;
|
|
374
420
|
presencePenalty?: number;
|
|
421
|
+
/** DRY anti-loop penalty strength (see GenerateOptions.dryMultiplier). When set, the chat layer
|
|
422
|
+
* supplies sequence-breaker token ids from the tokenizer (newline/punctuation/list markers) so
|
|
423
|
+
* structural repetition is never penalized; pass `dryBreakers` to override. */
|
|
424
|
+
dryMultiplier?: number;
|
|
425
|
+
dryBase?: number;
|
|
426
|
+
dryAllowedLength?: number;
|
|
427
|
+
dryRange?: number;
|
|
428
|
+
dryBreakers?: number[];
|
|
429
|
+
topNSigma?: number;
|
|
375
430
|
noRepeatNgramSize?: number;
|
|
376
431
|
seed?: number;
|
|
377
432
|
promptLookup?: GenerateOptions['promptLookup'];
|
|
@@ -399,6 +454,22 @@ interface ChatSendOptions {
|
|
|
399
454
|
* turn drops the KV cache afterwards (the stripped reply cannot reproduce the cached tokens).
|
|
400
455
|
* Default false. */
|
|
401
456
|
think?: boolean;
|
|
457
|
+
/** Cap on reasoning length (thinking mode only): after this many generated think tokens the
|
|
458
|
+
* engine may only emit `</think>`, so the model wraps up and answers - "budget forcing" for
|
|
459
|
+
* slow on-device decode. `0` suppresses reasoning entirely (thinking template, no think
|
|
460
|
+
* tokens). Unset = unlimited. Ignored when `think` is off. */
|
|
461
|
+
thinkBudget?: number;
|
|
462
|
+
/** ADAPTIVE early stop for the reasoning phase (thinking mode only; composes with
|
|
463
|
+
* `thinkBudget`, which stays the hard cap): when the model has been decisively confident -
|
|
464
|
+
* top-1 vs top-2 logit gap >= `gap` - for `window` consecutive think tokens after at least
|
|
465
|
+
* `minTokens` of reasoning, `</think>` is forced and the answer begins. Sustained certainty
|
|
466
|
+
* inside a think block is the signature of rote continuation, not active reasoning; cutting
|
|
467
|
+
* there buys latency at little answer-quality cost. Pass `true` for the calibrated defaults. */
|
|
468
|
+
thinkEarlyStop?: boolean | {
|
|
469
|
+
gap?: number;
|
|
470
|
+
window?: number;
|
|
471
|
+
minTokens?: number;
|
|
472
|
+
};
|
|
402
473
|
/** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
|
|
403
474
|
onText?: (delta: string) => void;
|
|
404
475
|
/** Streamed think content (only meaningful with `think: true`). */
|
|
@@ -526,5 +597,5 @@ interface Chat {
|
|
|
526
597
|
/** Load the tokenizer files and return a {@link Chat} bound to the engine. */
|
|
527
598
|
declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
|
|
528
599
|
//#endregion
|
|
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 };
|
|
600
|
+
export { Chat, type ChatMessage, ChatOptions, ChatResult, ChatSendOptions, ChatSnapshot, ChatTokenizer, type ChatTool, type DecoderStream, JsonMachine, type JsonSchema, StopScanner, ThinkBudget, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, type ToolCall, ToolCallSplitter, type ToolChoice, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
|
|
530
601
|
//# sourceMappingURL=chat.d.ts.map
|
package/dist/chat.js
CHANGED
|
@@ -4399,6 +4399,59 @@ var StopScanner = class {
|
|
|
4399
4399
|
return r;
|
|
4400
4400
|
}
|
|
4401
4401
|
};
|
|
4402
|
+
/** Budget-forcing for the think channel (s1-style "budget forcing", training-free): counts the
|
|
4403
|
+
* tokens generated inside a <think> block; once `budget` is spent - or the EARLY-STOP heuristic
|
|
4404
|
+
* fires (the model has been decisively confident for `window` consecutive steps after
|
|
4405
|
+
* `minTokens`, a signature of rote continuation rather than active reasoning) - `force()` names
|
|
4406
|
+
* `</think>` as the only permitted candidate (the engine's constrained pick guarantees it is
|
|
4407
|
+
* reachable even when outside the top-K), so the model closes its reasoning and continues
|
|
4408
|
+
* straight into the visible answer. `budget: 0` suppresses reasoning entirely while keeping the
|
|
4409
|
+
* thinking-mode template. advance() must see every emitted token; observe() should see each
|
|
4410
|
+
* step's candidate logits (descending) BEFORE the pick - the filter callback receives exactly
|
|
4411
|
+
* that. */
|
|
4412
|
+
var ThinkBudget = class {
|
|
4413
|
+
openId;
|
|
4414
|
+
closeId;
|
|
4415
|
+
budget;
|
|
4416
|
+
early;
|
|
4417
|
+
inThink;
|
|
4418
|
+
spent = 0;
|
|
4419
|
+
closed = false;
|
|
4420
|
+
run = 0;
|
|
4421
|
+
earlyFired = false;
|
|
4422
|
+
constructor(openId, closeId, budget, startInside, early = null) {
|
|
4423
|
+
this.openId = openId;
|
|
4424
|
+
this.closeId = closeId;
|
|
4425
|
+
this.budget = budget;
|
|
4426
|
+
this.early = early;
|
|
4427
|
+
this.inThink = startInside;
|
|
4428
|
+
}
|
|
4429
|
+
advance(id) {
|
|
4430
|
+
if (this.closed) return;
|
|
4431
|
+
if (!this.inThink) {
|
|
4432
|
+
if (this.openId != null && id === this.openId) this.inThink = true;
|
|
4433
|
+
return;
|
|
4434
|
+
}
|
|
4435
|
+
if (this.closeId != null && id === this.closeId) {
|
|
4436
|
+
this.inThink = false;
|
|
4437
|
+
this.closed = true;
|
|
4438
|
+
return;
|
|
4439
|
+
}
|
|
4440
|
+
this.spent++;
|
|
4441
|
+
}
|
|
4442
|
+
/** Feed one step's candidate logits (descending). Only meaningful inside think. */
|
|
4443
|
+
observe(vals) {
|
|
4444
|
+
if (!this.early || !this.inThink || this.closed || this.earlyFired || vals.length < 2) return;
|
|
4445
|
+
const confident = vals[0] - vals[1] >= this.early.gap;
|
|
4446
|
+
this.run = confident ? this.run + 1 : 0;
|
|
4447
|
+
if (this.spent >= this.early.minTokens && this.run >= this.early.window) this.earlyFired = true;
|
|
4448
|
+
}
|
|
4449
|
+
/** The forced token id once the budget is exhausted or early stop fired, else null. */
|
|
4450
|
+
force() {
|
|
4451
|
+
if (!this.inThink || this.closed || this.closeId == null) return null;
|
|
4452
|
+
return this.spent >= this.budget || this.earlyFired ? this.closeId : null;
|
|
4453
|
+
}
|
|
4454
|
+
};
|
|
4402
4455
|
//#endregion
|
|
4403
4456
|
//#region src/chat/json.ts
|
|
4404
4457
|
const SUPPORTED = /* @__PURE__ */ new Set([
|
|
@@ -4758,10 +4811,13 @@ var JsonMachine = class JsonMachine {
|
|
|
4758
4811
|
byte(b) {
|
|
4759
4812
|
if (!WS$1.has(b)) this.wsRun = 0;
|
|
4760
4813
|
switch (this.phase) {
|
|
4761
|
-
case 0:
|
|
4814
|
+
case 0: {
|
|
4762
4815
|
if (WS$1.has(b)) return this.ws();
|
|
4763
4816
|
if (b === 123 || b === 91) return this.openValue(b);
|
|
4817
|
+
const rt = this.root?.type;
|
|
4818
|
+
if (rt !== void 0 && rt !== "object" && rt !== "array") return this.openValue(b);
|
|
4764
4819
|
return false;
|
|
4820
|
+
}
|
|
4765
4821
|
case 1:
|
|
4766
4822
|
if (WS$1.has(b)) return this.ws();
|
|
4767
4823
|
return this.openValue(b);
|
|
@@ -5205,9 +5261,14 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5205
5261
|
reqLeft = [];
|
|
5206
5262
|
valTail = [];
|
|
5207
5263
|
valStarted = false;
|
|
5264
|
+
valMode = "raw";
|
|
5265
|
+
valBuf = "";
|
|
5266
|
+
valEnum = [];
|
|
5267
|
+
valJson = null;
|
|
5268
|
+
closeLit = 0;
|
|
5208
5269
|
complete = false;
|
|
5209
5270
|
name = "";
|
|
5210
|
-
/** byte-space tool names, and per name its
|
|
5271
|
+
/** byte-space tool names, and per name its property keys / required subset / param schemas */
|
|
5211
5272
|
constructor(cands, props) {
|
|
5212
5273
|
this.cands = cands;
|
|
5213
5274
|
this.props = props;
|
|
@@ -5226,6 +5287,11 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5226
5287
|
m.valStarted = this.valStarted;
|
|
5227
5288
|
m.complete = this.complete;
|
|
5228
5289
|
m.name = this.name;
|
|
5290
|
+
m.valMode = this.valMode;
|
|
5291
|
+
m.valBuf = this.valBuf;
|
|
5292
|
+
m.valEnum = [...this.valEnum];
|
|
5293
|
+
m.valJson = this.valJson ? this.valJson.clone() : null;
|
|
5294
|
+
m.closeLit = this.closeLit;
|
|
5229
5295
|
return m;
|
|
5230
5296
|
}
|
|
5231
5297
|
feed(bytes) {
|
|
@@ -5237,7 +5303,10 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5237
5303
|
case 2: return this.cands.includes(this.nameBuf) && !this.cands.some((c) => c !== this.nameBuf && c.startsWith(this.nameBuf)) ? 62 : -1;
|
|
5238
5304
|
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
5305
|
case 3: return this.elem.length === 0 && this.wsRun === 0 ? 10 : -1;
|
|
5240
|
-
case 5:
|
|
5306
|
+
case 5:
|
|
5307
|
+
if (this.wsRun === 0) return 10;
|
|
5308
|
+
if (this.valMode === "enum" && this.valEnum.includes(this.valBuf) && !this.valEnum.some((c) => c !== this.valBuf && c.startsWith(this.valBuf))) return 10;
|
|
5309
|
+
return -1;
|
|
5241
5310
|
default: return -1;
|
|
5242
5311
|
}
|
|
5243
5312
|
}
|
|
@@ -5285,7 +5354,7 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5285
5354
|
}
|
|
5286
5355
|
if (litEq(this.elem, X_FCLOSE)) {
|
|
5287
5356
|
if (this.reqLeft.length) return false;
|
|
5288
|
-
this.phase =
|
|
5357
|
+
this.phase = 7;
|
|
5289
5358
|
this.complete = true;
|
|
5290
5359
|
this.wsRun = 0;
|
|
5291
5360
|
return true;
|
|
@@ -5304,6 +5373,16 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5304
5373
|
this.valTail = [];
|
|
5305
5374
|
this.wsRun = 0;
|
|
5306
5375
|
this.valStarted = false;
|
|
5376
|
+
const sch = this.props.get(this.name)?.schemas?.get(this.keyBuf);
|
|
5377
|
+
const t = sch?.type;
|
|
5378
|
+
if (sch && t !== void 0 && t !== "string") {
|
|
5379
|
+
this.valMode = "json";
|
|
5380
|
+
this.valJson = new JsonMachine(sch);
|
|
5381
|
+
} else if (sch?.enum?.length) {
|
|
5382
|
+
this.valMode = "enum";
|
|
5383
|
+
this.valBuf = "";
|
|
5384
|
+
this.valEnum = sch.enum.map(ToolBodyMachine.bytesOf);
|
|
5385
|
+
} else this.valMode = "raw";
|
|
5307
5386
|
return true;
|
|
5308
5387
|
}
|
|
5309
5388
|
this.keyBuf += String.fromCharCode(b);
|
|
@@ -5320,6 +5399,27 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5320
5399
|
if (b === 10) return false;
|
|
5321
5400
|
this.valStarted = true;
|
|
5322
5401
|
}
|
|
5402
|
+
if (this.valMode === "json") {
|
|
5403
|
+
const j = this.valJson;
|
|
5404
|
+
if (j.feed(Uint8Array.of(b))) return true;
|
|
5405
|
+
if (!j.complete || b !== X_PCLOSE[0]) return false;
|
|
5406
|
+
this.phase = 6;
|
|
5407
|
+
this.closeLit = 1;
|
|
5408
|
+
return true;
|
|
5409
|
+
}
|
|
5410
|
+
if (this.valMode === "enum") {
|
|
5411
|
+
const next = this.valBuf + String.fromCharCode(b);
|
|
5412
|
+
if (this.valEnum.some((c) => c.startsWith(next))) {
|
|
5413
|
+
this.valBuf = next;
|
|
5414
|
+
return true;
|
|
5415
|
+
}
|
|
5416
|
+
if (b === 10 && this.valEnum.includes(this.valBuf)) {
|
|
5417
|
+
this.phase = 6;
|
|
5418
|
+
this.closeLit = 0;
|
|
5419
|
+
return true;
|
|
5420
|
+
}
|
|
5421
|
+
return false;
|
|
5422
|
+
}
|
|
5323
5423
|
this.valTail.push(b);
|
|
5324
5424
|
if (this.valTail.length > X_PCLOSE.length) this.valTail.shift();
|
|
5325
5425
|
if (litEq(this.valTail, X_PCLOSE)) {
|
|
@@ -5328,7 +5428,15 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
|
|
|
5328
5428
|
this.wsRun = 0;
|
|
5329
5429
|
}
|
|
5330
5430
|
return true;
|
|
5331
|
-
case 6:
|
|
5431
|
+
case 6:
|
|
5432
|
+
if (b !== X_PCLOSE[this.closeLit]) return false;
|
|
5433
|
+
if (++this.closeLit === X_PCLOSE.length) {
|
|
5434
|
+
this.phase = 3;
|
|
5435
|
+
this.elem = [];
|
|
5436
|
+
this.wsRun = 0;
|
|
5437
|
+
}
|
|
5438
|
+
return true;
|
|
5439
|
+
case 7: return WS.has(b) && ++this.wsRun <= WS_CAP;
|
|
5332
5440
|
}
|
|
5333
5441
|
}
|
|
5334
5442
|
};
|
|
@@ -5343,9 +5451,11 @@ function makeToolFilter(table, prep, startInThink = false) {
|
|
|
5343
5451
|
const schemas = new Map(prep.tools.map((t) => [ToolBodyMachine.bytesOf(t.function.name), argsSchemaOf(t)]));
|
|
5344
5452
|
const props = new Map(prep.tools.map((t) => {
|
|
5345
5453
|
const p = t.function.parameters;
|
|
5454
|
+
const schemas = new Map(Object.entries(p?.properties ?? {}).map(([k, v]) => [ToolBodyMachine.bytesOf(k), v]));
|
|
5346
5455
|
return [ToolBodyMachine.bytesOf(t.function.name), {
|
|
5347
|
-
keys:
|
|
5348
|
-
required: (p?.required ?? []).map(ToolBodyMachine.bytesOf)
|
|
5456
|
+
keys: [...schemas.keys()],
|
|
5457
|
+
required: (p?.required ?? []).map(ToolBodyMachine.bytesOf),
|
|
5458
|
+
schemas
|
|
5349
5459
|
}];
|
|
5350
5460
|
}));
|
|
5351
5461
|
const newBody = () => prep.format === "xml" ? new ToolBodyMachineXml(cands, props) : new ToolBodyMachine(cands, schemas);
|
|
@@ -5715,6 +5825,27 @@ async function createChat(engine, options) {
|
|
|
5715
5825
|
};
|
|
5716
5826
|
};
|
|
5717
5827
|
let byteTable = null;
|
|
5828
|
+
let dryBreakerIds = null;
|
|
5829
|
+
const defaultDryBreakers = () => {
|
|
5830
|
+
if (dryBreakerIds) return dryBreakerIds;
|
|
5831
|
+
const ids = /* @__PURE__ */ new Set();
|
|
5832
|
+
for (const t of [
|
|
5833
|
+
"\n",
|
|
5834
|
+
"\n\n",
|
|
5835
|
+
":",
|
|
5836
|
+
";",
|
|
5837
|
+
",",
|
|
5838
|
+
"\"",
|
|
5839
|
+
"'",
|
|
5840
|
+
"*",
|
|
5841
|
+
"-",
|
|
5842
|
+
"|",
|
|
5843
|
+
"#",
|
|
5844
|
+
".",
|
|
5845
|
+
".\n"
|
|
5846
|
+
]) for (const id of tk.encode(t)) ids.add(id);
|
|
5847
|
+
return dryBreakerIds = [...ids];
|
|
5848
|
+
};
|
|
5718
5849
|
async function sendImpl(messages, o = {}) {
|
|
5719
5850
|
if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
|
|
5720
5851
|
const json = o.format !== void 0;
|
|
@@ -5813,6 +5944,13 @@ async function createChat(engine, options) {
|
|
|
5813
5944
|
const epoch0 = resetEpoch;
|
|
5814
5945
|
const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
|
|
5815
5946
|
const tf = prep ? makeToolFilter(byteTable ??= new TokenByteTable(tk), prep, think && thinkPreopened) : null;
|
|
5947
|
+
const tes = o.thinkEarlyStop ? {
|
|
5948
|
+
gap: 6,
|
|
5949
|
+
window: 16,
|
|
5950
|
+
minTokens: 64,
|
|
5951
|
+
...o.thinkEarlyStop === true ? {} : o.thinkEarlyStop
|
|
5952
|
+
} : null;
|
|
5953
|
+
const tb = think && (o.thinkBudget != null || tes) && tk.tokenToId("</think>") != null ? new ThinkBudget(tk.tokenToId("<think>"), tk.tokenToId("</think>"), Math.max(0, o.thinkBudget ?? Infinity), thinkPreopened, tes) : null;
|
|
5816
5954
|
let result;
|
|
5817
5955
|
try {
|
|
5818
5956
|
result = await engine.generate(inputTokenIds, {
|
|
@@ -5823,6 +5961,12 @@ async function createChat(engine, options) {
|
|
|
5823
5961
|
minP: o.minP,
|
|
5824
5962
|
repetitionPenalty: o.repetitionPenalty,
|
|
5825
5963
|
presencePenalty: o.presencePenalty,
|
|
5964
|
+
dryMultiplier: o.dryMultiplier,
|
|
5965
|
+
dryBase: o.dryBase,
|
|
5966
|
+
dryAllowedLength: o.dryAllowedLength,
|
|
5967
|
+
dryRange: o.dryRange,
|
|
5968
|
+
dryBreakers: (o.dryMultiplier ?? 0) > 0 ? o.dryBreakers ?? defaultDryBreakers() : void 0,
|
|
5969
|
+
topNSigma: o.topNSigma,
|
|
5826
5970
|
noRepeatNgramSize: o.noRepeatNgramSize,
|
|
5827
5971
|
seed: o.seed,
|
|
5828
5972
|
logprobs: o.logprobs,
|
|
@@ -5830,8 +5974,14 @@ async function createChat(engine, options) {
|
|
|
5830
5974
|
stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
|
|
5831
5975
|
reuseCache: canReuse,
|
|
5832
5976
|
signal,
|
|
5833
|
-
candidateFilter: jf
|
|
5977
|
+
candidateFilter: jf || tf || tb ? (ids, vals) => {
|
|
5978
|
+
tb?.observe(vals);
|
|
5979
|
+
const forced = tb?.force();
|
|
5980
|
+
if (forced != null) return [forced];
|
|
5981
|
+
return jf ? jf.filter(ids) : tf ? tf.filter(ids) : Array.from(ids);
|
|
5982
|
+
} : void 0,
|
|
5834
5983
|
onToken: (id) => {
|
|
5984
|
+
tb?.advance(id);
|
|
5835
5985
|
jf?.advance(id);
|
|
5836
5986
|
tf?.advance(id);
|
|
5837
5987
|
emit(splitter.push(decoder.push(id)));
|
|
@@ -5993,6 +6143,6 @@ async function createChat(engine, options) {
|
|
|
5993
6143
|
};
|
|
5994
6144
|
}
|
|
5995
6145
|
//#endregion
|
|
5996
|
-
export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
|
|
6146
|
+
export { ChatTokenizer, JsonMachine, StopScanner, ThinkBudget, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
|
|
5997
6147
|
|
|
5998
6148
|
//# sourceMappingURL=chat.js.map
|