bitgpu 0.17.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-BkfIJ42d.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-BkfIJ42d.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
@@ -24,7 +24,7 @@ const SHADERS = {
24
24
  "copy_kv8": "// q8 cache append (kvCache: 'q8'): quantize f32 K/V rows into the packed-snorm8 cache, one f32\n// scale per 32-element block (llama.cpp q8_0-style). One 64-thread workgroup per row of D\n// elements: thread t owns packed word t (4 consecutive values), the workgroup reduces per-block\n// absolute maxima through shared memory, then packs with pack4x8snorm. Replaces copy/copy_kv16\n// at every cache-append site under q8. All attention arithmetic stays f32; the precision loss is\n// exactly one snorm8 rounding of K/V at write time, nothing compounding.\nstruct Params { rows: u32, D: u32, dstRow0: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, D]\n@group(0) @binding(2) var<storage, read_write> dstQ: array<u32>; // packed 4 x snorm8 per word\n@group(0) @binding(3) var<storage, read_write> dstS: array<f32>; // [.., D/32] block scales\n\nvar<workgroup> wabs: array<f32, 64>; // per-word abs max (D <= 256 -> at most 64 words)\nvar<workgroup> wblk: array<f32, 8>; // per-block scale (D/32 <= 8 blocks)\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.rows) { return; }\n let t = lid.x;\n let W4 = p.D / 4u;\n let base = row * p.D;\n var v = vec4<f32>(0.0);\n if (t < W4) {\n v = vec4<f32>(src[base + t * 4u], src[base + t * 4u + 1u], src[base + t * 4u + 2u], src[base + t * 4u + 3u]);\n wabs[t] = max(max(abs(v.x), abs(v.y)), max(abs(v.z), abs(v.w)));\n }\n workgroupBarrier();\n if (t < p.D / 32u) {\n var m = 0.0;\n for (var i = 0u; i < 8u; i = i + 1u) { m = max(m, wabs[t * 8u + i]); }\n let s = max(m, 1e-30); // an all-zero block packs zeros, never NaN\n wblk[t] = s;\n dstS[(p.dstRow0 + row) * (p.D / 32u) + t] = s;\n }\n workgroupBarrier();\n if (t < W4) {\n dstQ[(p.dstRow0 + row) * W4 + t] = pack4x8snorm(v / wblk[t >> 3u]);\n }\n}\n",
25
25
  "deltanet_gbeta": "// DeltaNet gate/decay compute: from the a (decay input) and b (beta input) projections,\n// g[s,h] = a_neg[h] * softplus(a[s,h] + dt_bias[h]) (<= 0, log-space decay)\n// beta[s,h] = sigmoid(b[s,h])\n// per value head h. a_neg is -exp(A_log): the PrismML GGUF stores this pre-computed in the ssm_a\n// tensor (verified against the transformers A_log), so no exp() here. One invocation per (s,h);\n// output is [g (S*H) ; beta (S*H)] concatenated (engine binds two sub-ranges). Matches qwen35_numpy.\nstruct Params { S: u32, H: u32, _p0: u32, _p1: u32 }; // H = num_value_heads\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> a: array<f32>; // [S, H]\n@group(0) @binding(2) var<storage, read> b: array<f32>; // [S, H]\n@group(0) @binding(3) var<storage, read> a_neg: array<f32>; // [H] = -exp(A_log)\n@group(0) @binding(4) var<storage, read> dt_bias: array<f32>; // [H]\n@group(0) @binding(5) var<storage, read_write> out: array<f32>;// [2*S*H]: g then beta\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 let n = p.S * p.H;\n if (i >= n) { return; }\n let h = i % p.H;\n let x = a[i] + dt_bias[h];\n let sp = max(x, 0.0) + log(1.0 + exp(-abs(x))); // softplus (stable)\n out[i] = a_neg[h] * sp; // g (a_neg already = -exp(A_log))\n out[n + i] = 1.0 / (1.0 + exp(-b[i])); // beta\n}\n",
26
26
  "deltanet_norm_gate": "// Gated RMSNorm for the DeltaNet output: y = gamma * rmsnorm(core) * silu(z), normalized over the\n// value head dim (one workgroup per head-vector row). Unlike the model's plain RMSNorm this uses\n// the weight directly (not 1+weight), matching tools/qwen35_numpy (Qwen3NextRMSNormGated).\noverride WG: u32 = 128u;\nstruct Params { rows: u32, DV: u32, eps: f32, _pad: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> core: array<f32>; // [rows, DV]\n@group(0) @binding(2) var<storage, read> z: array<f32>; // [rows, DV] gate\n@group(0) @binding(3) var<storage, read> gamma: array<f32>; // [DV]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>;// [rows, DV]\nvar<workgroup> sdata: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x;\n if (row >= p.rows) { return; }\n let tid = lid.x;\n let base = row * p.DV;\n var s = 0.0;\n for (var i = tid; i < p.DV; i = i + WG) { let c = core[base + i]; s = s + c * c; }\n sdata[tid] = s;\n workgroupBarrier();\n for (var st = WG / 2u; st > 0u; st = st >> 1u) {\n if (tid < st) { sdata[tid] = sdata[tid] + sdata[tid + st]; }\n workgroupBarrier();\n }\n let inv = inverseSqrt(sdata[0] / f32(p.DV) + p.eps);\n for (var i = tid; i < p.DV; i = i + WG) {\n let zz = z[base + i];\n y[base + i] = gamma[i] * (core[base + i] * inv) * (zz / (1.0 + exp(-zz))); // * silu(z)\n }\n}\n",
27
- "deltanet_recur": "// Gated DeltaNet recurrent scan (the sequential O(1)/token gated delta rule; bitgpu's decode path\n// and a correctness reference for prefill). One workgroup per value head; thread `dv` owns value\n// column dv of the per-head state S[dk,dv], held in registers across the token loop. Per token:\n// S *= exp(g); kv = Kn·S; delta = (v - kv)·beta; S += Kn⊗delta; out = Qn·S\n// with Kn = l2norm(k), Qn = l2norm(q)/sqrt(dk) (matches tools/qwen35_numpy._delta_recurrent).\n// GQA: value head h reads q/k from key head h%HK. GGUF/bitgpu store value heads grouped\n// [rep, n_key_heads] (transposed from HF's [n_key_heads, rep]), so the shared key/query head is\n// h%HK (a \"tile\"), NOT h/(H/HK) (a \"repeat-interleave\"). loadState!=0 continues from state_in\n// (persistent decode/cross-segment state); state_out always carries the final state out.\noverride WGV: u32 = 128u; // threads per workgroup == head_v_dim (dv)\nstruct Params { S: u32, H: u32, DK: u32, DV: u32, HK: u32, betaOff: u32, loadState: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, HK, DK]\n@group(0) @binding(2) var<storage, read> k: array<f32>; // [S, HK, DK]\n@group(0) @binding(3) var<storage, read> v: array<f32>; // [S, H, DV]\n@group(0) @binding(4) var<storage, read> g: array<f32>; // [S, H]\n@group(0) @binding(5) var<storage, read> beta: array<f32>; // [S, H]\n@group(0) @binding(6) var<storage, read> state_in: array<f32>; // [H, DK, DV]\n@group(0) @binding(7) var<storage, read_write> core: array<f32>; // [S, H, DV]\n@group(0) @binding(8) var<storage, read_write> state_out: array<f32>; // [H, DK, DV]\nvar<workgroup> ksh: array<f32, 128>; // current token's raw k (>= DK)\nvar<workgroup> qsh: array<f32, 128>; // current token's raw q\n\n@compute @workgroup_size(WGV)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let h = wg.x; // value head\n let hk = h % p.HK; // GQA: shared key/query head (GGUF [rep,n_key] tile order)\n let dv = lid.x;\n let DK = p.DK;\n let sbase = h * DK * p.DV + dv; // state column S[:, dv] of head h, stride DV\n let scale = inverseSqrt(f32(DK));\n var s: array<f32, 128>; // state column S[:, dv], length DK\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = select(0.0, state_in[sbase + dk * p.DV], p.loadState != 0u); }\n\n for (var t = 0u; t < p.S; t = t + 1u) {\n let base = t * p.H + h; // value-head row (v, g, beta, out)\n let basek = t * p.HK + hk; // key-head row (q, k)\n for (var i = lid.x; i < DK; i = i + WGV) { ksh[i] = k[basek * DK + i]; qsh[i] = q[basek * DK + i]; }\n workgroupBarrier();\n var sk = 0.0;\n var sq = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { sk = sk + ksh[dk] * ksh[dk]; sq = sq + qsh[dk] * qsh[dk]; }\n let ik = inverseSqrt(sk + 1e-6); // l2norm(k)\n let iq = inverseSqrt(sq + 1e-6) * scale; // l2norm(q) / sqrt(dk)\n if (dv < p.DV) {\n let gt = exp(g[base]);\n let bt = beta[p.betaOff + base]; // beta may share g's buffer (engine: gbeta = [g; beta])\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = s[dk] * gt; } // decay\n var kv = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { kv = kv + s[dk] * ksh[dk] * ik; }\n let delta = (v[base * p.DV + dv] - kv) * bt;\n var o = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) {\n s[dk] = s[dk] + ksh[dk] * ik * delta; // S += Kn ⊗ delta\n o = o + s[dk] * qsh[dk] * iq; // out = Qn · S (updated)\n }\n core[base * p.DV + dv] = o;\n }\n workgroupBarrier();\n }\n if (dv < p.DV) { for (var dk = 0u; dk < DK; dk = dk + 1u) { state_out[sbase + dk * p.DV] = s[dk]; } }\n}\n",
27
+ "deltanet_recur": "// Gated DeltaNet recurrent scan (the sequential O(1)/token gated delta rule; bitgpu's decode path\n// and a correctness reference for prefill). One workgroup per value head; thread `dv` owns value\n// column dv of the per-head state S[dk,dv], held in registers across the token loop. Per token:\n// S *= exp(g); kv = Kn·S; delta = (v - kv)·beta; S += Kn⊗delta; out = Qn·S\n// with Kn = l2norm(k), Qn = l2norm(q)/sqrt(dk) (matches tools/qwen35_numpy._delta_recurrent).\n// GQA: value head h reads q/k from key head h%HK. GGUF/bitgpu store value heads grouped\n// [rep, n_key_heads] (transposed from HF's [n_key_heads, rep]), so the shared key/query head is\n// h%HK (a \"tile\"), NOT h/(H/HK) (a \"repeat-interleave\"). loadState!=0 continues from state_in\n// (persistent decode/cross-segment state); state_out always carries the final state out.\noverride WGV: u32 = 128u; // threads per workgroup == head_v_dim (dv)\nstruct Params { S: u32, H: u32, DK: u32, DV: u32, HK: u32, betaOff: u32, loadState: u32, tOff: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, HK, DK]\n@group(0) @binding(2) var<storage, read> k: array<f32>; // [S, HK, DK]\n@group(0) @binding(3) var<storage, read> v: array<f32>; // [S, H, DV]\n@group(0) @binding(4) var<storage, read> g: array<f32>; // [S, H]\n@group(0) @binding(5) var<storage, read> beta: array<f32>; // [S, H]\n@group(0) @binding(6) var<storage, read> state_in: array<f32>; // [H, DK, DV]\n@group(0) @binding(7) var<storage, read_write> core: array<f32>; // [S, H, DV]\n@group(0) @binding(8) var<storage, read_write> state_out: array<f32>; // [H, DK, DV]\nvar<workgroup> ksh: array<f32, 128>; // current token's raw k (>= DK)\nvar<workgroup> qsh: array<f32, 128>; // current token's raw q\n\n@compute @workgroup_size(WGV)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let h = wg.x; // value head\n let hk = h % p.HK; // GQA: shared key/query head (GGUF [rep,n_key] tile order)\n let dv = lid.x;\n let DK = p.DK;\n let sbase = h * DK * p.DV + dv; // state column S[:, dv] of head h, stride DV\n let scale = inverseSqrt(f32(DK));\n var s: array<f32, 128>; // state column S[:, dv], length DK\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = select(0.0, state_in[sbase + dk * p.DV], p.loadState != 0u); }\n\n for (var t = 0u; t < p.S; t = t + 1u) {\n let base = (t + p.tOff) * p.H + h; // value-head row (v, g, beta, out); tOff = this chunk's\n let basek = (t + p.tOff) * p.HK + hk; // token offset when a long segment's scan is sub-chunked\n for (var i = lid.x; i < DK; i = i + WGV) { ksh[i] = k[basek * DK + i]; qsh[i] = q[basek * DK + i]; }\n workgroupBarrier();\n var sk = 0.0;\n var sq = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { sk = sk + ksh[dk] * ksh[dk]; sq = sq + qsh[dk] * qsh[dk]; }\n let ik = inverseSqrt(sk + 1e-6); // l2norm(k)\n let iq = inverseSqrt(sq + 1e-6) * scale; // l2norm(q) / sqrt(dk)\n if (dv < p.DV) {\n let gt = exp(g[base]);\n let bt = beta[p.betaOff + base]; // beta may share g's buffer (engine: gbeta = [g; beta])\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = s[dk] * gt; } // decay\n var kv = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { kv = kv + s[dk] * ksh[dk] * ik; }\n let delta = (v[base * p.DV + dv] - kv) * bt;\n var o = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) {\n s[dk] = s[dk] + ksh[dk] * ik * delta; // S += Kn ⊗ delta\n o = o + s[dk] * qsh[dk] * iq; // out = Qn · S (updated)\n }\n core[base * p.DV + dv] = o;\n }\n workgroupBarrier();\n }\n if (dv < p.DV) { for (var dk = 0u; dk < DK; dk = dk + 1u) { state_out[sbase + dk * p.DV] = s[dk]; } }\n}\n",
28
28
  "embed_gather": "// GPU embedding gather + 4-bit dequant: reads a token id from a GPU buffer and writes that token's\n// embedding (H f32) directly into a GPU buffer, so the decode loop never round-trips the token id to\n// the CPU. Faithful port of the CPU embedDequant (4-bit codes via the tgt4 LUT, per-128 zero-point,\n// per-block scale). uint8 source arrays are read as u32 and byte-extracted (little-endian).\noverride WG: u32 = 256u;\nstruct Params { H: u32, srcIdx: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenId: array<u32>; // tokenId[p.srcIdx] = the token to embed\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>;// [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>;// [H]\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let id = tokenId[p.srcIdx];\n // Per-row strides derived from H: rowBytes source bytes, scaleRow f32 scales,\n // zpRow packed zero-point bytes (H=2048 -> 256/16/8, H=2560 -> 320/20/10).\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n for (var k = lid.x; k < p.H; k = k + WG) {\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[k] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n }\n}\n",
29
29
  "embed_gather_batch": "// Batched GPU embedding gather + 4-bit dequant for PROMPT tokens: one invocation per output\n// element writes out[s*H + k] for tokenIds[s]. A prefill segment uploads S u32 token ids\n// instead of S*H dequantized floats, so the CPU-side embedding tables are not needed at all\n// (~50-100 MB RAM per model). Same per-row stride math and dequant as embed_gather.wgsl\n// (H=2048 -> 256/16/8 strides); uint8 sources read as u32 and byte-extracted (little-endian).\nstruct Params { S: u32, H: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenIds: array<u32>; // [S]\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>; // [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S * H]\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 gi = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (gi >= p.S * p.H) { return; }\n let k = gi % p.H;\n let id = tokenIds[gi / p.H];\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[gi] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n}\n",
30
30
  "gate_sigmoid": "// Output gate for Qwen3.5 gated attention: y = x * sigmoid(gate), elementwise. Applied to the\n// attention output before o_proj (the gate is the second half of the doubled q_proj).\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> x: array<f32>;\n@group(0) @binding(2) var<storage, read> gate: 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] = x[i] / (1.0 + exp(-gate[i]));\n}\n",
@@ -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"
@@ -191,6 +192,39 @@ function ngramBans(history, n) {
191
192
  const idx = history.slice(history.length + 1 - n, history.length);
192
193
  return generated.get(JSON.stringify(idx)) ?? [];
193
194
  }
195
+ /** DRY repetition penalty (Kingbri/llama.cpp lineage), applied over the top-K candidates on the
196
+ * CPU. For each candidate c: find the longest L such that the last L history tokens followed by c
197
+ * reproduce an earlier stretch of the history (i.e. picking c would EXTEND an L-token repeat).
198
+ * If L >= allowedLength the candidate's logit drops by multiplier * base^(L - allowedLength).
199
+ * Matching never crosses a breaker token on either side, and breaker candidates are never
200
+ * penalized (structural tokens - newlines, quotes - legitimately repeat). Operating on the
201
+ * candidates (not the full vocab) mirrors how topP/minP are scoped in this engine. Returns the
202
+ * adjusted pairs re-sorted descending (stable), leaving the inputs untouched. */
203
+ function applyDry(candIds, candVals, history, o) {
204
+ const n = history.length;
205
+ const lo = o.range > 0 ? Math.max(0, n - o.range) : 0;
206
+ const MAXL = o.allowedLength + 32;
207
+ const vals = Array.from(candVals);
208
+ const ids = Array.from(candIds);
209
+ if (n > lo && o.multiplier > 0) for (let ci = 0; ci < ids.length; ci++) {
210
+ const c = ids[ci];
211
+ if (o.breakers.has(c)) continue;
212
+ let maxL = 0;
213
+ for (let i = lo; i < n; i++) {
214
+ if (history[i] !== c) continue;
215
+ let l = 0;
216
+ while (l < MAXL && i - 1 - l >= lo && !o.breakers.has(history[i - 1 - l]) && !o.breakers.has(history[n - 1 - l]) && history[i - 1 - l] === history[n - 1 - l]) l++;
217
+ if (l > maxL) maxL = l;
218
+ if (maxL >= MAXL) break;
219
+ }
220
+ if (maxL >= o.allowedLength) vals[ci] -= o.multiplier * Math.pow(o.base, maxL - o.allowedLength);
221
+ }
222
+ const order = Array.from(ids.keys()).sort((a, b) => vals[b] - vals[a] || a - b);
223
+ return {
224
+ ids: order.map((i) => ids[i]),
225
+ vals: order.map((i) => vals[i])
226
+ };
227
+ }
194
228
  /** Stable softmax (max-subtract), matching transformers.js utils/maths.js softmax. */
195
229
  function softmax(arr) {
196
230
  let maxVal = arr[0];
@@ -257,7 +291,7 @@ const WGSLS = [
257
291
  ];
258
292
  const DEFAULT_MAX_SEQ = 2048;
259
293
  const PREFILL_SEG = 256;
260
- const PREFILL_SEG_HYBRID = 16;
294
+ const RECUR_FLUSH = 16;
261
295
  const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
262
296
  const PARAM_DV = new DataView(PARAM_AB);
263
297
  const PARAM_U8 = new Uint8Array(PARAM_AB);
@@ -547,7 +581,8 @@ async function createEngineInner(options, holder) {
547
581
  ["embed_gather_batch"],
548
582
  ["sampler_penalty"],
549
583
  ["argmax_masked"],
550
- ["logsumexp"]
584
+ ["logsumexp"],
585
+ ["sampler_sigma"]
551
586
  ];
552
587
  if (useSG) {
553
588
  for (const n of [
@@ -623,6 +658,15 @@ async function createEngineInner(options, holder) {
623
658
  if (!transients) return;
624
659
  for (const b of transients) b.destroy();
625
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]);
626
670
  };
627
671
  const upload = (typed, usage = S_ | CD) => {
628
672
  const b = device.createBuffer({
@@ -657,11 +701,17 @@ async function createEngineInner(options, holder) {
657
701
  };
658
702
  const actBuf = (n) => {
659
703
  if (!pool) {
704
+ const hit = arena?.get(n * 4)?.pop();
705
+ if (hit) {
706
+ arenaCur?.push(hit);
707
+ return hit;
708
+ }
660
709
  const b = device.createBuffer({
661
710
  size: n * 4,
662
711
  usage: S_ | CS | CD
663
712
  });
664
713
  transients?.push(b);
714
+ arenaCur?.push(b);
665
715
  return b;
666
716
  }
667
717
  const alloc = poolRoundFrom > 0 ? n / poolRoundFrom * poolRoundTo : n;
@@ -1093,6 +1143,15 @@ async function createEngineInner(options, holder) {
1093
1143
  }
1094
1144
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
1095
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;
1146
+ const HYBRID_SCRATCH_BUDGET = 1.25 * (1 << 30);
1147
+ const hybridScratchPerTok = (() => {
1148
+ if (!A.hybrid) return 0;
1149
+ const shared = 3 * Hd + 3 * F;
1150
+ const linear = 2 * CONVDIM + 2 * KEYDIM + 4 * VALDIM + 4 * NV + Hd;
1151
+ const full = 8 * H * Dh + 4 * KV * Dh + Hd;
1152
+ return 3 * (shared + Math.max(linear, full)) * 4;
1153
+ })();
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;
1096
1155
  let kvCapacity = Math.min(maxSeqLen, 512);
1097
1156
  const Kc = [], Vc = [];
1098
1157
  const Ksc = [], Vsc = [];
@@ -1676,24 +1735,35 @@ async function createEngineInner(options, holder) {
1676
1735
  w("linear.dt_bias").buf
1677
1736
  ], gb, S * NV);
1678
1737
  const core = actBuf(S * VALDIM);
1679
- setup(pass, "deltanet_recur", [
1680
- ["u", S],
1681
- ["u", NV],
1682
- ["u", DKV],
1683
- ["u", DKV],
1684
- ["u", NK],
1685
- ["u", S * NV],
1686
- ["u", ls],
1687
- ["u", 0]
1688
- ], [
1689
- q,
1690
- k,
1691
- v,
1692
- gb,
1693
- gb,
1694
- hyRS[li][par]
1695
- ], [core, hyRS[li][par ^ 1]]);
1696
- pass.dispatchWorkgroups(NV);
1738
+ {
1739
+ const sizes = [];
1740
+ if (Math.ceil(S / RECUR_FLUSH) % 2 === 0) sizes.push(RECUR_FLUSH / 2, RECUR_FLUSH / 2);
1741
+ for (let r = S - sizes.reduce((a, b) => a + b, 0); r > 0; r -= RECUR_FLUSH) sizes.push(Math.min(r, RECUR_FLUSH));
1742
+ let off = 0;
1743
+ for (let c = 0; c < sizes.length; c++) {
1744
+ const cin = hyRS[li][par ^ c & 1];
1745
+ const cout = hyRS[li][par ^ (c & 1 ^ 1)];
1746
+ setup(pass, "deltanet_recur", [
1747
+ ["u", sizes[c]],
1748
+ ["u", NV],
1749
+ ["u", DKV],
1750
+ ["u", DKV],
1751
+ ["u", NK],
1752
+ ["u", S * NV],
1753
+ ["u", c === 0 ? ls : 1],
1754
+ ["u", off]
1755
+ ], [
1756
+ q,
1757
+ k,
1758
+ v,
1759
+ gb,
1760
+ gb,
1761
+ cin
1762
+ ], [core, cout]);
1763
+ pass.dispatchWorkgroups(NV);
1764
+ off += sizes[c];
1765
+ }
1766
+ }
1697
1767
  const z = actBuf(S * VALDIM);
1698
1768
  fusedMM(pass, w("linear.z"), n1, S, [
1699
1769
  z,
@@ -2056,15 +2126,27 @@ async function createEngineInner(options, holder) {
2056
2126
  function stack(enc, h, S, posBase) {
2057
2127
  const { cos, sin } = ropeBufs(posBase, S);
2058
2128
  const pass = enc.beginComputePass();
2059
- 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();
2060
2133
  for (let li = 0; li < A.layers; li++) {
2061
- 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);
2062
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
+ }
2063
2144
  }
2064
2145
  if (A.hybrid) hyPar ^= 1;
2065
2146
  const fn = actBuf(S * Hd);
2066
2147
  rms(pass, cur, FINAL_NORM, S, Hd, fn);
2067
2148
  pass.end();
2149
+ arena = null;
2068
2150
  return {
2069
2151
  fn,
2070
2152
  layer0
@@ -2080,7 +2162,7 @@ async function createEngineInner(options, holder) {
2080
2162
  const vocab = W.lm_head.N;
2081
2163
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
2082
2164
  transients = [];
2083
- const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2165
+ const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
2084
2166
  try {
2085
2167
  for (let off = 0; off < S; off += prefillSeg) {
2086
2168
  const seg = ids.slice(off, off + prefillSeg);
@@ -2119,7 +2201,7 @@ async function createEngineInner(options, holder) {
2119
2201
  async function runPrefill(ids, posBase, signal) {
2120
2202
  let fn = null;
2121
2203
  let lastRow = 0;
2122
- const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2204
+ const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
2123
2205
  for (let off = 0; off < ids.length; off += prefillSeg) {
2124
2206
  if (off > 0 && signal?.aborted) {
2125
2207
  fullHistory = [];
@@ -2127,10 +2209,12 @@ async function createEngineInner(options, holder) {
2127
2209
  return null;
2128
2210
  }
2129
2211
  const seg = ids.slice(off, off + prefillSeg);
2212
+ device.pushErrorScope("out-of-memory");
2130
2213
  const enc = device.createCommandEncoder();
2131
2214
  fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
2132
2215
  lastRow = seg.length - 1;
2133
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.`);
2134
2218
  if (off + prefillSeg < ids.length) {
2135
2219
  await device.queue.onSubmittedWorkDone();
2136
2220
  flushTransients();
@@ -2313,6 +2397,14 @@ async function createEngineInner(options, holder) {
2313
2397
  const topP = genOpts.topP ?? 1;
2314
2398
  const minP = genOpts.minP ?? 0;
2315
2399
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2400
+ const dryO = (genOpts.dryMultiplier ?? 0) > 0 ? {
2401
+ multiplier: genOpts.dryMultiplier,
2402
+ base: genOpts.dryBase ?? 1.75,
2403
+ allowedLength: genOpts.dryAllowedLength ?? 2,
2404
+ range: genOpts.dryRange ?? 0,
2405
+ breakers: new Set(genOpts.dryBreakers ?? [])
2406
+ } : null;
2407
+ const topNS = genOpts.topNSigma ?? 0;
2316
2408
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2317
2409
  const onToken = genOpts.onToken;
2318
2410
  const signal = genOpts.signal;
@@ -2337,6 +2429,11 @@ async function createEngineInner(options, holder) {
2337
2429
  size: 4,
2338
2430
  usage: S_ | CS
2339
2431
  });
2432
+ const sigBuf = device.createBuffer({
2433
+ size: 12,
2434
+ usage: S_ | CS
2435
+ });
2436
+ const sigOff = KT * 8 + (lpN ? 4 : 0);
2340
2437
  const affBuf = device.createBuffer({
2341
2438
  size: maxSeqLen * 4,
2342
2439
  usage: S_ | CD
@@ -2346,7 +2443,7 @@ async function createEngineInner(options, holder) {
2346
2443
  usage: S_ | CD
2347
2444
  });
2348
2445
  const rbBuf = device.createBuffer({
2349
- size: KT * 8 + (lpN ? 4 : 0),
2446
+ size: sigOff + (topNS > 0 ? 12 : 0),
2350
2447
  usage: GPUBufferUsage.MAP_READ | CD
2351
2448
  });
2352
2449
  const embG = device.createBuffer({
@@ -2381,6 +2478,15 @@ async function createEngineInner(options, holder) {
2381
2478
  ], [lg], [lseBuf]);
2382
2479
  pass.dispatchWorkgroups(1);
2383
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
+ }
2384
2490
  for (let r = 0; r < KT; r++) {
2385
2491
  setup(pass, "argmax_masked", [
2386
2492
  ["u", vocab],
@@ -2395,13 +2501,19 @@ async function createEngineInner(options, holder) {
2395
2501
  enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4);
2396
2502
  enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4);
2397
2503
  if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4);
2504
+ if (topNS > 0) enc.copyBufferToBuffer(sigBuf, 0, rbBuf, sigOff, 12);
2398
2505
  };
2506
+ let sigma = 0;
2399
2507
  const readCands = async () => {
2400
2508
  await rbBuf.mapAsync(GPUMapMode.READ);
2401
2509
  const mapped = rbBuf.getMappedRange();
2402
2510
  const ci = new Uint32Array(mapped.slice(0, KT * 4));
2403
2511
  const cv = new Float32Array(mapped.slice(KT * 4, KT * 8));
2404
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
+ }
2405
2517
  rbBuf.unmap();
2406
2518
  return {
2407
2519
  ci,
@@ -2409,6 +2521,16 @@ async function createEngineInner(options, holder) {
2409
2521
  lse
2410
2522
  };
2411
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
+ };
2412
2534
  let chosenLogit = 0;
2413
2535
  const lpOut = lpN ? [] : null;
2414
2536
  const recordLp = (ci, cv, lse) => {
@@ -2426,7 +2548,18 @@ async function createEngineInner(options, holder) {
2426
2548
  const pick = (ciAll, cvAll) => {
2427
2549
  const ci = ciAll.subarray(0, K);
2428
2550
  const cv = cvAll.subarray(0, K);
2429
- const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng, topP, minP) : ci[0];
2551
+ let ids = ci, vals = cv;
2552
+ const st = sigTrim(ci, cv);
2553
+ if (st) {
2554
+ ids = st.ids;
2555
+ vals = st.vals;
2556
+ }
2557
+ if (dryO) {
2558
+ const a = applyDry(ids, vals, history, dryO);
2559
+ ids = a.ids;
2560
+ vals = a.vals;
2561
+ }
2562
+ const tk = sampled ? sampleFromCandidates(ids, vals, temperature, rng, topP, minP) : ids[0];
2430
2563
  chosenLogit = cv[ci.indexOf(tk)];
2431
2564
  return tk;
2432
2565
  };
@@ -2443,7 +2576,18 @@ async function createEngineInner(options, holder) {
2443
2576
  pIds.push(ci[i]);
2444
2577
  pVals.push(cv[i]);
2445
2578
  }
2446
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2579
+ let ids = pIds, vals = pVals;
2580
+ const st = sigTrim(pIds, pVals);
2581
+ if (st) {
2582
+ ids = st.ids;
2583
+ vals = st.vals;
2584
+ }
2585
+ if (dryO) {
2586
+ const a = applyDry(ids, vals, history, dryO);
2587
+ ids = a.ids;
2588
+ vals = a.vals;
2589
+ }
2590
+ const tk = sampled ? sampleFromCandidates(ids, vals, temperature, rng, topP, minP) : ids[0];
2447
2591
  chosenLogit = pVals[pIds.indexOf(tk)];
2448
2592
  return tk;
2449
2593
  }
@@ -2464,7 +2608,18 @@ async function createEngineInner(options, holder) {
2464
2608
  }
2465
2609
  }
2466
2610
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
2467
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2611
+ let ids = pIds, vals = pVals;
2612
+ const st = sigTrim(pIds, pVals);
2613
+ if (st) {
2614
+ ids = st.ids;
2615
+ vals = st.vals;
2616
+ }
2617
+ if (dryO) {
2618
+ const a = applyDry(ids, vals, history, dryO);
2619
+ ids = a.ids;
2620
+ vals = a.vals;
2621
+ }
2622
+ const tk = sampled ? sampleFromCandidates(ids, vals, temperature, rng, topP, minP) : ids[0];
2468
2623
  chosenLogit = pVals[pIds.indexOf(tk)];
2469
2624
  return tk;
2470
2625
  };
@@ -2586,6 +2741,7 @@ async function createEngineInner(options, holder) {
2586
2741
  candIds,
2587
2742
  candVals,
2588
2743
  lseBuf,
2744
+ sigBuf,
2589
2745
  affBuf,
2590
2746
  banBuf,
2591
2747
  rbBuf,
@@ -3014,7 +3170,8 @@ async function createEngineInner(options, holder) {
3014
3170
  };
3015
3171
  async function generate(promptTokenIds, genOpts = {}) {
3016
3172
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
3017
- const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0;
3173
+ const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0 || (genOpts.presencePenalty ?? 0) !== 0 || (genOpts.dryMultiplier ?? 0) > 0;
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)");
3018
3175
  const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
3019
3176
  if (genOpts.signal?.aborted) return {
3020
3177
  tokens: [],
@@ -3067,7 +3224,7 @@ async function createEngineInner(options, holder) {
3067
3224
  }
3068
3225
  const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3069
3226
  let r;
3070
- if (!hasFilter && genOpts.promptLookup === "auto" && maxTokens > 24) {
3227
+ if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && (genOpts.topNSigma ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3071
3228
  const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
3072
3229
  const E = r1.tokens.length;
3073
3230
  if (E < 24) r = r1;
@@ -3109,7 +3266,7 @@ async function createEngineInner(options, holder) {
3109
3266
  }
3110
3267
  };
3111
3268
  }
3112
- } else if (!hasFilter && 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);
3113
3270
  else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3114
3271
  else {
3115
3272
  const hist = fullHistory;