bitgpu 0.17.0 → 0.18.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
@@ -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.17.0/models/bonsai-1.7b-gguf'
56
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.18.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,12 @@ 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
+
108
114
  // Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
109
115
  // exactly like transformers.js greedy search:
110
116
  await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
@@ -229,6 +235,11 @@ reuse with exact token bookkeeping (a clean follow-up turn prefills only the del
229
235
  `chat.prewarm(messages)` warms a static system prompt at load). `chat.reset()` forgets the
230
236
  conversation.
231
237
 
238
+ `thinkBudget: N` caps the reasoning phase: after N generated think tokens only `</think>` may be
239
+ emitted, so the model wraps up and answers - "budget forcing", the practical way to run thinking
240
+ mode on-device where every token is slow. `thinkBudget: 0` keeps the thinking template but
241
+ suppresses reasoning entirely.
242
+
232
243
  ### Guaranteed-valid JSON (`format: 'json'`)
233
244
 
234
245
  ```ts
@@ -298,7 +309,11 @@ declared tools and the arguments are forced through that tool's `parameters` sch
298
309
  token-by-token. Both Qwen wire formats are supported and auto-detected from the chat template:
299
310
  the Qwen3 JSON shape (`<tool_call>{"name": …, "arguments": …}</tool_call>` - the dense Bonsai
300
311
  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.
312
+ Bonsai-27B), so the same `tools` array works across all of them. In the XML format each
313
+ parameter's VALUE is constrained by its own schema: a `number`/`integer`/`boolean`/`array`/
314
+ `object` parameter is forced to be exactly that (JSON grammar, including integer bounds and
315
+ array item schemas), a string `enum` is forced onto one of its literals, and plain strings stay
316
+ free text - the model cannot hand your tool `abc` where a number belongs.
302
317
 
303
318
  ```ts
304
319
  const tools = [{
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-BkfIJ42d.js";
1
+ import { c as KvSnapshot, m as TokenLogprobs, n as Engine, o as GenerateOptions } from "./types-CSpyQjyc.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 byte-space property keys + required subset */
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,24 @@ declare class StopScanner {
342
351
  push(text: string): string;
343
352
  flush(): string;
344
353
  }
354
+ /** Budget-forcing for the think channel (s1-style "budget forcing", training-free): counts the
355
+ * tokens generated inside a <think> block; once `budget` is spent, `force()` names `</think>` as
356
+ * the only permitted candidate (the engine's constrained pick guarantees it is reachable even
357
+ * when outside the top-K), so the model closes its reasoning and continues straight into the
358
+ * visible answer. `budget: 0` suppresses reasoning entirely while keeping the thinking-mode
359
+ * template. advance() must see every emitted token. */
360
+ declare class ThinkBudget {
361
+ private readonly openId;
362
+ private readonly closeId;
363
+ private readonly budget;
364
+ private inThink;
365
+ private spent;
366
+ private closed;
367
+ constructor(openId: number | undefined, closeId: number | undefined, budget: number, startInside: boolean);
368
+ advance(id: number): void;
369
+ /** The forced token id once the budget is exhausted (only `</think>` may be emitted), else null. */
370
+ force(): number | null;
371
+ }
345
372
  //#endregion
346
373
  //#region src/chat/index.d.ts
347
374
  /** Options for {@link createChat}. Point it at the model directory (which already hosts
@@ -372,6 +399,14 @@ interface ChatSendOptions {
372
399
  minP?: number;
373
400
  repetitionPenalty?: number;
374
401
  presencePenalty?: number;
402
+ /** DRY anti-loop penalty strength (see GenerateOptions.dryMultiplier). When set, the chat layer
403
+ * supplies sequence-breaker token ids from the tokenizer (newline/punctuation/list markers) so
404
+ * structural repetition is never penalized; pass `dryBreakers` to override. */
405
+ dryMultiplier?: number;
406
+ dryBase?: number;
407
+ dryAllowedLength?: number;
408
+ dryRange?: number;
409
+ dryBreakers?: number[];
375
410
  noRepeatNgramSize?: number;
376
411
  seed?: number;
377
412
  promptLookup?: GenerateOptions['promptLookup'];
@@ -399,6 +434,11 @@ interface ChatSendOptions {
399
434
  * turn drops the KV cache afterwards (the stripped reply cannot reproduce the cached tokens).
400
435
  * Default false. */
401
436
  think?: boolean;
437
+ /** Cap on reasoning length (thinking mode only): after this many generated think tokens the
438
+ * engine may only emit `</think>`, so the model wraps up and answers - "budget forcing" for
439
+ * slow on-device decode. `0` suppresses reasoning entirely (thinking template, no think
440
+ * tokens). Unset = unlimited. Ignored when `think` is off. */
441
+ thinkBudget?: number;
402
442
  /** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
403
443
  onText?: (delta: string) => void;
404
444
  /** Streamed think content (only meaningful with `think: true`). */
@@ -526,5 +566,5 @@ interface Chat {
526
566
  /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
527
567
  declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
528
568
  //#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 };
569
+ 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
570
  //# sourceMappingURL=chat.d.ts.map
package/dist/chat.js CHANGED
@@ -4399,6 +4399,43 @@ 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, `force()` names `</think>` as
4404
+ * the only permitted candidate (the engine's constrained pick guarantees it is reachable even
4405
+ * when outside the top-K), so the model closes its reasoning and continues straight into the
4406
+ * visible answer. `budget: 0` suppresses reasoning entirely while keeping the thinking-mode
4407
+ * template. advance() must see every emitted token. */
4408
+ var ThinkBudget = class {
4409
+ openId;
4410
+ closeId;
4411
+ budget;
4412
+ inThink;
4413
+ spent = 0;
4414
+ closed = false;
4415
+ constructor(openId, closeId, budget, startInside) {
4416
+ this.openId = openId;
4417
+ this.closeId = closeId;
4418
+ this.budget = budget;
4419
+ this.inThink = startInside;
4420
+ }
4421
+ advance(id) {
4422
+ if (this.closed) return;
4423
+ if (!this.inThink) {
4424
+ if (this.openId != null && id === this.openId) this.inThink = true;
4425
+ return;
4426
+ }
4427
+ if (this.closeId != null && id === this.closeId) {
4428
+ this.inThink = false;
4429
+ this.closed = true;
4430
+ return;
4431
+ }
4432
+ this.spent++;
4433
+ }
4434
+ /** The forced token id once the budget is exhausted (only `</think>` may be emitted), else null. */
4435
+ force() {
4436
+ return this.inThink && !this.closed && this.spent >= this.budget && this.closeId != null ? this.closeId : null;
4437
+ }
4438
+ };
4402
4439
  //#endregion
4403
4440
  //#region src/chat/json.ts
4404
4441
  const SUPPORTED = /* @__PURE__ */ new Set([
@@ -4758,10 +4795,13 @@ var JsonMachine = class JsonMachine {
4758
4795
  byte(b) {
4759
4796
  if (!WS$1.has(b)) this.wsRun = 0;
4760
4797
  switch (this.phase) {
4761
- case 0:
4798
+ case 0: {
4762
4799
  if (WS$1.has(b)) return this.ws();
4763
4800
  if (b === 123 || b === 91) return this.openValue(b);
4801
+ const rt = this.root?.type;
4802
+ if (rt !== void 0 && rt !== "object" && rt !== "array") return this.openValue(b);
4764
4803
  return false;
4804
+ }
4765
4805
  case 1:
4766
4806
  if (WS$1.has(b)) return this.ws();
4767
4807
  return this.openValue(b);
@@ -5205,9 +5245,14 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5205
5245
  reqLeft = [];
5206
5246
  valTail = [];
5207
5247
  valStarted = false;
5248
+ valMode = "raw";
5249
+ valBuf = "";
5250
+ valEnum = [];
5251
+ valJson = null;
5252
+ closeLit = 0;
5208
5253
  complete = false;
5209
5254
  name = "";
5210
- /** byte-space tool names, and per name its byte-space property keys + required subset */
5255
+ /** byte-space tool names, and per name its property keys / required subset / param schemas */
5211
5256
  constructor(cands, props) {
5212
5257
  this.cands = cands;
5213
5258
  this.props = props;
@@ -5226,6 +5271,11 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5226
5271
  m.valStarted = this.valStarted;
5227
5272
  m.complete = this.complete;
5228
5273
  m.name = this.name;
5274
+ m.valMode = this.valMode;
5275
+ m.valBuf = this.valBuf;
5276
+ m.valEnum = [...this.valEnum];
5277
+ m.valJson = this.valJson ? this.valJson.clone() : null;
5278
+ m.closeLit = this.closeLit;
5229
5279
  return m;
5230
5280
  }
5231
5281
  feed(bytes) {
@@ -5237,7 +5287,10 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5237
5287
  case 2: return this.cands.includes(this.nameBuf) && !this.cands.some((c) => c !== this.nameBuf && c.startsWith(this.nameBuf)) ? 62 : -1;
5238
5288
  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
5289
  case 3: return this.elem.length === 0 && this.wsRun === 0 ? 10 : -1;
5240
- case 5: return this.wsRun === 0 ? 10 : -1;
5290
+ case 5:
5291
+ if (this.wsRun === 0) return 10;
5292
+ if (this.valMode === "enum" && this.valEnum.includes(this.valBuf) && !this.valEnum.some((c) => c !== this.valBuf && c.startsWith(this.valBuf))) return 10;
5293
+ return -1;
5241
5294
  default: return -1;
5242
5295
  }
5243
5296
  }
@@ -5285,7 +5338,7 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5285
5338
  }
5286
5339
  if (litEq(this.elem, X_FCLOSE)) {
5287
5340
  if (this.reqLeft.length) return false;
5288
- this.phase = 6;
5341
+ this.phase = 7;
5289
5342
  this.complete = true;
5290
5343
  this.wsRun = 0;
5291
5344
  return true;
@@ -5304,6 +5357,16 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5304
5357
  this.valTail = [];
5305
5358
  this.wsRun = 0;
5306
5359
  this.valStarted = false;
5360
+ const sch = this.props.get(this.name)?.schemas?.get(this.keyBuf);
5361
+ const t = sch?.type;
5362
+ if (sch && t !== void 0 && t !== "string") {
5363
+ this.valMode = "json";
5364
+ this.valJson = new JsonMachine(sch);
5365
+ } else if (sch?.enum?.length) {
5366
+ this.valMode = "enum";
5367
+ this.valBuf = "";
5368
+ this.valEnum = sch.enum.map(ToolBodyMachine.bytesOf);
5369
+ } else this.valMode = "raw";
5307
5370
  return true;
5308
5371
  }
5309
5372
  this.keyBuf += String.fromCharCode(b);
@@ -5320,6 +5383,27 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5320
5383
  if (b === 10) return false;
5321
5384
  this.valStarted = true;
5322
5385
  }
5386
+ if (this.valMode === "json") {
5387
+ const j = this.valJson;
5388
+ if (j.feed(Uint8Array.of(b))) return true;
5389
+ if (!j.complete || b !== X_PCLOSE[0]) return false;
5390
+ this.phase = 6;
5391
+ this.closeLit = 1;
5392
+ return true;
5393
+ }
5394
+ if (this.valMode === "enum") {
5395
+ const next = this.valBuf + String.fromCharCode(b);
5396
+ if (this.valEnum.some((c) => c.startsWith(next))) {
5397
+ this.valBuf = next;
5398
+ return true;
5399
+ }
5400
+ if (b === 10 && this.valEnum.includes(this.valBuf)) {
5401
+ this.phase = 6;
5402
+ this.closeLit = 0;
5403
+ return true;
5404
+ }
5405
+ return false;
5406
+ }
5323
5407
  this.valTail.push(b);
5324
5408
  if (this.valTail.length > X_PCLOSE.length) this.valTail.shift();
5325
5409
  if (litEq(this.valTail, X_PCLOSE)) {
@@ -5328,7 +5412,15 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5328
5412
  this.wsRun = 0;
5329
5413
  }
5330
5414
  return true;
5331
- case 6: return WS.has(b) && ++this.wsRun <= WS_CAP;
5415
+ case 6:
5416
+ if (b !== X_PCLOSE[this.closeLit]) return false;
5417
+ if (++this.closeLit === X_PCLOSE.length) {
5418
+ this.phase = 3;
5419
+ this.elem = [];
5420
+ this.wsRun = 0;
5421
+ }
5422
+ return true;
5423
+ case 7: return WS.has(b) && ++this.wsRun <= WS_CAP;
5332
5424
  }
5333
5425
  }
5334
5426
  };
@@ -5343,9 +5435,11 @@ function makeToolFilter(table, prep, startInThink = false) {
5343
5435
  const schemas = new Map(prep.tools.map((t) => [ToolBodyMachine.bytesOf(t.function.name), argsSchemaOf(t)]));
5344
5436
  const props = new Map(prep.tools.map((t) => {
5345
5437
  const p = t.function.parameters;
5438
+ const schemas = new Map(Object.entries(p?.properties ?? {}).map(([k, v]) => [ToolBodyMachine.bytesOf(k), v]));
5346
5439
  return [ToolBodyMachine.bytesOf(t.function.name), {
5347
- keys: Object.keys(p?.properties ?? {}).map(ToolBodyMachine.bytesOf),
5348
- required: (p?.required ?? []).map(ToolBodyMachine.bytesOf)
5440
+ keys: [...schemas.keys()],
5441
+ required: (p?.required ?? []).map(ToolBodyMachine.bytesOf),
5442
+ schemas
5349
5443
  }];
5350
5444
  }));
5351
5445
  const newBody = () => prep.format === "xml" ? new ToolBodyMachineXml(cands, props) : new ToolBodyMachine(cands, schemas);
@@ -5715,6 +5809,27 @@ async function createChat(engine, options) {
5715
5809
  };
5716
5810
  };
5717
5811
  let byteTable = null;
5812
+ let dryBreakerIds = null;
5813
+ const defaultDryBreakers = () => {
5814
+ if (dryBreakerIds) return dryBreakerIds;
5815
+ const ids = /* @__PURE__ */ new Set();
5816
+ for (const t of [
5817
+ "\n",
5818
+ "\n\n",
5819
+ ":",
5820
+ ";",
5821
+ ",",
5822
+ "\"",
5823
+ "'",
5824
+ "*",
5825
+ "-",
5826
+ "|",
5827
+ "#",
5828
+ ".",
5829
+ ".\n"
5830
+ ]) for (const id of tk.encode(t)) ids.add(id);
5831
+ return dryBreakerIds = [...ids];
5832
+ };
5718
5833
  async function sendImpl(messages, o = {}) {
5719
5834
  if (messages.length === 0) throw new Error("bitgpu/chat: no messages");
5720
5835
  const json = o.format !== void 0;
@@ -5813,6 +5928,7 @@ async function createChat(engine, options) {
5813
5928
  const epoch0 = resetEpoch;
5814
5929
  const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
5815
5930
  const tf = prep ? makeToolFilter(byteTable ??= new TokenByteTable(tk), prep, think && thinkPreopened) : null;
5931
+ const tb = think && o.thinkBudget != null && tk.tokenToId("</think>") != null ? new ThinkBudget(tk.tokenToId("<think>"), tk.tokenToId("</think>"), Math.max(0, o.thinkBudget), thinkPreopened) : null;
5816
5932
  let result;
5817
5933
  try {
5818
5934
  result = await engine.generate(inputTokenIds, {
@@ -5823,6 +5939,11 @@ async function createChat(engine, options) {
5823
5939
  minP: o.minP,
5824
5940
  repetitionPenalty: o.repetitionPenalty,
5825
5941
  presencePenalty: o.presencePenalty,
5942
+ dryMultiplier: o.dryMultiplier,
5943
+ dryBase: o.dryBase,
5944
+ dryAllowedLength: o.dryAllowedLength,
5945
+ dryRange: o.dryRange,
5946
+ dryBreakers: (o.dryMultiplier ?? 0) > 0 ? o.dryBreakers ?? defaultDryBreakers() : void 0,
5826
5947
  noRepeatNgramSize: o.noRepeatNgramSize,
5827
5948
  seed: o.seed,
5828
5949
  logprobs: o.logprobs,
@@ -5830,8 +5951,13 @@ async function createChat(engine, options) {
5830
5951
  stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
5831
5952
  reuseCache: canReuse,
5832
5953
  signal,
5833
- candidateFilter: jf ? (ids) => jf.filter(ids) : tf ? (ids) => tf.filter(ids) : void 0,
5954
+ candidateFilter: jf || tf || tb ? (ids) => {
5955
+ const forced = tb?.force();
5956
+ if (forced != null) return [forced];
5957
+ return jf ? jf.filter(ids) : tf ? tf.filter(ids) : Array.from(ids);
5958
+ } : void 0,
5834
5959
  onToken: (id) => {
5960
+ tb?.advance(id);
5835
5961
  jf?.advance(id);
5836
5962
  tf?.advance(id);
5837
5963
  emit(splitter.push(decoder.push(id)));
@@ -5993,6 +6119,6 @@ async function createChat(engine, options) {
5993
6119
  };
5994
6120
  }
5995
6121
  //#endregion
5996
- export { ChatTokenizer, JsonMachine, StopScanner, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
6122
+ export { ChatTokenizer, JsonMachine, StopScanner, ThinkBudget, ThinkSplitter, ToolBodyMachine, ToolBodyMachineXml, ToolCallSplitter, createChat, makeToolFilter, parseToolCall, parseToolCallXml, validateJsonSchema, validateTools };
5997
6123
 
5998
6124
  //# sourceMappingURL=chat.js.map