bitgpu 0.16.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.16.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`,
@@ -100,6 +100,17 @@ 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
+
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
+
103
114
  // Penalties apply under greedy decoding too (penalized argmax, deterministic, no RNG),
104
115
  // exactly like transformers.js greedy search:
105
116
  await engine.generate(promptTokenIds, { repetitionPenalty: 1.15, noRepeatNgramSize: 3 })
@@ -224,6 +235,11 @@ reuse with exact token bookkeeping (a clean follow-up turn prefills only the del
224
235
  `chat.prewarm(messages)` warms a static system prompt at load). `chat.reset()` forgets the
225
236
  conversation.
226
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
+
227
243
  ### Guaranteed-valid JSON (`format: 'json'`)
228
244
 
229
245
  ```ts
@@ -287,11 +303,17 @@ with or without it; `promptLookup` is disabled for the turn.
287
303
 
288
304
  ### Tool calling (`tools`)
289
305
 
290
- The model's own protocol (Qwen3-family templates render a `tools` list and emit
291
- `<tool_call>` blocks), with the same enforcement guarantee as schema mode: a bitgpu tool call
306
+ The model's own protocol, with the same enforcement guarantee as schema mode: a bitgpu tool call
292
307
  **cannot be malformed** - once the model opens a call, the name is forced to one of your
293
308
  declared tools and the arguments are forced through that tool's `parameters` schema,
294
- token-by-token.
309
+ token-by-token. Both Qwen wire formats are supported and auto-detected from the chat template:
310
+ the Qwen3 JSON shape (`<tool_call>{"name": …, "arguments": …}</tool_call>` - the dense Bonsai
311
+ models) and the Qwen3.5 XML shape (`<tool_call><function=…><parameter=…>` - the hybrid
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.
295
317
 
296
318
  ```ts
297
319
  const tools = [{
@@ -373,14 +395,16 @@ const engine = await createEngine({
373
395
  })
374
396
  ```
375
397
 
376
- The Qwen3.5 hybrid **Bonsai-27B** loads exactly the same way - `fromGguf` is its only path (there is
377
- no offline converter for the hybrid yet), so point at
398
+ The Qwen3.5 hybrid **Bonsai-27B** loads exactly the same way - `fromGguf` on
378
399
  `prism-ml/Bonsai-27B-gguf/resolve/main/Bonsai-27B-Q1_0.gguf` with `kvCache: 'q8'` and, say,
379
- `maxSeqLen: 4096`. bitgpu runs its **text trunk** (the model is multimodal; the vision path is out of
380
- scope). Text chat works through `bitgpu/chat` unchanged - its Jinja template and tool-call rendering
381
- go through the same path as the dense models (verified end-to-end) - but the GGUF repo ships no
382
- tokenizer, so point `createChat` at [prism-ml/Bonsai-27B-unpacked](https://huggingface.co/prism-ml/Bonsai-27B-unpacked)
383
- for `tokenizer.json` + `tokenizer_config.json`. It is a ~3.8 GB download and comfortably wants a 16 GB
400
+ `maxSeqLen: 4096` - or via its [committed manifest](models/) like the dense models. bitgpu runs its
401
+ **text trunk** (the model is multimodal; the vision path is out of scope). Text chat AND tool calling
402
+ work through `bitgpu/chat` unchanged - the Qwen3.5 template's XML tool protocol is auto-detected and
403
+ enforced like the dense models' JSON protocol (verified end-to-end on the real 27B) - but the GGUF
404
+ repo ships no tokenizer, so point `createChat` at
405
+ [prism-ml/Bonsai-27B-unpacked](https://huggingface.co/prism-ml/Bonsai-27B-unpacked)
406
+ for `tokenizer.json` + `tokenizer_config.json`. Recommended sampling (per the model card):
407
+ `temperature: 0.5, topP: 0.85, topK: 20`. It is a ~3.8 GB download and comfortably wants a 16 GB
384
408
  (or larger) GPU budget - on an 8 GB laptop it runs but the weights spill to swap, so decode is slow.
385
409
  A hybrid upside: its 48 gated-DeltaNet layers cost O(1) per token, so decode throughput stays nearly
386
410
  flat as context grows (only the 16 full-attention layers scale with length) - a long-context
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-Wg8VrdrL.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 {
@@ -216,6 +216,53 @@ 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
+ /** 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
+ }
239
+ declare class ToolBodyMachineXml implements ToolBody {
240
+ private readonly cands;
241
+ private readonly props;
242
+ private phase;
243
+ private lit;
244
+ private nameBuf;
245
+ private wsRun;
246
+ private elem;
247
+ private keyBuf;
248
+ private keyCands;
249
+ private reqLeft;
250
+ private valTail;
251
+ private valStarted;
252
+ private valMode;
253
+ private valBuf;
254
+ private valEnum;
255
+ private valJson;
256
+ private closeLit;
257
+ complete: boolean;
258
+ name: string;
259
+ /** byte-space tool names, and per name its property keys / required subset / param schemas */
260
+ constructor(cands: readonly string[], props: ReadonlyMap<string, XmlToolProps>);
261
+ clone(): ToolBodyMachineXml;
262
+ feed(bytes: Uint8Array): boolean;
263
+ forcedNext(): number;
264
+ private byte;
265
+ }
219
266
  interface ToolMarkerIds {
220
267
  open: number;
221
268
  close: number;
@@ -228,13 +275,15 @@ interface PreparedTools {
228
275
  ids: ToolMarkerIds;
229
276
  /** null = 'auto'; a name = forced single call */
230
277
  forced: string | null;
278
+ /** the tool-call wire format the model's template uses: 'json' (Qwen3) or 'xml' (Qwen3.5) */
279
+ format: 'json' | 'xml';
231
280
  }
232
281
  /** Per-step candidate filter for tool turns. Auto mode: free text (everything permitted) until
233
282
  * the model opens <tool_call>, then the body grammar takes over until </tool_call>, then free
234
283
  * text again (another call, prose, or eos). Forced mode: the FIRST token must be <tool_call>,
235
284
  * the body is constrained to the named tool, and after </tool_call> only eos is permitted.
236
285
  * Call advance() with each emitted token to move the real machine. */
237
- declare function makeToolFilter(table: TokenByteTable, prep: PreparedTools): {
286
+ declare function makeToolFilter(table: TokenByteTable, prep: PreparedTools, startInThink?: boolean): {
238
287
  filter: (ids: Uint32Array | number[]) => number[];
239
288
  advance: (id: number) => void;
240
289
  };
@@ -263,6 +312,11 @@ declare class ToolCallSplitter {
263
312
  /** Parse one block's content into a ToolCall. With enforcement on this cannot fail for a
264
313
  * completed block; a failure (unenforced or truncated content) yields name '' and the raw text. */
265
314
  declare function parseToolCall(raw: string): ToolCall;
315
+ /** Parse one XML block's content into a ToolCall (the Qwen3.5 `<function=…><parameter=…>` protocol).
316
+ * Values are coerced by the tool's schema - string params keep their raw text, everything else is
317
+ * JSON.parse'd. Returns name '' if the block names an unknown tool/property, a required property is
318
+ * missing, or a non-string value is not valid JSON (so a surfaced call always conforms). */
319
+ declare function parseToolCallXml(raw: string, tools: readonly ChatTool[]): ToolCall;
266
320
  //#endregion
267
321
  //#region src/chat/think.d.ts
268
322
  interface SplitChunk {
@@ -276,7 +330,11 @@ declare class ThinkSplitter {
276
330
  private readonly close;
277
331
  private inside;
278
332
  private hold;
279
- constructor(open?: string, close?: string);
333
+ constructor(open?: string, close?: string,
334
+ /** Start already inside a think block - for templates whose generation prompt PRE-OPENS `<think>`
335
+ * (e.g. Qwen3.5 thinking mode), so the opening tag is in the prompt, not the generated stream. */
336
+
337
+ startInside?: boolean);
280
338
  push(chunk: string): SplitChunk;
281
339
  /** Emit whatever is held back. An unterminated think block (generation hit maxTokens inside it)
282
340
  * flushes to the think channel, never to the visible reply. */
@@ -293,6 +351,24 @@ declare class StopScanner {
293
351
  push(text: string): string;
294
352
  flush(): string;
295
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
+ }
296
372
  //#endregion
297
373
  //#region src/chat/index.d.ts
298
374
  /** Options for {@link createChat}. Point it at the model directory (which already hosts
@@ -320,7 +396,17 @@ interface ChatSendOptions {
320
396
  temperature?: number;
321
397
  topK?: number;
322
398
  topP?: number;
399
+ minP?: number;
323
400
  repetitionPenalty?: number;
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[];
324
410
  noRepeatNgramSize?: number;
325
411
  seed?: number;
326
412
  promptLookup?: GenerateOptions['promptLookup'];
@@ -348,6 +434,11 @@ interface ChatSendOptions {
348
434
  * turn drops the KV cache afterwards (the stripped reply cannot reproduce the cached tokens).
349
435
  * Default false. */
350
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;
351
442
  /** Streamed visible reply text (clean deltas: UTF-8-safe, think blocks removed). */
352
443
  onText?: (delta: string) => void;
353
444
  /** Streamed think content (only meaningful with `think: true`). */
@@ -475,5 +566,5 @@ interface Chat {
475
566
  /** Load the tokenizer files and return a {@link Chat} bound to the engine. */
476
567
  declare function createChat(engine: Engine, options: ChatOptions): Promise<Chat>;
477
568
  //#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 };
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 };
479
570
  //# sourceMappingURL=chat.d.ts.map