bitgpu 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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-CSpyQjyc.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-CSpyQjyc.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",
@@ -191,6 +191,39 @@ function ngramBans(history, n) {
191
191
  const idx = history.slice(history.length + 1 - n, history.length);
192
192
  return generated.get(JSON.stringify(idx)) ?? [];
193
193
  }
194
+ /** DRY repetition penalty (Kingbri/llama.cpp lineage), applied over the top-K candidates on the
195
+ * CPU. For each candidate c: find the longest L such that the last L history tokens followed by c
196
+ * reproduce an earlier stretch of the history (i.e. picking c would EXTEND an L-token repeat).
197
+ * If L >= allowedLength the candidate's logit drops by multiplier * base^(L - allowedLength).
198
+ * Matching never crosses a breaker token on either side, and breaker candidates are never
199
+ * penalized (structural tokens - newlines, quotes - legitimately repeat). Operating on the
200
+ * candidates (not the full vocab) mirrors how topP/minP are scoped in this engine. Returns the
201
+ * adjusted pairs re-sorted descending (stable), leaving the inputs untouched. */
202
+ function applyDry(candIds, candVals, history, o) {
203
+ const n = history.length;
204
+ const lo = o.range > 0 ? Math.max(0, n - o.range) : 0;
205
+ const MAXL = o.allowedLength + 32;
206
+ const vals = Array.from(candVals);
207
+ const ids = Array.from(candIds);
208
+ if (n > lo && o.multiplier > 0) for (let ci = 0; ci < ids.length; ci++) {
209
+ const c = ids[ci];
210
+ if (o.breakers.has(c)) continue;
211
+ let maxL = 0;
212
+ for (let i = lo; i < n; i++) {
213
+ if (history[i] !== c) continue;
214
+ let l = 0;
215
+ 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++;
216
+ if (l > maxL) maxL = l;
217
+ if (maxL >= MAXL) break;
218
+ }
219
+ if (maxL >= o.allowedLength) vals[ci] -= o.multiplier * Math.pow(o.base, maxL - o.allowedLength);
220
+ }
221
+ const order = Array.from(ids.keys()).sort((a, b) => vals[b] - vals[a] || a - b);
222
+ return {
223
+ ids: order.map((i) => ids[i]),
224
+ vals: order.map((i) => vals[i])
225
+ };
226
+ }
194
227
  /** Stable softmax (max-subtract), matching transformers.js utils/maths.js softmax. */
195
228
  function softmax(arr) {
196
229
  let maxVal = arr[0];
@@ -257,7 +290,7 @@ const WGSLS = [
257
290
  ];
258
291
  const DEFAULT_MAX_SEQ = 2048;
259
292
  const PREFILL_SEG = 256;
260
- const PREFILL_SEG_HYBRID = 16;
293
+ const RECUR_FLUSH = 16;
261
294
  const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
262
295
  const PARAM_DV = new DataView(PARAM_AB);
263
296
  const PARAM_U8 = new Uint8Array(PARAM_AB);
@@ -1093,6 +1126,14 @@ async function createEngineInner(options, holder) {
1093
1126
  }
1094
1127
  const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
1095
1128
  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
+ const HYBRID_SCRATCH_BUDGET = 1.25 * (1 << 30);
1130
+ const hybridScratchPerTok = A.hybrid ? A.hybrid.layer_types.reduce((sum, t) => {
1131
+ const shared = 3 * Hd + 3 * F;
1132
+ const linear = 2 * CONVDIM + 2 * KEYDIM + 4 * VALDIM + 4 * NV + Hd;
1133
+ const full = 8 * H * Dh + 4 * KV * Dh + Hd;
1134
+ return sum + (shared + (t === "linear" ? linear : full)) * 4;
1135
+ }, 0) : 0;
1136
+ 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
1137
  let kvCapacity = Math.min(maxSeqLen, 512);
1097
1138
  const Kc = [], Vc = [];
1098
1139
  const Ksc = [], Vsc = [];
@@ -1676,24 +1717,35 @@ async function createEngineInner(options, holder) {
1676
1717
  w("linear.dt_bias").buf
1677
1718
  ], gb, S * NV);
1678
1719
  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);
1720
+ {
1721
+ const sizes = [];
1722
+ if (Math.ceil(S / RECUR_FLUSH) % 2 === 0) sizes.push(RECUR_FLUSH / 2, RECUR_FLUSH / 2);
1723
+ for (let r = S - sizes.reduce((a, b) => a + b, 0); r > 0; r -= RECUR_FLUSH) sizes.push(Math.min(r, RECUR_FLUSH));
1724
+ let off = 0;
1725
+ for (let c = 0; c < sizes.length; c++) {
1726
+ const cin = hyRS[li][par ^ c & 1];
1727
+ const cout = hyRS[li][par ^ (c & 1 ^ 1)];
1728
+ setup(pass, "deltanet_recur", [
1729
+ ["u", sizes[c]],
1730
+ ["u", NV],
1731
+ ["u", DKV],
1732
+ ["u", DKV],
1733
+ ["u", NK],
1734
+ ["u", S * NV],
1735
+ ["u", c === 0 ? ls : 1],
1736
+ ["u", off]
1737
+ ], [
1738
+ q,
1739
+ k,
1740
+ v,
1741
+ gb,
1742
+ gb,
1743
+ cin
1744
+ ], [core, cout]);
1745
+ pass.dispatchWorkgroups(NV);
1746
+ off += sizes[c];
1747
+ }
1748
+ }
1697
1749
  const z = actBuf(S * VALDIM);
1698
1750
  fusedMM(pass, w("linear.z"), n1, S, [
1699
1751
  z,
@@ -2080,7 +2132,7 @@ async function createEngineInner(options, holder) {
2080
2132
  const vocab = W.lm_head.N;
2081
2133
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
2082
2134
  transients = [];
2083
- const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2135
+ const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
2084
2136
  try {
2085
2137
  for (let off = 0; off < S; off += prefillSeg) {
2086
2138
  const seg = ids.slice(off, off + prefillSeg);
@@ -2119,7 +2171,7 @@ async function createEngineInner(options, holder) {
2119
2171
  async function runPrefill(ids, posBase, signal) {
2120
2172
  let fn = null;
2121
2173
  let lastRow = 0;
2122
- const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2174
+ const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
2123
2175
  for (let off = 0; off < ids.length; off += prefillSeg) {
2124
2176
  if (off > 0 && signal?.aborted) {
2125
2177
  fullHistory = [];
@@ -2313,6 +2365,13 @@ async function createEngineInner(options, holder) {
2313
2365
  const topP = genOpts.topP ?? 1;
2314
2366
  const minP = genOpts.minP ?? 0;
2315
2367
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2368
+ const dryO = (genOpts.dryMultiplier ?? 0) > 0 ? {
2369
+ multiplier: genOpts.dryMultiplier,
2370
+ base: genOpts.dryBase ?? 1.75,
2371
+ allowedLength: genOpts.dryAllowedLength ?? 2,
2372
+ range: genOpts.dryRange ?? 0,
2373
+ breakers: new Set(genOpts.dryBreakers ?? [])
2374
+ } : null;
2316
2375
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2317
2376
  const onToken = genOpts.onToken;
2318
2377
  const signal = genOpts.signal;
@@ -2426,7 +2485,13 @@ async function createEngineInner(options, holder) {
2426
2485
  const pick = (ciAll, cvAll) => {
2427
2486
  const ci = ciAll.subarray(0, K);
2428
2487
  const cv = cvAll.subarray(0, K);
2429
- const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng, topP, minP) : ci[0];
2488
+ let ids = ci, vals = cv;
2489
+ if (dryO) {
2490
+ const a = applyDry(ci, cv, history, dryO);
2491
+ ids = a.ids;
2492
+ vals = a.vals;
2493
+ }
2494
+ const tk = sampled ? sampleFromCandidates(ids, vals, temperature, rng, topP, minP) : ids[0];
2430
2495
  chosenLogit = cv[ci.indexOf(tk)];
2431
2496
  return tk;
2432
2497
  };
@@ -2443,7 +2508,13 @@ async function createEngineInner(options, holder) {
2443
2508
  pIds.push(ci[i]);
2444
2509
  pVals.push(cv[i]);
2445
2510
  }
2446
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2511
+ let ids = pIds, vals = pVals;
2512
+ if (dryO) {
2513
+ const a = applyDry(pIds, pVals, history, dryO);
2514
+ ids = a.ids;
2515
+ vals = a.vals;
2516
+ }
2517
+ const tk = sampled ? sampleFromCandidates(ids, vals, temperature, rng, topP, minP) : ids[0];
2447
2518
  chosenLogit = pVals[pIds.indexOf(tk)];
2448
2519
  return tk;
2449
2520
  }
@@ -2464,7 +2535,13 @@ async function createEngineInner(options, holder) {
2464
2535
  }
2465
2536
  }
2466
2537
  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];
2538
+ let ids = pIds, vals = pVals;
2539
+ if (dryO) {
2540
+ const a = applyDry(pIds, pVals, history, dryO);
2541
+ ids = a.ids;
2542
+ vals = a.vals;
2543
+ }
2544
+ const tk = sampled ? sampleFromCandidates(ids, vals, temperature, rng, topP, minP) : ids[0];
2468
2545
  chosenLogit = pVals[pIds.indexOf(tk)];
2469
2546
  return tk;
2470
2547
  };
@@ -3014,7 +3091,8 @@ async function createEngineInner(options, holder) {
3014
3091
  };
3015
3092
  async function generate(promptTokenIds, genOpts = {}) {
3016
3093
  const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
3017
- const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0;
3094
+ 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)");
3018
3096
  const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
3019
3097
  if (genOpts.signal?.aborted) return {
3020
3098
  tokens: [],
@@ -3067,7 +3145,7 @@ async function createEngineInner(options, holder) {
3067
3145
  }
3068
3146
  const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
3069
3147
  let r;
3070
- if (!hasFilter && genOpts.promptLookup === "auto" && maxTokens > 24) {
3148
+ if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
3071
3149
  const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
3072
3150
  const E = r1.tokens.length;
3073
3151
  if (E < 24) r = r1;
@@ -3109,7 +3187,7 @@ async function createEngineInner(options, holder) {
3109
3187
  }
3110
3188
  };
3111
3189
  }
3112
- } else if (!hasFilter && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3190
+ } else if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3113
3191
  else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
3114
3192
  else {
3115
3193
  const hist = fullHistory;