bitgpu 0.19.0 → 0.19.2

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
@@ -1,4 +1,4 @@
1
- //#region src/shaders.generated.ts
1
+ // src/shaders.generated.ts
2
2
  const SHADERS = {
3
3
  "add": "// Elementwise residual add: y[i] = a[i] + b[i].\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> a: array<f32>;\n@group(0) @binding(2) var<storage, read> b: 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 y[i] = a[i] + b[i];\n}\n",
4
4
  "argmax": "// GPU argmax over the logits, writing one token id into a GPU buffer so the token never leaves the\n// GPU (enables the deferred-sync decode loop). Single workgroup, WG threads strided-scan the N\n// logits tracking (maxVal, maxIdx), then a shared-mem tree reduction. Tie-break = LOWEST index, to\n// match the CPU argmax (strict > keeps the first max). No subgroup ops -> all devices.\noverride WG: u32 = 256u;\nstruct Params { N: u32, outIdx: u32, _0: u32, _1: 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> outTok: array<u32>; // outTok[p.outIdx] = argmax\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { outTok[p.outIdx] = sidx[0]; }\n}\n",
@@ -62,8 +62,7 @@ const SHADERS = {
62
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",
63
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"
64
64
  };
65
- //#endregion
66
- //#region src/errors.ts
65
+ // src/errors.ts
67
66
  /** Thrown when WebGPU is unavailable: no `navigator.gpu` (unsupported browser, or a
68
67
  * non-secure context) or no adapter could be acquired. Catch this to render a
69
68
  * "your browser doesn't support WebGPU yet" fallback instead of crashing. */
@@ -82,8 +81,7 @@ var GpuOutOfMemoryError = class extends Error {
82
81
  super(message);
83
82
  }
84
83
  };
85
- //#endregion
86
- //#region src/pld.ts
84
+ // src/pld.ts
87
85
  /** Return up to `maxDraft` draft tokens: the continuation after the most recent prior occurrence
88
86
  * of the trailing g-gram, trying g = ngramSize down to 2 (1-grams draft too noisily to pay off).
89
87
  * Empty when nothing matches. */
@@ -109,8 +107,7 @@ function pldWorthIt(emitted, steps, sampled) {
109
107
  if (steps <= 0) return false;
110
108
  return emitted / steps >= (sampled ? 1.5 : 2);
111
109
  }
112
- //#endregion
113
- //#region src/sampler.ts
110
+ // src/sampler.ts
114
111
  /** Mersenne Twister 19937, matching transformers.js utils/random.js (= Python's random.Random). */
115
112
  var MT19937 = class {
116
113
  mt = /* @__PURE__ */ new Uint32Array(624);
@@ -127,10 +124,10 @@ var MT19937 = class {
127
124
  const mt = this.mt;
128
125
  const u = (a, b) => Math.imul(a, b) >>> 0;
129
126
  const key = [];
130
- for (let v = n || 0; v > 0; v = Math.floor(v / 4294967296)) key.push(v & 4294967295);
127
+ for (let v = n || 0; v > 0; v = Math.floor(v / 4294967296)) key.push(v & 0xffffffff);
131
128
  if (!key.length) key.push(0);
132
129
  mt[0] = 19650218;
133
- for (let k = 1; k < 624; ++k) mt[k] = u(1812433253, mt[k - 1] ^ mt[k - 1] >>> 30) + k >>> 0;
130
+ for (let k = 1; k < 624; ++k) mt[k] = u(0x6c078965, mt[k - 1] ^ mt[k - 1] >>> 30) + k >>> 0;
134
131
  let i = 1;
135
132
  let j = 0;
136
133
  for (let k = Math.max(624, key.length); k > 0; --k, ++i, ++j) {
@@ -146,30 +143,30 @@ var MT19937 = class {
146
143
  mt[0] = mt[623];
147
144
  i = 1;
148
145
  }
149
- mt[i] = (mt[i] ^ u(mt[i - 1] ^ mt[i - 1] >>> 30, 1566083941)) - i >>> 0;
146
+ mt[i] = (mt[i] ^ u(mt[i - 1] ^ mt[i - 1] >>> 30, 0x5d588b65)) - i >>> 0;
150
147
  }
151
- mt[0] = 2147483648;
148
+ mt[0] = 0x80000000;
152
149
  this.idx = 624;
153
150
  }
154
151
  int32() {
155
152
  const mt = this.mt;
156
153
  if (this.idx >= 624) {
157
154
  for (let k = 0; k < 624; ++k) {
158
- const y = mt[k] & 2147483648 | mt[(k + 1) % 624] & 2147483647;
159
- mt[k] = (mt[(k + 397) % 624] ^ y >>> 1 ^ (y & 1 ? 2567483615 : 0)) >>> 0;
155
+ const y = mt[k] & 0x80000000 | mt[(k + 1) % 624] & 0x7fffffff;
156
+ mt[k] = (mt[(k + 397) % 624] ^ y >>> 1 ^ (y & 1 ? 0x9908b0df : 0)) >>> 0;
160
157
  }
161
158
  this.idx = 0;
162
159
  }
163
160
  let y = mt[this.idx++];
164
161
  y ^= y >>> 11;
165
- y ^= y << 7 & 2636928640;
166
- y ^= y << 15 & 4022730752;
162
+ y ^= y << 7 & 0x9d2c5680;
163
+ y ^= y << 15 & 0xefc60000;
167
164
  y ^= y >>> 18;
168
165
  return y >>> 0;
169
166
  }
170
167
  /** Uniform float in [0, 1), matching Python's random.random(). */
171
168
  random() {
172
- return ((this.int32() >>> 5) * 67108864 + (this.int32() >>> 6)) / 9007199254740992;
169
+ return ((this.int32() >>> 5) * 67108864 + (this.int32() >>> 6)) / 0x20000000000000;
173
170
  }
174
171
  };
175
172
  /** Deduped set of token ids that repetition_penalty applies to (the full prompt+generated history). */
@@ -274,8 +271,7 @@ function sampleFromCandidates(candIds, candVals, temperature, rng, topP = 1, min
274
271
  }
275
272
  return candIds[m - 1];
276
273
  }
277
- //#endregion
278
- //#region src/engine.ts
274
+ // src/engine.ts
279
275
  const VIEW = {
280
276
  FLOAT: Float32Array,
281
277
  UINT8: Uint8Array,
@@ -468,7 +464,7 @@ async function createEngineInner(options, holder) {
468
464
  if (kv16 || actF16) features.push("shader-f16");
469
465
  const hasTS = adapter.features.has("timestamp-query");
470
466
  if (hasTS) features.push("timestamp-query");
471
- const DEFAULT_BINDING = 134217728;
467
+ const DEFAULT_BINDING = 0x8000000;
472
468
  const DEFAULT_BUFFER = 268435456;
473
469
  let needBind = 0;
474
470
  let weightBytes = 0;
@@ -841,7 +837,7 @@ async function createEngineInner(options, holder) {
841
837
  const e = h >> 10 & 31;
842
838
  const m = h & 1023;
843
839
  if (e === 0) return s * m * 2 ** -24;
844
- if (e === 31) return m ? NaN : s * Infinity;
840
+ if (e === 31) return m ? NaN : s * 1e400;
845
841
  return s * (1024 + m) * 2 ** (e - 25);
846
842
  };
847
843
  const wireQ10 = (region, signPush, signFinish, scalePush, scaleFinish) => {
@@ -1229,6 +1225,7 @@ async function createEngineInner(options, holder) {
1229
1225
  if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`);
1230
1226
  if (loadVal) throw new Error(`bitgpu: WebGPU validation error while loading weights: ${loadVal.message}`);
1231
1227
  async function ensureKvCapacity(needed) {
1228
+ needed = Math.min(needed, maxSeqLen);
1232
1229
  if (needed <= kvCapacity) return;
1233
1230
  const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
1234
1231
  const copyBytes = kvCapacity * KV * Dh * KVB;
@@ -2162,7 +2159,7 @@ async function createEngineInner(options, holder) {
2162
2159
  const vocab = W.lm_head.N;
2163
2160
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
2164
2161
  transients = [];
2165
- const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
2162
+ const prefillSeg = Math.min((globalThis.__SEG ?? 0) || PREFILL_SEG_HY, 32);
2166
2163
  try {
2167
2164
  for (let off = 0; off < S; off += prefillSeg) {
2168
2165
  const seg = ids.slice(off, off + prefillSeg);
@@ -2434,14 +2431,22 @@ async function createEngineInner(options, holder) {
2434
2431
  usage: S_ | CS
2435
2432
  });
2436
2433
  const sigOff = KT * 8 + (lpN ? 4 : 0);
2437
- const affBuf = device.createBuffer({
2434
+ let affBuf = device.createBuffer({
2438
2435
  size: maxSeqLen * 4,
2439
2436
  usage: S_ | CD
2440
2437
  });
2441
- const banBuf = device.createBuffer({
2438
+ let banBuf = device.createBuffer({
2442
2439
  size: maxSeqLen * 4,
2443
2440
  usage: S_ | CD
2444
2441
  });
2442
+ const grow = (b, bytes) => {
2443
+ if (bytes <= b.size) return b;
2444
+ b.destroy();
2445
+ return device.createBuffer({
2446
+ size: 1 << 32 - Math.clz32(bytes - 1),
2447
+ usage: S_ | CD
2448
+ });
2449
+ };
2445
2450
  const rbBuf = device.createBuffer({
2446
2451
  size: sigOff + (topNS > 0 ? 12 : 0),
2447
2452
  usage: GPUBufferUsage.MAP_READ | CD
@@ -2452,9 +2457,9 @@ async function createEngineInner(options, holder) {
2452
2457
  });
2453
2458
  const writeAffBan = (history) => {
2454
2459
  const aff = penalty !== 1 || presence !== 0 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
2455
- if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2460
+ if (aff.length) device.queue.writeBuffer(affBuf = grow(affBuf, aff.byteLength), 0, aff);
2456
2461
  const ban = ngramN > 0 ? ngramBans(history, ngramN) : [];
2457
- if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
2462
+ if (ban.length) device.queue.writeBuffer(banBuf = grow(banBuf, ban.length * 4), 0, Uint32Array.from(ban));
2458
2463
  return {
2459
2464
  affLen: aff.length,
2460
2465
  banLen: ban.length
@@ -2465,7 +2470,7 @@ async function createEngineInner(options, holder) {
2465
2470
  ["u", affLen],
2466
2471
  ["u", banLen],
2467
2472
  ["f", penalty],
2468
- ["u", 4286578688],
2473
+ ["u", 0xff800000],
2469
2474
  ["f", presence]
2470
2475
  ], [affBuf, banBuf], [lg]);
2471
2476
  pass.dispatchWorkgroups(1);
@@ -2569,13 +2574,14 @@ async function createEngineInner(options, holder) {
2569
2574
  const ci = ciAll.subarray(0, K);
2570
2575
  const cv = cvAll.subarray(0, K);
2571
2576
  const perm = new Set(filter(ci, cv));
2572
- if (perm.size > 0) {
2577
+ {
2573
2578
  const pIds = [];
2574
2579
  const pVals = [];
2575
2580
  for (let i = 0; i < ci.length; i++) if (perm.has(ci[i])) {
2576
2581
  pIds.push(ci[i]);
2577
2582
  pVals.push(cv[i]);
2578
2583
  }
2584
+ if (pIds.length === 0) return chooseTokenSlow(ciAll, cvAll);
2579
2585
  let ids = pIds, vals = pVals;
2580
2586
  const st = sigTrim(pIds, pVals);
2581
2587
  if (st) {
@@ -2591,6 +2597,8 @@ async function createEngineInner(options, holder) {
2591
2597
  chosenLogit = pVals[pIds.indexOf(tk)];
2592
2598
  return tk;
2593
2599
  }
2600
+ };
2601
+ const chooseTokenSlow = async (ciAll, cvAll) => {
2594
2602
  const all = await readback(lg, vocab);
2595
2603
  for (let i = 0; i < ciAll.length; i++) all[ciAll[i]] = cvAll[i];
2596
2604
  const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b);
@@ -2598,14 +2606,19 @@ async function createEngineInner(options, holder) {
2598
2606
  const pVals = [];
2599
2607
  const B = 512;
2600
2608
  for (let i = 0; i < order.length && pIds.length < K; i += B) {
2601
- if (all[order[i]] === -Infinity) break;
2602
- const batch = order.slice(i, i + B).filter((id) => all[id] !== -Infinity);
2609
+ if (all[order[i]] === -1e400 && pIds.length > 0) break;
2610
+ const batch = order.slice(i, i + B);
2603
2611
  const ok = new Set(filter(Uint32Array.from(batch), Float32Array.from(batch.map((id) => all[id]))));
2604
2612
  for (const id of batch) if (ok.has(id)) {
2605
2613
  pIds.push(id);
2606
2614
  pVals.push(all[id]);
2607
2615
  if (pIds.length >= K) break;
2608
2616
  }
2617
+ if (pVals[0] === -1e400) {
2618
+ pIds.length = 1;
2619
+ pVals.length = 1;
2620
+ break;
2621
+ }
2609
2622
  }
2610
2623
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
2611
2624
  let ids = pIds, vals = pVals;
@@ -2762,7 +2775,7 @@ async function createEngineInner(options, holder) {
2762
2775
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2763
2776
  const pl = typeof genOpts.promptLookup === "object" && genOpts.promptLookup !== null ? genOpts.promptLookup : {};
2764
2777
  const ngramSize = Math.max(2, pl.ngramSize ?? 3);
2765
- const maxDraft = Math.max(1, pl.maxDraft ?? 8);
2778
+ const maxDraft = Math.max(1, Math.min(pl.maxDraft ?? 8, 31));
2766
2779
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2767
2780
  const onToken = genOpts.onToken;
2768
2781
  const signal = genOpts.signal;
@@ -2788,14 +2801,22 @@ async function createEngineInner(options, holder) {
2788
2801
  size: K * 4,
2789
2802
  usage: S_ | CS
2790
2803
  });
2791
- const affBuf = device.createBuffer({
2804
+ let affBuf = device.createBuffer({
2792
2805
  size: (maxSeqLen + maxDraft + 1) * 4,
2793
2806
  usage: S_ | CD
2794
2807
  });
2795
- const banBuf = device.createBuffer({
2808
+ let banBuf = device.createBuffer({
2796
2809
  size: (maxSeqLen + maxDraft + 1) * 4,
2797
2810
  usage: S_ | CD
2798
2811
  });
2812
+ const grow = (b, bytes) => {
2813
+ if (bytes <= b.size) return b;
2814
+ b.destroy();
2815
+ return device.createBuffer({
2816
+ size: 1 << 32 - Math.clz32(bytes - 1),
2817
+ usage: S_ | CD
2818
+ });
2819
+ };
2799
2820
  const rbAll = device.createBuffer({
2800
2821
  size: (maxDraft + 1) * K * 8,
2801
2822
  usage: GPUBufferUsage.MAP_READ | CD
@@ -2810,9 +2831,9 @@ async function createEngineInner(options, holder) {
2810
2831
  });
2811
2832
  const writeAffBan = (h) => {
2812
2833
  const aff = penalty !== 1 || presence !== 0 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
2813
- if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2834
+ if (aff.length) device.queue.writeBuffer(affBuf = grow(affBuf, aff.byteLength), 0, aff);
2814
2835
  const ban = ngramN > 0 ? ngramBans(h, ngramN) : [];
2815
- if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
2836
+ if (ban.length) device.queue.writeBuffer(banBuf = grow(banBuf, ban.length * 4), 0, Uint32Array.from(ban));
2816
2837
  return {
2817
2838
  affLen: aff.length,
2818
2839
  banLen: ban.length
@@ -2823,7 +2844,7 @@ async function createEngineInner(options, holder) {
2823
2844
  ["u", affLen],
2824
2845
  ["u", banLen],
2825
2846
  ["f", penalty],
2826
- ["u", 4286578688],
2847
+ ["u", 0xff800000],
2827
2848
  ["f", presence]
2828
2849
  ], [affBuf, banBuf], [lg]);
2829
2850
  pass.dispatchWorkgroups(1);
@@ -3046,7 +3067,10 @@ async function createEngineInner(options, holder) {
3046
3067
  }
3047
3068
  }
3048
3069
  async function debugDecode(prefillIds) {
3070
+ fullHistory = [];
3071
+ cacheLen = 0;
3049
3072
  await ensureKvCapacity(prefillIds.length + 1);
3073
+ transients = [];
3050
3074
  const encP = device.createCommandEncoder();
3051
3075
  stack(encP, embedBatch(encP, prefillIds), prefillIds.length, 0);
3052
3076
  device.queue.submit([encP.finish()]);
@@ -3061,6 +3085,7 @@ async function createEngineInner(options, holder) {
3061
3085
  size: W.lm_head.N * 4,
3062
3086
  usage: S_ | CS
3063
3087
  });
3088
+ transients?.push(lg);
3064
3089
  const pass = enc.beginComputePass();
3065
3090
  lmHead(pass, r.fn, 1, lg);
3066
3091
  pass.end();
@@ -3080,12 +3105,22 @@ async function createEngineInner(options, holder) {
3080
3105
  DBG0 = null;
3081
3106
  return ck;
3082
3107
  };
3083
- return {
3084
- fast: await runStep(false),
3085
- slow: await runStep(true)
3086
- };
3108
+ try {
3109
+ return {
3110
+ fast: await runStep(false),
3111
+ slow: await runStep(true)
3112
+ };
3113
+ } finally {
3114
+ FORCE_SLOW = false;
3115
+ DBG0 = null;
3116
+ flushTransients();
3117
+ transients = null;
3118
+ }
3087
3119
  }
3088
3120
  async function debugSampler(ids, genOpts) {
3121
+ fullHistory = [];
3122
+ cacheLen = 0;
3123
+ transients = [];
3089
3124
  const vocab = W.lm_head.N;
3090
3125
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
3091
3126
  const penalty = genOpts.repetitionPenalty ?? 1;
@@ -3103,6 +3138,7 @@ async function createEngineInner(options, holder) {
3103
3138
  size: K * 4,
3104
3139
  usage: S_ | CS
3105
3140
  });
3141
+ transients?.push(lg, candIds, candVals);
3106
3142
  const aff = penalty !== 1 || presence !== 0 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
3107
3143
  const ban = ngramN > 0 ? ngramBans(ids, ngramN) : [];
3108
3144
  const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
@@ -3113,6 +3149,7 @@ async function createEngineInner(options, holder) {
3113
3149
  size: Hd * 4,
3114
3150
  usage: S_ | CS | CD
3115
3151
  });
3152
+ transients?.push(lastP);
3116
3153
  enc1.copyBufferToBuffer(fn, (ids.length - 1) * Hd * 4, lastP, 0, Hd * 4);
3117
3154
  let pass = enc1.beginComputePass();
3118
3155
  lmHead(pass, lastP, 1, lg);
@@ -3126,7 +3163,7 @@ async function createEngineInner(options, holder) {
3126
3163
  ["u", aff.length],
3127
3164
  ["u", ban.length],
3128
3165
  ["f", penalty],
3129
- ["u", 4286578688],
3166
+ ["u", 0xff800000],
3130
3167
  ["f", presence]
3131
3168
  ], [affBuf, banBuf], [lg]);
3132
3169
  pass.dispatchWorkgroups(1);
@@ -3142,12 +3179,17 @@ async function createEngineInner(options, holder) {
3142
3179
  pass.end();
3143
3180
  device.queue.submit([enc2.finish()]);
3144
3181
  await device.queue.onSubmittedWorkDone();
3145
- return {
3146
- base,
3147
- penalized: await readback(lg, vocab),
3148
- candIds: await readbackU32(candIds, K),
3149
- candVals: await readback(candVals, K)
3150
- };
3182
+ try {
3183
+ return {
3184
+ base,
3185
+ penalized: await readback(lg, vocab),
3186
+ candIds: await readbackU32(candIds, K),
3187
+ candVals: await readback(candVals, K)
3188
+ };
3189
+ } finally {
3190
+ flushTransients();
3191
+ transients = null;
3192
+ }
3151
3193
  }
3152
3194
  const capabilities = {
3153
3195
  useSubgroups: useSG,
@@ -3172,6 +3214,7 @@ async function createEngineInner(options, holder) {
3172
3214
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
3173
3215
  const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0 || (genOpts.presencePenalty ?? 0) !== 0 || (genOpts.dryMultiplier ?? 0) > 0;
3174
3216
  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)");
3217
+ 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");
3175
3218
  const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
3176
3219
  if (genOpts.signal?.aborted) return {
3177
3220
  tokens: [],
@@ -3186,6 +3229,7 @@ async function createEngineInner(options, holder) {
3186
3229
  };
3187
3230
  let posBase = reuse ? roll ? cacheLen : fullHistory.length - 1 : 0;
3188
3231
  const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds;
3232
+ const hist = reuse ? fullHistory : [...promptTokenIds];
3189
3233
  if (prefillTokens.length === 0) throw new Error("generate: no tokens to process");
3190
3234
  if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {
3191
3235
  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`);
@@ -3196,110 +3240,120 @@ async function createEngineInner(options, holder) {
3196
3240
  const room = maxSeqLen - posBase - prefillTokens.length;
3197
3241
  if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`);
3198
3242
  const maxTokens = roll ? genOpts.maxTokens ?? 256 : Math.min(genOpts.maxTokens ?? 256, room);
3199
- if (reuse) fullHistory.push(...promptTokenIds);
3200
- else fullHistory = [...promptTokenIds];
3201
- if (maxTokens < 1) {
3202
- await ensureKvCapacity(posBase + prefillTokens.length);
3203
- transients = [];
3204
- try {
3205
- const t0 = performance.now();
3206
- await runPrefill(prefillTokens, posBase, genOpts.signal);
3207
- await device.queue.onSubmittedWorkDone();
3208
- cacheLen = posBase + prefillTokens.length - 1;
3209
- return {
3210
- tokens: [],
3211
- prefillMs: performance.now() - t0,
3212
- decodeMs: 0,
3213
- tokensPerSecond: 0,
3214
- timing: {
3215
- recordMs: 0,
3216
- gpuMs: 0,
3217
- readbackMs: 0
3243
+ if (reuse) hist.push(...promptTokenIds);
3244
+ else fullHistory = hist;
3245
+ try {
3246
+ if (maxTokens < 1) {
3247
+ await ensureKvCapacity(posBase + prefillTokens.length);
3248
+ transients = [];
3249
+ try {
3250
+ const t0 = performance.now();
3251
+ if (prefillTokens.length > 1) {
3252
+ await runPrefill(prefillTokens.slice(0, -1), posBase, genOpts.signal);
3253
+ await device.queue.onSubmittedWorkDone();
3218
3254
  }
3219
- };
3220
- } finally {
3221
- flushTransients();
3222
- transients = null;
3255
+ cacheLen = posBase + prefillTokens.length - 1;
3256
+ return {
3257
+ tokens: [],
3258
+ prefillMs: performance.now() - t0,
3259
+ decodeMs: 0,
3260
+ tokensPerSecond: 0,
3261
+ timing: {
3262
+ recordMs: 0,
3263
+ gpuMs: 0,
3264
+ readbackMs: 0
3265
+ }
3266
+ };
3267
+ } finally {
3268
+ flushTransients();
3269
+ transients = null;
3270
+ }
3223
3271
  }
3224
- }
3225
- const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3226
- let r;
3227
- if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3228
- const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
3229
- const E = r1.tokens.length;
3230
- if (E < 24) r = r1;
3231
- else {
3232
- const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors);
3233
- const ids2 = [r1.tokens[E - 1]];
3234
- const pos2 = posBase + prefillTokens.length + E - 1;
3235
- const n2 = maxTokens - E;
3236
- let r2;
3237
- if (keep) r2 = await generatePldImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng);
3238
- else if (sampled || hasProcessors) r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, fullHistory, r1.rng);
3272
+ const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3273
+ let r;
3274
+ if (!hasFilter && !A.hybrid && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3275
+ const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, hist);
3276
+ const E = r1.tokens.length;
3277
+ if (E < 24) r = r1;
3239
3278
  else {
3240
- const hist = fullHistory;
3241
- r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, {
3242
- stopTokens: genOpts.stopTokens,
3243
- onToken: genOpts.onToken,
3244
- signal: genOpts.signal
3245
- });
3246
- hist.push(...r2.tokens);
3247
- }
3248
- const total = E + r2.tokens.length;
3249
- const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs;
3250
- const w1 = Math.max(1, E - 1);
3251
- const w2 = Math.max(0, r2.tokens.length);
3252
- r = {
3253
- prefillMs: r1.prefillMs,
3254
- decodeMs,
3255
- tokPerSec: Math.max(1, total - 1) / (decodeMs / 1e3),
3256
- tokens: [...r1.tokens, ...r2.tokens],
3257
- firstArgmax: r1.firstArgmax,
3258
- recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),
3259
- gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),
3260
- rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),
3261
- spec: {
3262
- steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),
3263
- drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),
3264
- accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),
3265
- bailed: !keep
3279
+ const keep = pldWorthIt(E, r1.spec?.steps ?? 0, sampled || hasProcessors);
3280
+ const ids2 = [r1.tokens[E - 1]];
3281
+ const pos2 = posBase + prefillTokens.length + E - 1;
3282
+ const n2 = maxTokens - E;
3283
+ let r2;
3284
+ if (keep) r2 = await generatePldImpl(ids2, pos2, n2, genOpts, hist, r1.rng);
3285
+ else if (sampled || hasProcessors) r2 = await generateSampledImpl(ids2, pos2, n2, genOpts, hist, r1.rng);
3286
+ else {
3287
+ r2 = await generateImpl(ids2, pos2, n2, null, SYNC_N, {
3288
+ stopTokens: genOpts.stopTokens,
3289
+ onToken: genOpts.onToken,
3290
+ signal: genOpts.signal
3291
+ });
3292
+ hist.push(...r2.tokens);
3266
3293
  }
3267
- };
3294
+ const total = E + r2.tokens.length;
3295
+ const decodeMs = r1.decodeMs + r2.prefillMs + r2.decodeMs;
3296
+ const w1 = Math.max(1, E - 1);
3297
+ const w2 = Math.max(0, r2.tokens.length);
3298
+ r = {
3299
+ prefillMs: r1.prefillMs,
3300
+ decodeMs,
3301
+ tokPerSec: Math.max(1, total - 1) / (decodeMs / 1e3),
3302
+ tokens: [...r1.tokens, ...r2.tokens],
3303
+ firstArgmax: r1.firstArgmax,
3304
+ recMs: (r1.recMs * w1 + r2.recMs * w2) / (w1 + w2),
3305
+ gpuMs: (r1.gpuMs * w1 + r2.gpuMs * w2) / (w1 + w2),
3306
+ rbMs: (r1.rbMs * w1 + r2.rbMs * w2) / (w1 + w2),
3307
+ spec: {
3308
+ steps: (r1.spec?.steps ?? 0) + (r2.spec?.steps ?? 0),
3309
+ drafted: (r1.spec?.drafted ?? 0) + (r2.spec?.drafted ?? 0),
3310
+ accepted: (r1.spec?.accepted ?? 0) + (r2.spec?.accepted ?? 0),
3311
+ bailed: !keep
3312
+ }
3313
+ };
3314
+ }
3315
+ } else if (!hasFilter && !A.hybrid && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, hist);
3316
+ else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, hist);
3317
+ else {
3318
+ r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
3319
+ stopTokens: genOpts.stopTokens,
3320
+ onToken: genOpts.onToken,
3321
+ signal: genOpts.signal
3322
+ });
3323
+ hist.push(...r.tokens);
3268
3324
  }
3269
- } else if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3270
- else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3271
- else {
3272
- const hist = fullHistory;
3273
- r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
3274
- stopTokens: genOpts.stopTokens,
3275
- onToken: genOpts.onToken,
3276
- signal: genOpts.signal
3277
- });
3278
- hist.push(...r.tokens);
3325
+ return {
3326
+ tokens: r.tokens,
3327
+ prefillMs: r.prefillMs,
3328
+ decodeMs: r.decodeMs,
3329
+ tokensPerSecond: r.tokPerSec,
3330
+ timing: {
3331
+ recordMs: r.recMs,
3332
+ gpuMs: r.gpuMs,
3333
+ readbackMs: r.rbMs
3334
+ },
3335
+ ...r.spec ? { speculation: r.spec } : {},
3336
+ ...r.lp ? { logprobs: r.lp } : {}
3337
+ };
3338
+ } catch (e) {
3339
+ fullHistory = [];
3340
+ cacheLen = 0;
3341
+ throw e;
3279
3342
  }
3280
- return {
3281
- tokens: r.tokens,
3282
- prefillMs: r.prefillMs,
3283
- decodeMs: r.decodeMs,
3284
- tokensPerSecond: r.tokPerSec,
3285
- timing: {
3286
- recordMs: r.recMs,
3287
- gpuMs: r.gpuMs,
3288
- readbackMs: r.rbMs
3289
- },
3290
- ...r.spec ? { speculation: r.spec } : {},
3291
- ...r.lp ? { logprobs: r.lp } : {}
3292
- };
3293
3343
  }
3294
3344
  async function prefill(ids) {
3295
3345
  if (ids.length === 0) throw new Error("prefill: no tokens to process");
3296
3346
  if (ids.length > maxSeqLen) throw new Error(`prefill: sequence length ${ids.length} exceeds maxSeqLen ${maxSeqLen}`);
3347
+ fullHistory = [];
3348
+ cacheLen = 0;
3297
3349
  await ensureKvCapacity(ids.length);
3298
3350
  transients = [];
3299
3351
  try {
3300
3352
  const t0 = performance.now();
3301
- await runPrefill(ids, 0);
3302
- await device.queue.onSubmittedWorkDone();
3353
+ if (ids.length > 1) {
3354
+ await runPrefill(ids.slice(0, -1), 0);
3355
+ await device.queue.onSubmittedWorkDone();
3356
+ }
3303
3357
  fullHistory = [...ids];
3304
3358
  cacheLen = ids.length - 1;
3305
3359
  return { prefillMs: performance.now() - t0 };
@@ -3321,34 +3375,70 @@ async function createEngineInner(options, holder) {
3321
3375
  const bytes = snapshotBytes(count);
3322
3376
  const data = new ArrayBuffer(bytes);
3323
3377
  if (bytes > 0) {
3324
- const rb = device.createBuffer({
3325
- size: bytes,
3326
- usage: GPUBufferUsage.MAP_READ | CD
3327
- });
3328
- const enc = device.createCommandEncoder();
3329
- let off = 0;
3378
+ const cap = Math.max(4, Math.min((globalThis.__RBCAP ?? 0) || 128 << 20, device.limits.maxBufferSize) & -4);
3379
+ const pieces = [];
3330
3380
  if (count > 0) for (const li of kvLayers) {
3331
- enc.copyBufferToBuffer(Kc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
3332
- off += count * kvRowBytes;
3333
- enc.copyBufferToBuffer(Vc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
3334
- off += count * kvRowBytes;
3381
+ pieces.push({
3382
+ src: Kc[li],
3383
+ off: base * kvRowBytes,
3384
+ size: count * kvRowBytes
3385
+ });
3386
+ pieces.push({
3387
+ src: Vc[li],
3388
+ off: base * kvRowBytes,
3389
+ size: count * kvRowBytes
3390
+ });
3335
3391
  if (kv8) {
3336
- enc.copyBufferToBuffer(Ksc[li], base * scRowBytes, rb, off, count * scRowBytes);
3337
- off += count * scRowBytes;
3338
- enc.copyBufferToBuffer(Vsc[li], base * scRowBytes, rb, off, count * scRowBytes);
3339
- off += count * scRowBytes;
3392
+ pieces.push({
3393
+ src: Ksc[li],
3394
+ off: base * scRowBytes,
3395
+ size: count * scRowBytes
3396
+ });
3397
+ pieces.push({
3398
+ src: Vsc[li],
3399
+ off: base * scRowBytes,
3400
+ size: count * scRowBytes
3401
+ });
3340
3402
  }
3341
3403
  }
3342
3404
  for (const li of linearLayers) {
3343
- enc.copyBufferToBuffer(hyRS[li][hyPar], 0, rb, off, rsSz);
3344
- off += rsSz;
3345
- enc.copyBufferToBuffer(hyCS[li][hyPar], 0, rb, off, csSz);
3346
- off += csSz;
3405
+ pieces.push({
3406
+ src: hyRS[li][hyPar],
3407
+ off: 0,
3408
+ size: rsSz
3409
+ });
3410
+ pieces.push({
3411
+ src: hyCS[li][hyPar],
3412
+ off: 0,
3413
+ size: csSz
3414
+ });
3415
+ }
3416
+ const rb = device.createBuffer({
3417
+ size: Math.min(bytes, cap),
3418
+ usage: GPUBufferUsage.MAP_READ | CD
3419
+ });
3420
+ let pi = 0;
3421
+ let pOff = 0;
3422
+ for (let dst = 0; dst < bytes;) {
3423
+ const sz = Math.min(cap, bytes - dst);
3424
+ const enc = device.createCommandEncoder();
3425
+ for (let fill = 0; fill < sz;) {
3426
+ const p = pieces[pi];
3427
+ const take = Math.min(p.size - pOff, sz - fill);
3428
+ enc.copyBufferToBuffer(p.src, p.off + pOff, rb, fill, take);
3429
+ fill += take;
3430
+ pOff += take;
3431
+ if (pOff === p.size) {
3432
+ pi++;
3433
+ pOff = 0;
3434
+ }
3435
+ }
3436
+ device.queue.submit([enc.finish()]);
3437
+ await rb.mapAsync(GPUMapMode.READ, 0, sz);
3438
+ new Uint8Array(data, dst, sz).set(new Uint8Array(rb.getMappedRange(0, sz)));
3439
+ rb.unmap();
3440
+ dst += sz;
3347
3441
  }
3348
- device.queue.submit([enc.finish()]);
3349
- await rb.mapAsync(GPUMapMode.READ);
3350
- new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()));
3351
- rb.unmap();
3352
3442
  rb.destroy();
3353
3443
  }
3354
3444
  return {
@@ -3382,7 +3472,7 @@ async function createEngineInner(options, holder) {
3382
3472
  const base = Math.max(0, Math.floor(snap.base ?? 0));
3383
3473
  if (base > 0 && A.hybrid) throw new Error("restoreCache: delta snapshots are not supported for the qwen3_5 hybrid backbone");
3384
3474
  const count = len - base;
3385
- if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
3475
+ 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}`);
3386
3476
  if (snap.data.byteLength !== snapshotBytes(count)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(count)}`);
3387
3477
  if (base > 0) {
3388
3478
  if (cacheLen !== base) throw new Error(`restoreCache: delta snapshot expects the cache at position ${base} (prewarm the shared prefix first); it is at ${cacheLen}`);
@@ -3432,19 +3522,20 @@ async function createEngineInner(options, holder) {
3432
3522
  dispose: () => device.destroy(),
3433
3523
  device,
3434
3524
  adapter,
3435
- profileDecode: async (ids, nTokens, full = null, syncN = SYNC_N) => {
3525
+ profileDecode: serialize(async (ids, nTokens, full = null, syncN = SYNC_N) => {
3526
+ fullHistory = [];
3527
+ cacheLen = 0;
3436
3528
  TS_PROFILE = hasTS;
3437
3529
  try {
3438
3530
  return await generateImpl(ids, 0, nTokens, full, syncN);
3439
3531
  } finally {
3440
3532
  TS_PROFILE = false;
3441
3533
  }
3442
- },
3443
- debugDecode,
3444
- debugSampler
3534
+ }),
3535
+ debugDecode: serialize(debugDecode),
3536
+ debugSampler: serialize(debugSampler)
3445
3537
  };
3446
3538
  }
3447
- //#endregion
3448
3539
  export { GpuOutOfMemoryError, WebGPUUnavailableError, createEngine };
3449
3540
 
3450
3541
  //# sourceMappingURL=index.js.map