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/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 = [];
@@ -1211,6 +1229,7 @@ async function createEngineInner(options, holder) {
1211
1229
  if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`);
1212
1230
  if (loadVal) throw new Error(`bitgpu: WebGPU validation error while loading weights: ${loadVal.message}`);
1213
1231
  async function ensureKvCapacity(needed) {
1232
+ needed = Math.min(needed, maxSeqLen);
1214
1233
  if (needed <= kvCapacity) return;
1215
1234
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
1216
1235
  const copyBytes = kvCapacity * KV * Dh * KVB;
@@ -2108,15 +2127,27 @@ async function createEngineInner(options, holder) {
2108
2127
  function stack(enc, h, S, posBase) {
2109
2128
  const { cos, sin } = ropeBufs(posBase, S);
2110
2129
  const pass = enc.beginComputePass();
2111
- let cur = h, layer0 = null;
2130
+ const useArena = !pool && !DBG0;
2131
+ let layer0 = null;
2132
+ let cur = h;
2133
+ if (useArena) arena = arena ?? /* @__PURE__ */ new Map();
2112
2134
  for (let li = 0; li < A.layers; li++) {
2113
- cur = layer(pass, li, cur, S, posBase, cos, sin);
2135
+ const mine = [];
2136
+ if (useArena) arenaCur = mine;
2137
+ const inH = cur;
2138
+ cur = layer(pass, li, inH, S, posBase, cos, sin);
2114
2139
  if (li === 0) layer0 = cur;
2140
+ if (useArena) {
2141
+ arenaCur = null;
2142
+ for (const b of mine) if (b !== cur) arenaFree(b);
2143
+ if (inH !== h && inH !== layer0) arenaFree(inH);
2144
+ }
2115
2145
  }
2116
2146
  if (A.hybrid) hyPar ^= 1;
2117
2147
  const fn = actBuf(S * Hd);
2118
2148
  rms(pass, cur, FINAL_NORM, S, Hd, fn);
2119
2149
  pass.end();
2150
+ arena = null;
2120
2151
  return {
2121
2152
  fn,
2122
2153
  layer0
@@ -2132,7 +2163,7 @@ async function createEngineInner(options, holder) {
2132
2163
  const vocab = W.lm_head.N;
2133
2164
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
2134
2165
  transients = [];
2135
- const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
2166
+ const prefillSeg = Math.min((globalThis.__SEG ?? 0) || PREFILL_SEG_HY, 32);
2136
2167
  try {
2137
2168
  for (let off = 0; off < S; off += prefillSeg) {
2138
2169
  const seg = ids.slice(off, off + prefillSeg);
@@ -2179,10 +2210,12 @@ async function createEngineInner(options, holder) {
2179
2210
  return null;
2180
2211
  }
2181
2212
  const seg = ids.slice(off, off + prefillSeg);
2213
+ device.pushErrorScope("out-of-memory");
2182
2214
  const enc = device.createCommandEncoder();
2183
2215
  fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
2184
2216
  lastRow = seg.length - 1;
2185
2217
  device.queue.submit([enc.finish()]);
2218
+ 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
2219
  if (off + prefillSeg < ids.length) {
2187
2220
  await device.queue.onSubmittedWorkDone();
2188
2221
  flushTransients();
@@ -2372,6 +2405,7 @@ async function createEngineInner(options, holder) {
2372
2405
  range: genOpts.dryRange ?? 0,
2373
2406
  breakers: new Set(genOpts.dryBreakers ?? [])
2374
2407
  } : null;
2408
+ const topNS = genOpts.topNSigma ?? 0;
2375
2409
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2376
2410
  const onToken = genOpts.onToken;
2377
2411
  const signal = genOpts.signal;
@@ -2396,16 +2430,29 @@ async function createEngineInner(options, holder) {
2396
2430
  size: 4,
2397
2431
  usage: S_ | CS
2398
2432
  });
2399
- const affBuf = device.createBuffer({
2433
+ const sigBuf = device.createBuffer({
2434
+ size: 12,
2435
+ usage: S_ | CS
2436
+ });
2437
+ const sigOff = KT * 8 + (lpN ? 4 : 0);
2438
+ let affBuf = device.createBuffer({
2400
2439
  size: maxSeqLen * 4,
2401
2440
  usage: S_ | CD
2402
2441
  });
2403
- const banBuf = device.createBuffer({
2442
+ let banBuf = device.createBuffer({
2404
2443
  size: maxSeqLen * 4,
2405
2444
  usage: S_ | CD
2406
2445
  });
2446
+ const grow = (b, bytes) => {
2447
+ if (bytes <= b.size) return b;
2448
+ b.destroy();
2449
+ return device.createBuffer({
2450
+ size: 1 << 32 - Math.clz32(bytes - 1),
2451
+ usage: S_ | CD
2452
+ });
2453
+ };
2407
2454
  const rbBuf = device.createBuffer({
2408
- size: KT * 8 + (lpN ? 4 : 0),
2455
+ size: sigOff + (topNS > 0 ? 12 : 0),
2409
2456
  usage: GPUBufferUsage.MAP_READ | CD
2410
2457
  });
2411
2458
  const embG = device.createBuffer({
@@ -2414,9 +2461,9 @@ async function createEngineInner(options, holder) {
2414
2461
  });
2415
2462
  const writeAffBan = (history) => {
2416
2463
  const aff = penalty !== 1 || presence !== 0 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
2417
- if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2464
+ if (aff.length) device.queue.writeBuffer(affBuf = grow(affBuf, aff.byteLength), 0, aff);
2418
2465
  const ban = ngramN > 0 ? ngramBans(history, ngramN) : [];
2419
- if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
2466
+ if (ban.length) device.queue.writeBuffer(banBuf = grow(banBuf, ban.length * 4), 0, Uint32Array.from(ban));
2420
2467
  return {
2421
2468
  affLen: aff.length,
2422
2469
  banLen: ban.length
@@ -2440,6 +2487,15 @@ async function createEngineInner(options, holder) {
2440
2487
  ], [lg], [lseBuf]);
2441
2488
  pass.dispatchWorkgroups(1);
2442
2489
  }
2490
+ if (topNS > 0) {
2491
+ setup(pass, "sampler_sigma", [
2492
+ ["u", vocab],
2493
+ ["u", 0],
2494
+ ["u", 0],
2495
+ ["u", 0]
2496
+ ], [lg], [sigBuf]);
2497
+ pass.dispatchWorkgroups(1);
2498
+ }
2443
2499
  for (let r = 0; r < KT; r++) {
2444
2500
  setup(pass, "argmax_masked", [
2445
2501
  ["u", vocab],
@@ -2454,13 +2510,19 @@ async function createEngineInner(options, holder) {
2454
2510
  enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4);
2455
2511
  enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4);
2456
2512
  if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4);
2513
+ if (topNS > 0) enc.copyBufferToBuffer(sigBuf, 0, rbBuf, sigOff, 12);
2457
2514
  };
2515
+ let sigma = 0;
2458
2516
  const readCands = async () => {
2459
2517
  await rbBuf.mapAsync(GPUMapMode.READ);
2460
2518
  const mapped = rbBuf.getMappedRange();
2461
2519
  const ci = new Uint32Array(mapped.slice(0, KT * 4));
2462
2520
  const cv = new Float32Array(mapped.slice(KT * 4, KT * 8));
2463
2521
  const lse = lpN ? new Float32Array(mapped.slice(KT * 8, KT * 8 + 4))[0] : 0;
2522
+ if (topNS > 0) {
2523
+ const [sm, sq, c] = new Float32Array(mapped.slice(sigOff, sigOff + 12));
2524
+ sigma = c > 0 ? Math.sqrt(Math.max(0, sq / c - (sm / c) ** 2)) : 0;
2525
+ }
2464
2526
  rbBuf.unmap();
2465
2527
  return {
2466
2528
  ci,
@@ -2468,6 +2530,16 @@ async function createEngineInner(options, holder) {
2468
2530
  lse
2469
2531
  };
2470
2532
  };
2533
+ const sigTrim = (ids, vals) => {
2534
+ if (!(topNS > 0) || vals.length === 0) return null;
2535
+ const cut = vals[0] - topNS * sigma;
2536
+ let m = 1;
2537
+ while (m < vals.length && vals[m] >= cut) m++;
2538
+ return {
2539
+ ids: Array.prototype.slice.call(ids, 0, m),
2540
+ vals: Array.prototype.slice.call(vals, 0, m)
2541
+ };
2542
+ };
2471
2543
  let chosenLogit = 0;
2472
2544
  const lpOut = lpN ? [] : null;
2473
2545
  const recordLp = (ci, cv, lse) => {
@@ -2486,8 +2558,13 @@ async function createEngineInner(options, holder) {
2486
2558
  const ci = ciAll.subarray(0, K);
2487
2559
  const cv = cvAll.subarray(0, K);
2488
2560
  let ids = ci, vals = cv;
2561
+ const st = sigTrim(ci, cv);
2562
+ if (st) {
2563
+ ids = st.ids;
2564
+ vals = st.vals;
2565
+ }
2489
2566
  if (dryO) {
2490
- const a = applyDry(ci, cv, history, dryO);
2567
+ const a = applyDry(ids, vals, history, dryO);
2491
2568
  ids = a.ids;
2492
2569
  vals = a.vals;
2493
2570
  }
@@ -2501,16 +2578,22 @@ async function createEngineInner(options, holder) {
2501
2578
  const ci = ciAll.subarray(0, K);
2502
2579
  const cv = cvAll.subarray(0, K);
2503
2580
  const perm = new Set(filter(ci, cv));
2504
- if (perm.size > 0) {
2581
+ {
2505
2582
  const pIds = [];
2506
2583
  const pVals = [];
2507
2584
  for (let i = 0; i < ci.length; i++) if (perm.has(ci[i])) {
2508
2585
  pIds.push(ci[i]);
2509
2586
  pVals.push(cv[i]);
2510
2587
  }
2588
+ if (pIds.length === 0) return chooseTokenSlow(ciAll, cvAll);
2511
2589
  let ids = pIds, vals = pVals;
2590
+ const st = sigTrim(pIds, pVals);
2591
+ if (st) {
2592
+ ids = st.ids;
2593
+ vals = st.vals;
2594
+ }
2512
2595
  if (dryO) {
2513
- const a = applyDry(pIds, pVals, history, dryO);
2596
+ const a = applyDry(ids, vals, history, dryO);
2514
2597
  ids = a.ids;
2515
2598
  vals = a.vals;
2516
2599
  }
@@ -2518,6 +2601,8 @@ async function createEngineInner(options, holder) {
2518
2601
  chosenLogit = pVals[pIds.indexOf(tk)];
2519
2602
  return tk;
2520
2603
  }
2604
+ };
2605
+ const chooseTokenSlow = async (ciAll, cvAll) => {
2521
2606
  const all = await readback(lg, vocab);
2522
2607
  for (let i = 0; i < ciAll.length; i++) all[ciAll[i]] = cvAll[i];
2523
2608
  const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b);
@@ -2525,19 +2610,29 @@ async function createEngineInner(options, holder) {
2525
2610
  const pVals = [];
2526
2611
  const B = 512;
2527
2612
  for (let i = 0; i < order.length && pIds.length < K; i += B) {
2528
- if (all[order[i]] === -Infinity) break;
2529
- const batch = order.slice(i, i + B).filter((id) => all[id] !== -Infinity);
2613
+ if (all[order[i]] === -Infinity && pIds.length > 0) break;
2614
+ const batch = order.slice(i, i + B);
2530
2615
  const ok = new Set(filter(Uint32Array.from(batch), Float32Array.from(batch.map((id) => all[id]))));
2531
2616
  for (const id of batch) if (ok.has(id)) {
2532
2617
  pIds.push(id);
2533
2618
  pVals.push(all[id]);
2534
2619
  if (pIds.length >= K) break;
2535
2620
  }
2621
+ if (pVals[0] === -Infinity) {
2622
+ pIds.length = 1;
2623
+ pVals.length = 1;
2624
+ break;
2625
+ }
2536
2626
  }
2537
2627
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
2538
2628
  let ids = pIds, vals = pVals;
2629
+ const st = sigTrim(pIds, pVals);
2630
+ if (st) {
2631
+ ids = st.ids;
2632
+ vals = st.vals;
2633
+ }
2539
2634
  if (dryO) {
2540
- const a = applyDry(pIds, pVals, history, dryO);
2635
+ const a = applyDry(ids, vals, history, dryO);
2541
2636
  ids = a.ids;
2542
2637
  vals = a.vals;
2543
2638
  }
@@ -2663,6 +2758,7 @@ async function createEngineInner(options, holder) {
2663
2758
  candIds,
2664
2759
  candVals,
2665
2760
  lseBuf,
2761
+ sigBuf,
2666
2762
  affBuf,
2667
2763
  banBuf,
2668
2764
  rbBuf,
@@ -2683,7 +2779,7 @@ async function createEngineInner(options, holder) {
2683
2779
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2684
2780
  const pl = typeof genOpts.promptLookup === "object" && genOpts.promptLookup !== null ? genOpts.promptLookup : {};
2685
2781
  const ngramSize = Math.max(2, pl.ngramSize ?? 3);
2686
- const maxDraft = Math.max(1, pl.maxDraft ?? 8);
2782
+ const maxDraft = Math.max(1, Math.min(pl.maxDraft ?? 8, 31));
2687
2783
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2688
2784
  const onToken = genOpts.onToken;
2689
2785
  const signal = genOpts.signal;
@@ -2709,14 +2805,22 @@ async function createEngineInner(options, holder) {
2709
2805
  size: K * 4,
2710
2806
  usage: S_ | CS
2711
2807
  });
2712
- const affBuf = device.createBuffer({
2808
+ let affBuf = device.createBuffer({
2713
2809
  size: (maxSeqLen + maxDraft + 1) * 4,
2714
2810
  usage: S_ | CD
2715
2811
  });
2716
- const banBuf = device.createBuffer({
2812
+ let banBuf = device.createBuffer({
2717
2813
  size: (maxSeqLen + maxDraft + 1) * 4,
2718
2814
  usage: S_ | CD
2719
2815
  });
2816
+ const grow = (b, bytes) => {
2817
+ if (bytes <= b.size) return b;
2818
+ b.destroy();
2819
+ return device.createBuffer({
2820
+ size: 1 << 32 - Math.clz32(bytes - 1),
2821
+ usage: S_ | CD
2822
+ });
2823
+ };
2720
2824
  const rbAll = device.createBuffer({
2721
2825
  size: (maxDraft + 1) * K * 8,
2722
2826
  usage: GPUBufferUsage.MAP_READ | CD
@@ -2731,9 +2835,9 @@ async function createEngineInner(options, holder) {
2731
2835
  });
2732
2836
  const writeAffBan = (h) => {
2733
2837
  const aff = penalty !== 1 || presence !== 0 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
2734
- if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2838
+ if (aff.length) device.queue.writeBuffer(affBuf = grow(affBuf, aff.byteLength), 0, aff);
2735
2839
  const ban = ngramN > 0 ? ngramBans(h, ngramN) : [];
2736
- if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
2840
+ if (ban.length) device.queue.writeBuffer(banBuf = grow(banBuf, ban.length * 4), 0, Uint32Array.from(ban));
2737
2841
  return {
2738
2842
  affLen: aff.length,
2739
2843
  banLen: ban.length
@@ -2967,7 +3071,10 @@ async function createEngineInner(options, holder) {
2967
3071
  }
2968
3072
  }
2969
3073
  async function debugDecode(prefillIds) {
3074
+ fullHistory = [];
3075
+ cacheLen = 0;
2970
3076
  await ensureKvCapacity(prefillIds.length + 1);
3077
+ transients = [];
2971
3078
  const encP = device.createCommandEncoder();
2972
3079
  stack(encP, embedBatch(encP, prefillIds), prefillIds.length, 0);
2973
3080
  device.queue.submit([encP.finish()]);
@@ -2982,6 +3089,7 @@ async function createEngineInner(options, holder) {
2982
3089
  size: W.lm_head.N * 4,
2983
3090
  usage: S_ | CS
2984
3091
  });
3092
+ transients?.push(lg);
2985
3093
  const pass = enc.beginComputePass();
2986
3094
  lmHead(pass, r.fn, 1, lg);
2987
3095
  pass.end();
@@ -3001,12 +3109,22 @@ async function createEngineInner(options, holder) {
3001
3109
  DBG0 = null;
3002
3110
  return ck;
3003
3111
  };
3004
- return {
3005
- fast: await runStep(false),
3006
- slow: await runStep(true)
3007
- };
3112
+ try {
3113
+ return {
3114
+ fast: await runStep(false),
3115
+ slow: await runStep(true)
3116
+ };
3117
+ } finally {
3118
+ FORCE_SLOW = false;
3119
+ DBG0 = null;
3120
+ flushTransients();
3121
+ transients = null;
3122
+ }
3008
3123
  }
3009
3124
  async function debugSampler(ids, genOpts) {
3125
+ fullHistory = [];
3126
+ cacheLen = 0;
3127
+ transients = [];
3010
3128
  const vocab = W.lm_head.N;
3011
3129
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
3012
3130
  const penalty = genOpts.repetitionPenalty ?? 1;
@@ -3024,6 +3142,7 @@ async function createEngineInner(options, holder) {
3024
3142
  size: K * 4,
3025
3143
  usage: S_ | CS
3026
3144
  });
3145
+ transients?.push(lg, candIds, candVals);
3027
3146
  const aff = penalty !== 1 || presence !== 0 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
3028
3147
  const ban = ngramN > 0 ? ngramBans(ids, ngramN) : [];
3029
3148
  const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
@@ -3034,6 +3153,7 @@ async function createEngineInner(options, holder) {
3034
3153
  size: Hd * 4,
3035
3154
  usage: S_ | CS | CD
3036
3155
  });
3156
+ transients?.push(lastP);
3037
3157
  enc1.copyBufferToBuffer(fn, (ids.length - 1) * Hd * 4, lastP, 0, Hd * 4);
3038
3158
  let pass = enc1.beginComputePass();
3039
3159
  lmHead(pass, lastP, 1, lg);
@@ -3063,12 +3183,17 @@ async function createEngineInner(options, holder) {
3063
3183
  pass.end();
3064
3184
  device.queue.submit([enc2.finish()]);
3065
3185
  await device.queue.onSubmittedWorkDone();
3066
- return {
3067
- base,
3068
- penalized: await readback(lg, vocab),
3069
- candIds: await readbackU32(candIds, K),
3070
- candVals: await readback(candVals, K)
3071
- };
3186
+ try {
3187
+ return {
3188
+ base,
3189
+ penalized: await readback(lg, vocab),
3190
+ candIds: await readbackU32(candIds, K),
3191
+ candVals: await readback(candVals, K)
3192
+ };
3193
+ } finally {
3194
+ flushTransients();
3195
+ transients = null;
3196
+ }
3072
3197
  }
3073
3198
  const capabilities = {
3074
3199
  useSubgroups: useSG,
@@ -3092,7 +3217,8 @@ async function createEngineInner(options, holder) {
3092
3217
  async function generate(promptTokenIds, genOpts = {}) {
3093
3218
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
3094
3219
  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)");
3220
+ 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)");
3221
+ if (A.hybrid && genOpts.promptLookup && genOpts.promptLookup !== "auto") throw new Error("bitgpu: promptLookup is not supported on the qwen3_5 hybrid backbone (rejected drafts would corrupt the linear-attention recurrent state); use promptLookup: 'auto' or omit it");
3096
3222
  const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
3097
3223
  if (genOpts.signal?.aborted) return {
3098
3224
  tokens: [],
@@ -3107,6 +3233,7 @@ async function createEngineInner(options, holder) {
3107
3233
  };
3108
3234
  let posBase = reuse ? roll ? cacheLen : fullHistory.length - 1 : 0;
3109
3235
  const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds;
3236
+ const hist = reuse ? fullHistory : [...promptTokenIds];
3110
3237
  if (prefillTokens.length === 0) throw new Error("generate: no tokens to process");
3111
3238
  if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {
3112
3239
  if (SINKS + prefillTokens.length + 1 > maxSeqLen) throw new Error(`generate: prompt length ${prefillTokens.length} exceeds the rolling window (maxSeqLen ${maxSeqLen} minus ${SINKS} sinks); trim the prompt`);
@@ -3117,110 +3244,120 @@ async function createEngineInner(options, holder) {
3117
3244
  const room = maxSeqLen - posBase - prefillTokens.length;
3118
3245
  if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`);
3119
3246
  const maxTokens = roll ? genOpts.maxTokens ?? 256 : Math.min(genOpts.maxTokens ?? 256, room);
3120
- if (reuse) fullHistory.push(...promptTokenIds);
3121
- else fullHistory = [...promptTokenIds];
3122
- if (maxTokens < 1) {
3123
- await ensureKvCapacity(posBase + prefillTokens.length);
3124
- transients = [];
3125
- try {
3126
- const t0 = performance.now();
3127
- await runPrefill(prefillTokens, posBase, genOpts.signal);
3128
- await device.queue.onSubmittedWorkDone();
3129
- cacheLen = posBase + prefillTokens.length - 1;
3130
- return {
3131
- tokens: [],
3132
- prefillMs: performance.now() - t0,
3133
- decodeMs: 0,
3134
- tokensPerSecond: 0,
3135
- timing: {
3136
- recordMs: 0,
3137
- gpuMs: 0,
3138
- readbackMs: 0
3247
+ if (reuse) hist.push(...promptTokenIds);
3248
+ else fullHistory = hist;
3249
+ try {
3250
+ if (maxTokens < 1) {
3251
+ await ensureKvCapacity(posBase + prefillTokens.length);
3252
+ transients = [];
3253
+ try {
3254
+ const t0 = performance.now();
3255
+ if (prefillTokens.length > 1) {
3256
+ await runPrefill(prefillTokens.slice(0, -1), posBase, genOpts.signal);
3257
+ await device.queue.onSubmittedWorkDone();
3139
3258
  }
3140
- };
3141
- } finally {
3142
- flushTransients();
3143
- transients = null;
3259
+ cacheLen = posBase + prefillTokens.length - 1;
3260
+ return {
3261
+ tokens: [],
3262
+ prefillMs: performance.now() - t0,
3263
+ decodeMs: 0,
3264
+ tokensPerSecond: 0,
3265
+ timing: {
3266
+ recordMs: 0,
3267
+ gpuMs: 0,
3268
+ readbackMs: 0
3269
+ }
3270
+ };
3271
+ } finally {
3272
+ flushTransients();
3273
+ transients = null;
3274
+ }
3144
3275
  }
3145
- }
3146
- const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3147
- let r;
3148
- if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3149
- const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
3150
- const E = r1.tokens.length;
3151
- if (E < 24) r = r1;
3152
- else {
3153
- const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors);
3154
- const ids2 = [r1.tokens[E - 1]];
3155
- const pos2 = posBase + prefillTokens.length + E - 1;
3156
- const n2 = maxTokens - E;
3157
- let r2;
3158
- if (keep) r2 = await generatePldImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng);
3159
- else if (sampled || hasProcessors) r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng);
3276
+ const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3277
+ let r;
3278
+ if (!hasFilter && !A.hybrid && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3279
+ const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, hist);
3280
+ const E = r1.tokens.length;
3281
+ if (E < 24) r = r1;
3160
3282
  else {
3161
- const hist = fullHistory;
3162
- r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, {
3163
- stopTokens: genOpts.stopTokens,
3164
- onToken: genOpts.onToken,
3165
- signal: genOpts.signal
3166
- });
3167
- hist.push(...r2.tokens);
3168
- }
3169
- const total = E + r2.tokens.length;
3170
- const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs;
3171
- const w1 = Math.max(1, E - 1);
3172
- const w2 = Math.max(0, r2.tokens.length);
3173
- r = {
3174
- prefillMs: r1.prefillMs,
3175
- decodeMs,
3176
- tokPerSec: Math.max(1, total - 1) / (decodeMs / 1e3),
3177
- tokens: [...r1.tokens, ...r2.tokens],
3178
- firstArgmax: r1.firstArgmax,
3179
- recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),
3180
- gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),
3181
- rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),
3182
- spec: {
3183
- steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),
3184
- drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),
3185
- accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),
3186
- bailed: !keep
3283
+ const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors);
3284
+ const ids2 = [r1.tokens[E - 1]];
3285
+ const pos2 = posBase + prefillTokens.length + E - 1;
3286
+ const n2 = maxTokens - E;
3287
+ let r2;
3288
+ if (keep) r2 = await generatePldImpl(ids2, pos2, n2, genOpts, hist, r1.rng);
3289
+ else if (sampled || hasProcessors) r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, hist, r1.rng);
3290
+ else {
3291
+ r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, {
3292
+ stopTokens: genOpts.stopTokens,
3293
+ onToken: genOpts.onToken,
3294
+ signal: genOpts.signal
3295
+ });
3296
+ hist.push(...r2.tokens);
3187
3297
  }
3188
- };
3298
+ const total = E + r2.tokens.length;
3299
+ const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs;
3300
+ const w1 = Math.max(1, E - 1);
3301
+ const w2 = Math.max(0, r2.tokens.length);
3302
+ r = {
3303
+ prefillMs: r1.prefillMs,
3304
+ decodeMs,
3305
+ tokPerSec: Math.max(1, total - 1) / (decodeMs / 1e3),
3306
+ tokens: [...r1.tokens, ...r2.tokens],
3307
+ firstArgmax: r1.firstArgmax,
3308
+ recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),
3309
+ gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),
3310
+ rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),
3311
+ spec: {
3312
+ steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),
3313
+ drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),
3314
+ accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),
3315
+ bailed: !keep
3316
+ }
3317
+ };
3318
+ }
3319
+ } else if (!hasFilter && !A.hybrid && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, hist);
3320
+ else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, hist);
3321
+ else {
3322
+ r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
3323
+ stopTokens: genOpts.stopTokens,
3324
+ onToken: genOpts.onToken,
3325
+ signal: genOpts.signal
3326
+ });
3327
+ hist.push(...r.tokens);
3189
3328
  }
3190
- } else if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3191
- else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3192
- else {
3193
- const hist = fullHistory;
3194
- r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
3195
- stopTokens: genOpts.stopTokens,
3196
- onToken: genOpts.onToken,
3197
- signal: genOpts.signal
3198
- });
3199
- hist.push(...r.tokens);
3329
+ return {
3330
+ tokens: r.tokens,
3331
+ prefillMs: r.prefillMs,
3332
+ decodeMs: r.decodeMs,
3333
+ tokensPerSecond: r.tokPerSec,
3334
+ timing: {
3335
+ recordMs: r.recMs,
3336
+ gpuMs: r.gpuMs,
3337
+ readbackMs: r.rbMs
3338
+ },
3339
+ ...r.spec ? { speculation: r.spec } : {},
3340
+ ...r.lp ? { logprobs: r.lp } : {}
3341
+ };
3342
+ } catch (e) {
3343
+ fullHistory = [];
3344
+ cacheLen = 0;
3345
+ throw e;
3200
3346
  }
3201
- return {
3202
- tokens: r.tokens,
3203
- prefillMs: r.prefillMs,
3204
- decodeMs: r.decodeMs,
3205
- tokensPerSecond: r.tokPerSec,
3206
- timing: {
3207
- recordMs: r.recMs,
3208
- gpuMs: r.gpuMs,
3209
- readbackMs: r.rbMs
3210
- },
3211
- ...r.spec ? { speculation: r.spec } : {},
3212
- ...r.lp ? { logprobs: r.lp } : {}
3213
- };
3214
3347
  }
3215
3348
  async function prefill(ids) {
3216
3349
  if (ids.length === 0) throw new Error("prefill: no tokens to process");
3217
3350
  if (ids.length > maxSeqLen) throw new Error(`prefill: sequence length ${ids.length} exceeds maxSeqLen ${maxSeqLen}`);
3351
+ fullHistory = [];
3352
+ cacheLen = 0;
3218
3353
  await ensureKvCapacity(ids.length);
3219
3354
  transients = [];
3220
3355
  try {
3221
3356
  const t0 = performance.now();
3222
- await runPrefill(ids, 0);
3223
- await device.queue.onSubmittedWorkDone();
3357
+ if (ids.length > 1) {
3358
+ await runPrefill(ids.slice(0, -1), 0);
3359
+ await device.queue.onSubmittedWorkDone();
3360
+ }
3224
3361
  fullHistory = [...ids];
3225
3362
  cacheLen = ids.length - 1;
3226
3363
  return { prefillMs: performance.now() - t0 };
@@ -3242,34 +3379,70 @@ async function createEngineInner(options, holder) {
3242
3379
  const bytes = snapshotBytes(count);
3243
3380
  const data = new ArrayBuffer(bytes);
3244
3381
  if (bytes > 0) {
3245
- const rb = device.createBuffer({
3246
- size: bytes,
3247
- usage: GPUBufferUsage.MAP_READ | CD
3248
- });
3249
- const enc = device.createCommandEncoder();
3250
- let off = 0;
3382
+ const cap = Math.max(4, Math.min((globalThis.__RBCAP ?? 0) || 128 << 20, device.limits.maxBufferSize) & -4);
3383
+ const pieces = [];
3251
3384
  if (count > 0) for (const li of kvLayers) {
3252
- enc.copyBufferToBuffer(Kc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
3253
- off += count * kvRowBytes;
3254
- enc.copyBufferToBuffer(Vc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
3255
- off += count * kvRowBytes;
3385
+ pieces.push({
3386
+ src: Kc[li],
3387
+ off: base * kvRowBytes,
3388
+ size: count * kvRowBytes
3389
+ });
3390
+ pieces.push({
3391
+ src: Vc[li],
3392
+ off: base * kvRowBytes,
3393
+ size: count * kvRowBytes
3394
+ });
3256
3395
  if (kv8) {
3257
- enc.copyBufferToBuffer(Ksc[li], base * scRowBytes, rb, off, count * scRowBytes);
3258
- off += count * scRowBytes;
3259
- enc.copyBufferToBuffer(Vsc[li], base * scRowBytes, rb, off, count * scRowBytes);
3260
- off += count * scRowBytes;
3396
+ pieces.push({
3397
+ src: Ksc[li],
3398
+ off: base * scRowBytes,
3399
+ size: count * scRowBytes
3400
+ });
3401
+ pieces.push({
3402
+ src: Vsc[li],
3403
+ off: base * scRowBytes,
3404
+ size: count * scRowBytes
3405
+ });
3261
3406
  }
3262
3407
  }
3263
3408
  for (const li of linearLayers) {
3264
- enc.copyBufferToBuffer(hyRS[li][hyPar], 0, rb, off, rsSz);
3265
- off += rsSz;
3266
- enc.copyBufferToBuffer(hyCS[li][hyPar], 0, rb, off, csSz);
3267
- off += csSz;
3409
+ pieces.push({
3410
+ src: hyRS[li][hyPar],
3411
+ off: 0,
3412
+ size: rsSz
3413
+ });
3414
+ pieces.push({
3415
+ src: hyCS[li][hyPar],
3416
+ off: 0,
3417
+ size: csSz
3418
+ });
3419
+ }
3420
+ const rb = device.createBuffer({
3421
+ size: Math.min(bytes, cap),
3422
+ usage: GPUBufferUsage.MAP_READ | CD
3423
+ });
3424
+ let pi = 0;
3425
+ let pOff = 0;
3426
+ for (let dst = 0; dst < bytes;) {
3427
+ const sz = Math.min(cap, bytes - dst);
3428
+ const enc = device.createCommandEncoder();
3429
+ for (let fill = 0; fill < sz;) {
3430
+ const p = pieces[pi];
3431
+ const take = Math.min(p.size - pOff, sz - fill);
3432
+ enc.copyBufferToBuffer(p.src, p.off + pOff, rb, fill, take);
3433
+ fill += take;
3434
+ pOff += take;
3435
+ if (pOff === p.size) {
3436
+ pi++;
3437
+ pOff = 0;
3438
+ }
3439
+ }
3440
+ device.queue.submit([enc.finish()]);
3441
+ await rb.mapAsync(GPUMapMode.READ, 0, sz);
3442
+ new Uint8Array(data, dst, sz).set(new Uint8Array(rb.getMappedRange(0, sz)));
3443
+ rb.unmap();
3444
+ dst += sz;
3268
3445
  }
3269
- device.queue.submit([enc.finish()]);
3270
- await rb.mapAsync(GPUMapMode.READ);
3271
- new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()));
3272
- rb.unmap();
3273
3446
  rb.destroy();
3274
3447
  }
3275
3448
  return {
@@ -3303,7 +3476,7 @@ async function createEngineInner(options, holder) {
3303
3476
  const base = Math.max(0, Math.floor(snap.base ?? 0));
3304
3477
  if (base > 0 && A.hybrid) throw new Error("restoreCache: delta snapshots are not supported for the qwen3_5 hybrid backbone");
3305
3478
  const count = len - base;
3306
- if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
3479
+ if (len + (snap.version === 2 ? 0 : 1) > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + (snap.version === 2 ? 0 : 1)} cache slots but maxSeqLen is ${maxSeqLen}`);
3307
3480
  if (snap.data.byteLength !== snapshotBytes(count)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(count)}`);
3308
3481
  if (base > 0) {
3309
3482
  if (cacheLen !== base) throw new Error(`restoreCache: delta snapshot expects the cache at position ${base} (prewarm the shared prefix first); it is at ${cacheLen}`);
@@ -3353,16 +3526,18 @@ async function createEngineInner(options, holder) {
3353
3526
  dispose: () => device.destroy(),
3354
3527
  device,
3355
3528
  adapter,
3356
- profileDecode: async (ids, nTokens, full = null, syncN = SYNC_N) => {
3529
+ profileDecode: serialize(async (ids, nTokens, full = null, syncN = SYNC_N) => {
3530
+ fullHistory = [];
3531
+ cacheLen = 0;
3357
3532
  TS_PROFILE = hasTS;
3358
3533
  try {
3359
3534
  return await generateImpl(ids, 0, nTokens, full, syncN);
3360
3535
  } finally {
3361
3536
  TS_PROFILE = false;
3362
3537
  }
3363
- },
3364
- debugDecode,
3365
- debugSampler
3538
+ }),
3539
+ debugDecode: serialize(debugDecode),
3540
+ debugSampler: serialize(debugSampler)
3366
3541
  };
3367
3542
  }
3368
3543
  //#endregion