bitgpu 0.18.0 → 0.19.1

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.18.0/models/bonsai-1.7b-gguf'
56
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.19.1/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`,
@@ -111,6 +111,12 @@ await engine.generate(promptTokenIds, { temperature: 0.5, topP: 0.85, topK: 20,
111
111
  // fills them from the tokenizer automatically). Not combinable with promptLookup.
112
112
  await engine.generate(promptTokenIds, { temperature: 0.5, dryMultiplier: 0.8, dryAllowedLength: 2 })
113
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
+
114
120
  // Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
115
121
  // exactly like transformers.js greedy search:
116
122
  await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
@@ -238,7 +244,15 @@ conversation.
238
244
  `thinkBudget: N` caps the reasoning phase: after N generated think tokens only `</think>` may be
239
245
  emitted, so the model wraps up and answers - "budget forcing", the practical way to run thinking
240
246
  mode on-device where every token is slow. `thinkBudget: 0` keeps the thinking template but
241
- suppresses reasoning entirely.
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.
242
256
 
243
257
  ### Guaranteed-valid JSON (`format: 'json'`)
244
258
 
@@ -536,6 +550,10 @@ ln -s /path/to/bonsai-model examples/model-1.7b # or copy the files in
536
550
  npm run build
537
551
  npm run verify:headless # serves the repo itself + drives system Chrome headlessly
538
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.
539
557
  ```
540
558
 
541
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-CSpyQjyc.js";
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 {
@@ -246,6 +246,8 @@ declare class ToolBodyMachineXml implements ToolBody {
246
246
  private elem;
247
247
  private keyBuf;
248
248
  private keyCands;
249
+ private declared;
250
+ private valWs;
249
251
  private reqLeft;
250
252
  private valTail;
251
253
  private valStarted;
@@ -351,22 +353,45 @@ declare class StopScanner {
351
353
  push(text: string): string;
352
354
  flush(): string;
353
355
  }
356
+ /** Confidence-based early stop for the think channel (training-free, DART-lineage heuristic). */
357
+ interface ThinkEarlyStop {
358
+ /** Logit gap (top1 - top2) that counts as a "confident" step. */
359
+ gap: number;
360
+ /** Consecutive confident steps required before firing. */
361
+ window: number;
362
+ /** Reasoning tokens that must be spent before early stop may fire (don't cut the model off
363
+ * before it has actually reasoned). */
364
+ minTokens: number;
365
+ }
354
366
  /** 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. */
367
+ * tokens generated inside a <think> block; once `budget` is spent - or the EARLY-STOP heuristic
368
+ * fires (the model has been decisively confident for `window` consecutive steps after
369
+ * `minTokens`, a signature of rote continuation rather than active reasoning) - `force()` names
370
+ * `</think>` as the only permitted candidate (the engine's constrained pick guarantees it is
371
+ * reachable even when outside the top-K), so the model closes its reasoning and continues
372
+ * straight into the visible answer. `budget: 0` suppresses reasoning entirely while keeping the
373
+ * thinking-mode template. advance() must see every emitted token; observe() should see each
374
+ * step's candidate logits (descending) BEFORE the pick - the filter callback receives exactly
375
+ * that. */
360
376
  declare class ThinkBudget {
361
377
  private readonly openId;
362
378
  private readonly closeId;
363
379
  private readonly budget;
380
+ private readonly early;
364
381
  private inThink;
365
382
  private spent;
366
383
  private closed;
367
- constructor(openId: number | undefined, closeId: number | undefined, budget: number, startInside: boolean);
384
+ private run;
385
+ private earlyFired;
386
+ private seen;
387
+ constructor(openId: number | undefined, closeId: number | undefined, budget: number, startInside: boolean, early?: ThinkEarlyStop | null);
368
388
  advance(id: number): void;
369
- /** The forced token id once the budget is exhausted (only `</think>` may be emitted), else null. */
389
+ /** Feed one step's candidate logits (descending). Only meaningful inside think. Counted at most
390
+ * once per emitted step: the engine re-invokes the candidate filter (and thus observe) once per
391
+ * 512-token batch when it has to walk the full vocabulary for a forced token, and those
392
+ * batch-local gaps must not eat the early-stop window. */
393
+ observe(vals: ArrayLike<number>): void;
394
+ /** The forced token id once the budget is exhausted or early stop fired, else null. */
370
395
  force(): number | null;
371
396
  }
372
397
  //#endregion
@@ -407,6 +432,7 @@ interface ChatSendOptions {
407
432
  dryAllowedLength?: number;
408
433
  dryRange?: number;
409
434
  dryBreakers?: number[];
435
+ topNSigma?: number;
410
436
  noRepeatNgramSize?: number;
411
437
  seed?: number;
412
438
  promptLookup?: GenerateOptions['promptLookup'];
@@ -439,6 +465,17 @@ interface ChatSendOptions {
439
465
  * slow on-device decode. `0` suppresses reasoning entirely (thinking template, no think
440
466
  * tokens). Unset = unlimited. Ignored when `think` is off. */
441
467
  thinkBudget?: number;
468
+ /** ADAPTIVE early stop for the reasoning phase (thinking mode only; composes with
469
+ * `thinkBudget`, which stays the hard cap): when the model has been decisively confident -
470
+ * top-1 vs top-2 logit gap >= `gap` - for `window` consecutive think tokens after at least
471
+ * `minTokens` of reasoning, `</think>` is forced and the answer begins. Sustained certainty
472
+ * inside a think block is the signature of rote continuation, not active reasoning; cutting
473
+ * there buys latency at little answer-quality cost. Pass `true` for the calibrated defaults. */
474
+ thinkEarlyStop?: boolean | {
475
+ gap?: number;
476
+ window?: number;
477
+ minTokens?: number;
478
+ };
442
479
  /** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
443
480
  onText?: (delta: string) => void;
444
481
  /** Streamed think content (only meaningful with `think: true`). */
package/dist/chat.js CHANGED
@@ -4400,22 +4400,31 @@ var StopScanner = class {
4400
4400
  }
4401
4401
  };
4402
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. */
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. */
4408
4412
  var ThinkBudget = class {
4409
4413
  openId;
4410
4414
  closeId;
4411
4415
  budget;
4416
+ early;
4412
4417
  inThink;
4413
4418
  spent = 0;
4414
4419
  closed = false;
4415
- constructor(openId, closeId, budget, startInside) {
4420
+ run = 0;
4421
+ earlyFired = false;
4422
+ seen = false;
4423
+ constructor(openId, closeId, budget, startInside, early = null) {
4416
4424
  this.openId = openId;
4417
4425
  this.closeId = closeId;
4418
4426
  this.budget = budget;
4427
+ this.early = early;
4419
4428
  this.inThink = startInside;
4420
4429
  }
4421
4430
  advance(id) {
@@ -4430,10 +4439,23 @@ var ThinkBudget = class {
4430
4439
  return;
4431
4440
  }
4432
4441
  this.spent++;
4433
- }
4434
- /** The forced token id once the budget is exhausted (only `</think>` may be emitted), else null. */
4442
+ this.seen = false;
4443
+ }
4444
+ /** Feed one step's candidate logits (descending). Only meaningful inside think. Counted at most
4445
+ * once per emitted step: the engine re-invokes the candidate filter (and thus observe) once per
4446
+ * 512-token batch when it has to walk the full vocabulary for a forced token, and those
4447
+ * batch-local gaps must not eat the early-stop window. */
4448
+ observe(vals) {
4449
+ if (!this.early || !this.inThink || this.closed || this.earlyFired || this.seen || vals.length < 2) return;
4450
+ this.seen = true;
4451
+ const confident = vals[0] - vals[1] >= this.early.gap;
4452
+ this.run = confident ? this.run + 1 : 0;
4453
+ if (this.spent >= this.early.minTokens && this.run >= this.early.window) this.earlyFired = true;
4454
+ }
4455
+ /** The forced token id once the budget is exhausted or early stop fired, else null. */
4435
4456
  force() {
4436
- return this.inThink && !this.closed && this.spent >= this.budget && this.closeId != null ? this.closeId : null;
4457
+ if (!this.inThink || this.closed || this.closeId == null) return null;
4458
+ return this.spent >= this.budget || this.earlyFired ? this.closeId : null;
4437
4459
  }
4438
4460
  };
4439
4461
  //#endregion
@@ -5242,6 +5264,8 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5242
5264
  elem = [];
5243
5265
  keyBuf = "";
5244
5266
  keyCands = [];
5267
+ declared = false;
5268
+ valWs = 0;
5245
5269
  reqLeft = [];
5246
5270
  valTail = [];
5247
5271
  valStarted = false;
@@ -5268,6 +5292,8 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5268
5292
  m.keyCands = [...this.keyCands];
5269
5293
  m.reqLeft = [...this.reqLeft];
5270
5294
  m.valTail = [...this.valTail];
5295
+ m.declared = this.declared;
5296
+ m.valWs = this.valWs;
5271
5297
  m.valStarted = this.valStarted;
5272
5298
  m.complete = this.complete;
5273
5299
  m.name = this.name;
@@ -5315,6 +5341,7 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5315
5341
  this.name = this.nameBuf;
5316
5342
  const spec = this.props.get(this.nameBuf);
5317
5343
  this.keyCands = [...spec?.keys ?? []];
5344
+ this.declared = this.keyCands.length > 0;
5318
5345
  this.reqLeft = [...spec?.required ?? []];
5319
5346
  this.phase = 3;
5320
5347
  this.elem = [];
@@ -5331,7 +5358,9 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5331
5358
  return true;
5332
5359
  }
5333
5360
  this.elem.push(b);
5361
+ const canParam = this.keyCands.length > 0 || !this.declared;
5334
5362
  if (litEq(this.elem, X_PARAM)) {
5363
+ if (!canParam) return false;
5335
5364
  this.phase = 4;
5336
5365
  this.keyBuf = "";
5337
5366
  return true;
@@ -5343,7 +5372,7 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5343
5372
  this.wsRun = 0;
5344
5373
  return true;
5345
5374
  }
5346
- const pP = litPrefix(this.elem, X_PARAM);
5375
+ const pP = litPrefix(this.elem, X_PARAM) && canParam;
5347
5376
  const pF = litPrefix(this.elem, X_FCLOSE);
5348
5377
  if (pF && !pP && this.reqLeft.length) return false;
5349
5378
  return pP || pF;
@@ -5359,7 +5388,7 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5359
5388
  this.valStarted = false;
5360
5389
  const sch = this.props.get(this.name)?.schemas?.get(this.keyBuf);
5361
5390
  const t = sch?.type;
5362
- if (sch && t !== void 0 && t !== "string") {
5391
+ if (sch && (sch.oneOf !== void 0 || t !== void 0 && t !== "string")) {
5363
5392
  this.valMode = "json";
5364
5393
  this.valJson = new JsonMachine(sch);
5365
5394
  } else if (sch?.enum?.length) {
@@ -5385,7 +5414,12 @@ var ToolBodyMachineXml = class ToolBodyMachineXml {
5385
5414
  }
5386
5415
  if (this.valMode === "json") {
5387
5416
  const j = this.valJson;
5388
- if (j.feed(Uint8Array.of(b))) return true;
5417
+ if (j.feed(Uint8Array.of(b))) {
5418
+ if (j.complete && (b === 10 || b === 32 || b === 9 || b === 13)) {
5419
+ if (++this.valWs > 1) return false;
5420
+ } else this.valWs = 0;
5421
+ return true;
5422
+ }
5389
5423
  if (!j.complete || b !== X_PCLOSE[0]) return false;
5390
5424
  this.phase = 6;
5391
5425
  this.closeLit = 1;
@@ -5442,7 +5476,14 @@ function makeToolFilter(table, prep, startInThink = false) {
5442
5476
  schemas
5443
5477
  }];
5444
5478
  }));
5479
+ if (prep.format === "xml") for (const t of prep.tools) for (const [k, s] of Object.entries(t.function.parameters?.properties ?? {})) {
5480
+ const sch = s;
5481
+ if (sch.oneOf === void 0 && (sch.type === void 0 || sch.type === "string") && !sch.enum?.length && (sch.minLength !== void 0 || sch.maxLength !== void 0)) throw new Error(`bitgpu/chat: minLength/maxLength on string parameter '${t.function.name}.${k}' cannot be enforced with the XML tool protocol (values are raw text); use an enum or drop the constraint`);
5482
+ if (sch.enum?.some((v) => v === "")) throw new Error(`bitgpu/chat: enum on parameter '${t.function.name}.${k}' contains an empty string, which the XML tool protocol cannot represent (the value scaffold newline would be ambiguous)`);
5483
+ }
5445
5484
  const newBody = () => prep.format === "xml" ? new ToolBodyMachineXml(cands, props) : new ToolBodyMachine(cands, schemas);
5485
+ const CLOSE_TEXT = ToolBodyMachine.bytesOf("</tool_call>");
5486
+ let bodyTail = "";
5446
5487
  let state = forced ? 1 : 0;
5447
5488
  let body = null;
5448
5489
  let inThink = startInThink;
@@ -5467,6 +5508,7 @@ function makeToolFilter(table, prep, startInThink = false) {
5467
5508
  }
5468
5509
  const bytes = table.bytes(n);
5469
5510
  if (!bytes || bytes.length === 0) continue;
5511
+ if ((bodyTail + String.fromCharCode(...bytes)).includes(CLOSE_TEXT)) continue;
5470
5512
  const fb = m.forcedNext?.() ?? -1;
5471
5513
  if (fb >= 0) {
5472
5514
  if (bytes.length === 1 && bytes[0] === fb) out.push(n);
@@ -5492,6 +5534,7 @@ function makeToolFilter(table, prep, startInThink = false) {
5492
5534
  if (id === ids.open) {
5493
5535
  state = 2;
5494
5536
  body = newBody();
5537
+ bodyTail = "";
5495
5538
  }
5496
5539
  return;
5497
5540
  case 2:
@@ -5502,7 +5545,10 @@ function makeToolFilter(table, prep, startInThink = false) {
5502
5545
  }
5503
5546
  {
5504
5547
  const bytes = table.bytes(id);
5505
- if (bytes) body.feed(bytes);
5548
+ if (bytes) {
5549
+ body.feed(bytes);
5550
+ bodyTail = (bodyTail + String.fromCharCode(...bytes)).slice(1 - CLOSE_TEXT.length);
5551
+ }
5506
5552
  }
5507
5553
  return;
5508
5554
  case 3: return;
@@ -5630,7 +5676,7 @@ function parseToolCallXml(raw, tools) {
5630
5676
  const key = m[1];
5631
5677
  const valText = m[2].replace(/^\n/, "").replace(/\n$/, "");
5632
5678
  const pschema = props[key];
5633
- if (pschema?.type !== void 0 && pschema.type !== "string") try {
5679
+ if (pschema?.oneOf !== void 0 || pschema?.type !== void 0 && pschema.type !== "string") try {
5634
5680
  args[key] = JSON.parse(valText);
5635
5681
  } catch {
5636
5682
  return {
@@ -5928,7 +5974,13 @@ async function createChat(engine, options) {
5928
5974
  const epoch0 = resetEpoch;
5929
5975
  const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
5930
5976
  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;
5977
+ const tes = o.thinkEarlyStop ? {
5978
+ gap: 6,
5979
+ window: 16,
5980
+ minTokens: 64,
5981
+ ...o.thinkEarlyStop === true ? {} : o.thinkEarlyStop
5982
+ } : null;
5983
+ 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;
5932
5984
  let result;
5933
5985
  try {
5934
5986
  result = await engine.generate(inputTokenIds, {
@@ -5944,6 +5996,7 @@ async function createChat(engine, options) {
5944
5996
  dryAllowedLength: o.dryAllowedLength,
5945
5997
  dryRange: o.dryRange,
5946
5998
  dryBreakers: (o.dryMultiplier ?? 0) > 0 ? o.dryBreakers ?? defaultDryBreakers() : void 0,
5999
+ topNSigma: o.topNSigma,
5947
6000
  noRepeatNgramSize: o.noRepeatNgramSize,
5948
6001
  seed: o.seed,
5949
6002
  logprobs: o.logprobs,
@@ -5951,7 +6004,8 @@ async function createChat(engine, options) {
5951
6004
  stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
5952
6005
  reuseCache: canReuse,
5953
6006
  signal,
5954
- candidateFilter: jf || tf || tb ? (ids) => {
6007
+ candidateFilter: jf || tf || tb ? (ids, vals) => {
6008
+ tb?.observe(vals);
5955
6009
  const forced = tb?.force();
5956
6010
  if (forced != null) return [forced];
5957
6011
  return jf ? jf.filter(ids) : tf ? tf.filter(ids) : Array.from(ids);