bitgpu 0.18.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 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.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`,
@@ -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 {
@@ -351,22 +351,41 @@ declare class StopScanner {
351
351
  push(text: string): string;
352
352
  flush(): string;
353
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
+ }
354
364
  /** 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. */
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. */
360
374
  declare class ThinkBudget {
361
375
  private readonly openId;
362
376
  private readonly closeId;
363
377
  private readonly budget;
378
+ private readonly early;
364
379
  private inThink;
365
380
  private spent;
366
381
  private closed;
367
- constructor(openId: number | undefined, closeId: number | undefined, budget: number, startInside: boolean);
382
+ private run;
383
+ private earlyFired;
384
+ constructor(openId: number | undefined, closeId: number | undefined, budget: number, startInside: boolean, early?: ThinkEarlyStop | null);
368
385
  advance(id: number): void;
369
- /** The forced token id once the budget is exhausted (only `</think>` may be emitted), else null. */
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. */
370
389
  force(): number | null;
371
390
  }
372
391
  //#endregion
@@ -407,6 +426,7 @@ interface ChatSendOptions {
407
426
  dryAllowedLength?: number;
408
427
  dryRange?: number;
409
428
  dryBreakers?: number[];
429
+ topNSigma?: number;
410
430
  noRepeatNgramSize?: number;
411
431
  seed?: number;
412
432
  promptLookup?: GenerateOptions['promptLookup'];
@@ -439,6 +459,17 @@ interface ChatSendOptions {
439
459
  * slow on-device decode. `0` suppresses reasoning entirely (thinking template, no think
440
460
  * tokens). Unset = unlimited. Ignored when `think` is off. */
441
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
+ };
442
473
  /** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
443
474
  onText?: (delta: string) => void;
444
475
  /** Streamed think content (only meaningful with `think: true`). */
package/dist/chat.js CHANGED
@@ -4400,22 +4400,30 @@ 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
+ constructor(openId, closeId, budget, startInside, early = null) {
4416
4423
  this.openId = openId;
4417
4424
  this.closeId = closeId;
4418
4425
  this.budget = budget;
4426
+ this.early = early;
4419
4427
  this.inThink = startInside;
4420
4428
  }
4421
4429
  advance(id) {
@@ -4431,9 +4439,17 @@ var ThinkBudget = class {
4431
4439
  }
4432
4440
  this.spent++;
4433
4441
  }
4434
- /** The forced token id once the budget is exhausted (only `</think>` may be emitted), else null. */
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. */
4435
4450
  force() {
4436
- return this.inThink && !this.closed && this.spent >= this.budget && this.closeId != null ? this.closeId : null;
4451
+ if (!this.inThink || this.closed || this.closeId == null) return null;
4452
+ return this.spent >= this.budget || this.earlyFired ? this.closeId : null;
4437
4453
  }
4438
4454
  };
4439
4455
  //#endregion
@@ -5928,7 +5944,13 @@ async function createChat(engine, options) {
5928
5944
  const epoch0 = resetEpoch;
5929
5945
  const jf = json ? makeJsonFilter(byteTable ??= new TokenByteTable(tk), tk.eosTokenId, schema) : null;
5930
5946
  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;
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;
5932
5954
  let result;
5933
5955
  try {
5934
5956
  result = await engine.generate(inputTokenIds, {
@@ -5944,6 +5966,7 @@ async function createChat(engine, options) {
5944
5966
  dryAllowedLength: o.dryAllowedLength,
5945
5967
  dryRange: o.dryRange,
5946
5968
  dryBreakers: (o.dryMultiplier ?? 0) > 0 ? o.dryBreakers ?? defaultDryBreakers() : void 0,
5969
+ topNSigma: o.topNSigma,
5947
5970
  noRepeatNgramSize: o.noRepeatNgramSize,
5948
5971
  seed: o.seed,
5949
5972
  logprobs: o.logprobs,
@@ -5951,7 +5974,8 @@ async function createChat(engine, options) {
5951
5974
  stopTokens: [tk.eosTokenId, ...o.stopTokens ?? []],
5952
5975
  reuseCache: canReuse,
5953
5976
  signal,
5954
- candidateFilter: jf || tf || tb ? (ids) => {
5977
+ candidateFilter: jf || tf || tb ? (ids, vals) => {
5978
+ tb?.observe(vals);
5955
5979
  const forced = tb?.force();
5956
5980
  if (forced != null) return [forced];
5957
5981
  return jf ? jf.filter(ids) : tf ? tf.filter(ids) : Array.from(ids);