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/dist/gguf.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { u as Manifest } from "./types-CSpyQjyc.js";
1
+ import { u as Manifest } from "./types-CBW7T_3s.js";
2
2
 
3
3
  //#region src/gguf.d.ts
4
4
  interface GgufModel {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ForwardResult, c as KvSnapshot, d as ManifestArch, f as ManifestRef, i as EngineOptions, l as LoadProgress, m as TokenLogprobs, n as Engine, o as GenerateOptions, p as ManifestTensor, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as Manifest } from "./types-CSpyQjyc.js";
1
+ import { a as ForwardResult, c as KvSnapshot, d as ManifestArch, f as ManifestRef, i as EngineOptions, l as LoadProgress, m as TokenLogprobs, n as Engine, o as GenerateOptions, p as ManifestTensor, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as Manifest } from "./types-CBW7T_3s.js";
2
2
 
3
3
  //#region src/engine.d.ts
4
4
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
package/dist/index.js CHANGED
@@ -57,6 +57,7 @@ const SHADERS = {
57
57
  "rope": "// RoPE (rotate_half) with precomputed full cos/sin [S, D]. x is [S, H, D]. One invocation per element.\nstruct Params { S: u32, H: u32, D: u32, _pad: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> cos: array<f32>; // [S, D]\n@group(0) @binding(3) var<storage, read> sin: array<f32>; // [S, D]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.S * p.H * p.D) { return; }\n let d = idx % p.D;\n let sh = idx / p.D;\n let s = sh / p.H;\n let half = p.D / 2u;\n let row = sh * p.D; // s*H*D + h*D\n var rot: f32;\n if (d < half) {\n rot = -x[row + d + half];\n } else {\n rot = x[row + d - half];\n }\n y[idx] = x[idx] * cos[s * p.D + d] + rot * sin[s * p.D + d];\n}\n",
58
58
  "rope_partial": "// Partial RoPE: rotate only the first ROT dims of each head (rotate_half within [0,ROT)); the\n// remaining head_dim-ROT dims pass through unrotated. cos/sin are [S, ROT]. x/y are [S, H, D].\n// Matches tools/qwen35_numpy._rope_partial (Qwen3.5 full-attention layers, partial_rotary_factor).\nstruct Params { S: u32, H: u32, D: u32, ROT: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> cosb: array<f32>; // [S, ROT]\n@group(0) @binding(3) var<storage, read> sinb: array<f32>; // [S, ROT]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.S * p.H * p.D) { return; }\n let d = idx % p.D;\n if (d >= p.ROT) { y[idx] = x[idx]; return; } // passthrough tail\n let sh = idx / p.D;\n let s = sh / p.H;\n let half = p.ROT / 2u;\n var rot: f32;\n if (d < half) { rot = -x[idx + half]; } else { rot = x[idx - half]; }\n y[idx] = x[idx] * cosb[s * p.ROT + d] + rot * sinb[s * p.ROT + d];\n}\n",
59
59
  "sampler_penalty": "// GPU logits pre-filter for sampling: applies repetition_penalty + presence_penalty, then\n// no_repeat_ngram bans, in place on the full vocab logit buffer, so only a tiny top-K candidate set\n// has to be read back (not all ~151k logits). rep_penalty matches transformers.js over the DEDUPED\n// prompt+generated id set (logit<0 ? *penalty : /penalty); presence_penalty then SUBTRACTS a flat\n// amount from every seen token (the additive anti-repetition knob the Qwen3.5 family recommends,\n// applied after the multiplicative rep_penalty like vLLM); then ngram-banned next-tokens go to\n// -Infinity. Both id lists are computed on the CPU each step (exact, since at syncN=1 the full\n// history is known) and uploaded. presence is 0 unless requested, so `v*penalty - 0.0 == v*penalty`\n// keeps the rep-penalty-only path bit-identical. Temperature is NOT applied here: top-k is invariant\n// under the monotonic divide, so temperature is applied on the CPU to just the K candidate values\n// before softmax (bit-identical, one less pass). Single workgroup, no subgroup ops -> all devices.\n// The storageBarrier guarantees every penalty write lands before any ban write, so a token that is\n// both repeated and ngram-banned ends at -inf (ban wins, matching the reference order penalties -> ngram).\noverride WG: u32 = 256u;\n// negInf carries the -Infinity bit pattern (0xff800000) from the host: bitcasting it at RUNTIME yields\n// -inf, whereas bitcast<f32>(0xff800000u) is a const-expression evaluating to inf, which is a WGSL\n// shader-creation error. (Runtime inf is fine; only const/override inf/nan is rejected.)\nstruct Params { affectedLen: u32, banLen: u32, penalty: f32, negInf: u32, presence: f32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> affectedIds: array<u32>; // deduped prompt+generated ids\n@group(0) @binding(2) var<storage, read> banIds: array<u32>; // ngram-banned next-token ids\n@group(0) @binding(3) var<storage, read_write> logits: array<f32>; // [vocab], modified in place\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n for (var i = tid; i < p.affectedLen; i = i + WG) {\n let t = affectedIds[i];\n let v = logits[t];\n let rp = select(v / p.penalty, v * p.penalty, v < 0.0); // repetition_penalty (multiplicative)\n logits[t] = rp - p.presence; // presence_penalty (subtractive; 0 = no-op)\n }\n storageBarrier(); // all penalty writes before any ban write\n for (var i = tid; i < p.banLen; i = i + WG) {\n logits[banIds[i]] = bitcast<f32>(p.negInf); // -Infinity (runtime bitcast)\n }\n}\n",
60
+ "sampler_sigma": "// Mean/variance statistics of the (penalty-filtered) logits for the top-n-sigma warper\n// (arXiv 2411.07641): the CPU keeps candidates with logit >= max - n * sigma, where sigma is the\n// standard deviation of the FULL logit vector (the paper's statistic - a top-K-only estimate is\n// biased). Runs AFTER sampler_penalty and BEFORE the argmax_masked rounds (those mask winners in\n// place, which would corrupt the moments). Banned entries (-inf sentinel) are excluded; numerical\n// stability comes from centering on the global max before accumulating (logits are O(10), so\n// sum-of-squares around the max stays well inside f32). Three f32s are read back:\n// out = [sum(x - max), sum((x - max)^2), count] -> CPU: var = q/c - (s/c)^2.\noverride WG: u32 = 256u;\nstruct Params { N: u32, _0: u32, _1: u32, _2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> outStats: array<f32>; // [sum, sumsq, count] centered on max\n\nconst NEG_SENTINEL: f32 = -3.0e38; // below any real logit; banned entries sit at f32 -inf\n\nvar<workgroup> sa: array<f32, 256>;\nvar<workgroup> sb: array<f32, 256>;\nvar<workgroup> sc: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var m = -3.4e38;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL && v > m) { m = v; }\n }\n sa[tid] = m;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s && sa[tid + s] > sa[tid]) { sa[tid] = sa[tid + s]; }\n workgroupBarrier();\n }\n let gmax = sa[0];\n workgroupBarrier();\n var acc = 0.0;\n var accq = 0.0;\n var cnt = 0.0;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL) {\n let d = v - gmax;\n acc = acc + d;\n accq = accq + d * d;\n cnt = cnt + 1.0;\n }\n }\n sa[tid] = acc;\n sb[tid] = accq;\n sc[tid] = cnt;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n sa[tid] = sa[tid] + sa[tid + s];\n sb[tid] = sb[tid] + sb[tid + s];\n sc[tid] = sc[tid] + sc[tid + s];\n }\n workgroupBarrier();\n }\n if (tid == 0u) {\n outStats[0] = sa[0];\n outStats[1] = sb[0];\n outStats[2] = sc[0];\n }\n}\n",
60
61
  "slice_cols": "// Extract a contiguous column range [off, off+w) from each row of a [rows, stride] buffer into a\n// packed [rows, w] buffer. Splits the DeltaNet conv output (q|k|v concatenated per token) into the\n// separate q/k/v activation buffers the scan reads.\nstruct Params { rows: u32, w: u32, stride: u32, off: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, stride]\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;// [rows, w]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.rows * p.w) { return; }\n let r = i / p.w;\n let c = i % p.w;\n dst[i] = src[r * p.stride + p.off + c];\n}\n",
61
62
  "split_head": "// De-interleave a per-head doubled projection [S, H, 2*Dh] into [S, H, Dh], taking the half at\n// `off` (0 = query, Dh = gate). The Qwen3.5 gated-attention q_proj packs query and output-gate\n// interleaved per head; this pulls one out into a packed buffer.\nstruct Params { S: u32, H: u32, Dh: u32, off: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [S, H, 2*Dh]\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;// [S, H, Dh]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.S * p.H * p.Dh) { return; }\n let d = i % p.Dh;\n let sh = i / p.Dh; // s*H + h\n dst[i] = src[sh * (2u * p.Dh) + p.off + d];\n}\n",
62
63
  "swiglu": "// SwiGLU gate: y[i] = silu(gate[i]) * up[i], silu(g) = g * sigmoid(g). One invocation per element.\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> gate: array<f32>;\n@group(0) @binding(2) var<storage, read> up: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n let g = gate[i];\n y[i] = (g / (1.0 + exp(-g))) * up[i];\n}\n"
@@ -580,7 +581,8 @@ async function createEngineInner(options, holder) {
580
581
  ["embed_gather_batch"],
581
582
  ["sampler_penalty"],
582
583
  ["argmax_masked"],
583
- ["logsumexp"]
584
+ ["logsumexp"],
585
+ ["sampler_sigma"]
584
586
  ];
585
587
  if (useSG) {
586
588
  for (const n of [
@@ -656,6 +658,15 @@ async function createEngineInner(options, holder) {
656
658
  if (!transients) return;
657
659
  for (const b of transients) b.destroy();
658
660
  transients = [];
661
+ arena = null;
662
+ };
663
+ let arena = null;
664
+ let arenaCur = null;
665
+ const arenaFree = (b) => {
666
+ if (!arena) return;
667
+ const list = arena.get(b.size);
668
+ if (list) list.push(b);
669
+ else arena.set(b.size, [b]);
659
670
  };
660
671
  const upload = (typed, usage = S_ | CD) => {
661
672
  const b = device.createBuffer({
@@ -690,11 +701,17 @@ async function createEngineInner(options, holder) {
690
701
  };
691
702
  const actBuf = (n) => {
692
703
  if (!pool) {
704
+ const hit = arena?.get(n * 4)?.pop();
705
+ if (hit) {
706
+ arenaCur?.push(hit);
707
+ return hit;
708
+ }
693
709
  const b = device.createBuffer({
694
710
  size: n * 4,
695
711
  usage: S_ | CS | CD
696
712
  });
697
713
  transients?.push(b);
714
+ arenaCur?.push(b);
698
715
  return b;
699
716
  }
700
717
  const alloc = poolRoundFrom > 0 ? n / poolRoundFrom * poolRoundTo : n;
@@ -1127,12 +1144,13 @@ async function createEngineInner(options, holder) {
1127
1144
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
1128
1145
  const NK = A.hybrid?.linear_key_heads ?? 0, NV = A.hybrid?.linear_value_heads ?? 0, DKV = A.hybrid?.linear_head_dim ?? 0, CONVK = A.hybrid?.conv_kernel ?? 0, KEYDIM = NK * DKV, VALDIM = NV * DKV, CONVDIM = KEYDIM * 2 + VALDIM;
1129
1146
  const HYBRID_SCRATCH_BUDGET = 1.25 * (1 << 30);
1130
- const hybridScratchPerTok = A.hybrid ? A.hybrid.layer_types.reduce((sum, t) => {
1147
+ const hybridScratchPerTok = (() => {
1148
+ if (!A.hybrid) return 0;
1131
1149
  const shared = 3 * Hd + 3 * F;
1132
1150
  const linear = 2 * CONVDIM + 2 * KEYDIM + 4 * VALDIM + 4 * NV + Hd;
1133
1151
  const full = 8 * H * Dh + 4 * KV * Dh + Hd;
1134
- return sum + (shared + (t === "linear" ? linear : full)) * 4;
1135
- }, 0) : 0;
1152
+ return 3 * (shared + Math.max(linear, full)) * 4;
1153
+ })();
1136
1154
  const PREFILL_SEG_HY = A.hybrid ? Math.max(RECUR_FLUSH, Math.min(PREFILL_SEG, Math.floor(HYBRID_SCRATCH_BUDGET / hybridScratchPerTok / RECUR_FLUSH) * RECUR_FLUSH)) : PREFILL_SEG;
1137
1155
  let kvCapacity = Math.min(maxSeqLen, 512);
1138
1156
  const Kc = [], Vc = [];
@@ -2108,15 +2126,27 @@ async function createEngineInner(options, holder) {
2108
2126
  function stack(enc, h, S, posBase) {
2109
2127
  const { cos, sin } = ropeBufs(posBase, S);
2110
2128
  const pass = enc.beginComputePass();
2111
- let cur = h, layer0 = null;
2129
+ const useArena = !pool && !DBG0;
2130
+ let layer0 = null;
2131
+ let cur = h;
2132
+ if (useArena) arena = arena ?? /* @__PURE__ */ new Map();
2112
2133
  for (let li = 0; li < A.layers; li++) {
2113
- cur = layer(pass, li, cur, S, posBase, cos, sin);
2134
+ const mine = [];
2135
+ if (useArena) arenaCur = mine;
2136
+ const inH = cur;
2137
+ cur = layer(pass, li, inH, S, posBase, cos, sin);
2114
2138
  if (li === 0) layer0 = cur;
2139
+ if (useArena) {
2140
+ arenaCur = null;
2141
+ for (const b of mine) if (b !== cur) arenaFree(b);
2142
+ if (inH !== h && inH !== layer0) arenaFree(inH);
2143
+ }
2115
2144
  }
2116
2145
  if (A.hybrid) hyPar ^= 1;
2117
2146
  const fn = actBuf(S * Hd);
2118
2147
  rms(pass, cur, FINAL_NORM, S, Hd, fn);
2119
2148
  pass.end();
2149
+ arena = null;
2120
2150
  return {
2121
2151
  fn,
2122
2152
  layer0
@@ -2179,10 +2209,12 @@ async function createEngineInner(options, holder) {
2179
2209
  return null;
2180
2210
  }
2181
2211
  const seg = ids.slice(off, off + prefillSeg);
2212
+ device.pushErrorScope("out-of-memory");
2182
2213
  const enc = device.createCommandEncoder();
2183
2214
  fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
2184
2215
  lastRow = seg.length - 1;
2185
2216
  device.queue.submit([enc.finish()]);
2217
+ if (await device.popErrorScope()) throw new Error(`bitgpu: GPU out of memory during prefill (segment of ${seg.length} tokens at position ${posBase + off}) - the output would have been silently corrupted. Lower maxSeqLen, use kvCache: 'q8', or free GPU memory.`);
2186
2218
  if (off + prefillSeg < ids.length) {
2187
2219
  await device.queue.onSubmittedWorkDone();
2188
2220
  flushTransients();
@@ -2372,6 +2404,7 @@ async function createEngineInner(options, holder) {
2372
2404
  range: genOpts.dryRange ?? 0,
2373
2405
  breakers: new Set(genOpts.dryBreakers ?? [])
2374
2406
  } : null;
2407
+ const topNS = genOpts.topNSigma ?? 0;
2375
2408
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2376
2409
  const onToken = genOpts.onToken;
2377
2410
  const signal = genOpts.signal;
@@ -2396,6 +2429,11 @@ async function createEngineInner(options, holder) {
2396
2429
  size: 4,
2397
2430
  usage: S_ | CS
2398
2431
  });
2432
+ const sigBuf = device.createBuffer({
2433
+ size: 12,
2434
+ usage: S_ | CS
2435
+ });
2436
+ const sigOff = KT * 8 + (lpN ? 4 : 0);
2399
2437
  const affBuf = device.createBuffer({
2400
2438
  size: maxSeqLen * 4,
2401
2439
  usage: S_ | CD
@@ -2405,7 +2443,7 @@ async function createEngineInner(options, holder) {
2405
2443
  usage: S_ | CD
2406
2444
  });
2407
2445
  const rbBuf = device.createBuffer({
2408
- size: KT * 8 + (lpN ? 4 : 0),
2446
+ size: sigOff + (topNS > 0 ? 12 : 0),
2409
2447
  usage: GPUBufferUsage.MAP_READ | CD
2410
2448
  });
2411
2449
  const embG = device.createBuffer({
@@ -2440,6 +2478,15 @@ async function createEngineInner(options, holder) {
2440
2478
  ], [lg], [lseBuf]);
2441
2479
  pass.dispatchWorkgroups(1);
2442
2480
  }
2481
+ if (topNS > 0) {
2482
+ setup(pass, "sampler_sigma", [
2483
+ ["u", vocab],
2484
+ ["u", 0],
2485
+ ["u", 0],
2486
+ ["u", 0]
2487
+ ], [lg], [sigBuf]);
2488
+ pass.dispatchWorkgroups(1);
2489
+ }
2443
2490
  for (let r = 0; r < KT; r++) {
2444
2491
  setup(pass, "argmax_masked", [
2445
2492
  ["u", vocab],
@@ -2454,13 +2501,19 @@ async function createEngineInner(options, holder) {
2454
2501
  enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4);
2455
2502
  enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4);
2456
2503
  if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4);
2504
+ if (topNS > 0) enc.copyBufferToBuffer(sigBuf, 0, rbBuf, sigOff, 12);
2457
2505
  };
2506
+ let sigma = 0;
2458
2507
  const readCands = async () => {
2459
2508
  await rbBuf.mapAsync(GPUMapMode.READ);
2460
2509
  const mapped = rbBuf.getMappedRange();
2461
2510
  const ci = new Uint32Array(mapped.slice(0, KT * 4));
2462
2511
  const cv = new Float32Array(mapped.slice(KT * 4, KT * 8));
2463
2512
  const lse = lpN ? new Float32Array(mapped.slice(KT * 8, KT * 8 + 4))[0] : 0;
2513
+ if (topNS > 0) {
2514
+ const [sm, sq, c] = new Float32Array(mapped.slice(sigOff, sigOff + 12));
2515
+ sigma = c > 0 ? Math.sqrt(Math.max(0, sq / c - (sm / c) ** 2)) : 0;
2516
+ }
2464
2517
  rbBuf.unmap();
2465
2518
  return {
2466
2519
  ci,
@@ -2468,6 +2521,16 @@ async function createEngineInner(options, holder) {
2468
2521
  lse
2469
2522
  };
2470
2523
  };
2524
+ const sigTrim = (ids, vals) => {
2525
+ if (!(topNS > 0) || vals.length === 0) return null;
2526
+ const cut = vals[0] - topNS * sigma;
2527
+ let m = 1;
2528
+ while (m < vals.length && vals[m] >= cut) m++;
2529
+ return {
2530
+ ids: Array.prototype.slice.call(ids, 0, m),
2531
+ vals: Array.prototype.slice.call(vals, 0, m)
2532
+ };
2533
+ };
2471
2534
  let chosenLogit = 0;
2472
2535
  const lpOut = lpN ? [] : null;
2473
2536
  const recordLp = (ci, cv, lse) => {
@@ -2486,8 +2549,13 @@ async function createEngineInner(options, holder) {
2486
2549
  const ci = ciAll.subarray(0, K);
2487
2550
  const cv = cvAll.subarray(0, K);
2488
2551
  let ids = ci, vals = cv;
2552
+ const st = sigTrim(ci, cv);
2553
+ if (st) {
2554
+ ids = st.ids;
2555
+ vals = st.vals;
2556
+ }
2489
2557
  if (dryO) {
2490
- const a = applyDry(ci, cv, history, dryO);
2558
+ const a = applyDry(ids, vals, history, dryO);
2491
2559
  ids = a.ids;
2492
2560
  vals = a.vals;
2493
2561
  }
@@ -2509,8 +2577,13 @@ async function createEngineInner(options, holder) {
2509
2577
  pVals.push(cv[i]);
2510
2578
  }
2511
2579
  let ids = pIds, vals = pVals;
2580
+ const st = sigTrim(pIds, pVals);
2581
+ if (st) {
2582
+ ids = st.ids;
2583
+ vals = st.vals;
2584
+ }
2512
2585
  if (dryO) {
2513
- const a = applyDry(pIds, pVals, history, dryO);
2586
+ const a = applyDry(ids, vals, history, dryO);
2514
2587
  ids = a.ids;
2515
2588
  vals = a.vals;
2516
2589
  }
@@ -2536,8 +2609,13 @@ async function createEngineInner(options, holder) {
2536
2609
  }
2537
2610
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
2538
2611
  let ids = pIds, vals = pVals;
2612
+ const st = sigTrim(pIds, pVals);
2613
+ if (st) {
2614
+ ids = st.ids;
2615
+ vals = st.vals;
2616
+ }
2539
2617
  if (dryO) {
2540
- const a = applyDry(pIds, pVals, history, dryO);
2618
+ const a = applyDry(ids, vals, history, dryO);
2541
2619
  ids = a.ids;
2542
2620
  vals = a.vals;
2543
2621
  }
@@ -2663,6 +2741,7 @@ async function createEngineInner(options, holder) {
2663
2741
  candIds,
2664
2742
  candVals,
2665
2743
  lseBuf,
2744
+ sigBuf,
2666
2745
  affBuf,
2667
2746
  banBuf,
2668
2747
  rbBuf,
@@ -3092,7 +3171,7 @@ async function createEngineInner(options, holder) {
3092
3171
  async function generate(promptTokenIds, genOpts = {}) {
3093
3172
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
3094
3173
  const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0 || (genOpts.presencePenalty ?? 0) !== 0 || (genOpts.dryMultiplier ?? 0) > 0;
3095
- if ((genOpts.dryMultiplier ?? 0) > 0 && genOpts.promptLookup && genOpts.promptLookup !== "auto") throw new Error("bitgpu: dryMultiplier is not supported with promptLookup (DRY needs per-position history; auto simply disables lookup)");
3174
+ if (((genOpts.dryMultiplier ?? 0) > 0 || (genOpts.topNSigma ?? 0) > 0) && genOpts.promptLookup && genOpts.promptLookup !== "auto") throw new Error("bitgpu: dryMultiplier/topNSigma are not supported with promptLookup (they need per-position statistics; auto simply disables lookup)");
3096
3175
  const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
3097
3176
  if (genOpts.signal?.aborted) return {
3098
3177
  tokens: [],
@@ -3145,7 +3224,7 @@ async function createEngineInner(options, holder) {
3145
3224
  }
3146
3225
  const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3147
3226
  let r;
3148
- if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3227
+ if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3149
3228
  const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
3150
3229
  const E = r1.tokens.length;
3151
3230
  if (E < 24) r = r1;
@@ -3187,7 +3266,7 @@ async function createEngineInner(options, holder) {
3187
3266
  }
3188
3267
  };
3189
3268
  }
3190
- } else if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3269
+ } else if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3191
3270
  else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3192
3271
  else {
3193
3272
  const hist = fullHistory;