bitgpu 0.16.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/README.md +35 -11
- package/dist/chat.d.ts +95 -4
- package/dist/chat.js +409 -17
- package/dist/chat.js.map +1 -1
- package/dist/gguf.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +178 -46
- package/dist/index.js.map +1 -1
- package/dist/{types-Wg8VrdrL.d.ts → types-CSpyQjyc.d.ts} +32 -2
- package/package.json +1 -1
package/dist/gguf.d.ts
CHANGED
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-
|
|
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,
|
|
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",
|
|
@@ -56,7 +56,7 @@ const SHADERS = {
|
|
|
56
56
|
"rmsnorm_wg": "// RMSNorm, no-subgroup fallback: one workgroup per row; threads split D and tree-reduce the\n// sum of squares via shared memory. Replaces the one-thread-per-row kernel on this path: at\n// decode (R=1) that kernel walked 2xD elements serially on a single thread, latency-bound,\n// and it ran twice per layer - the dominant cost of the whole fallback decode step.\n// Mirrors rmsnorm_sg exactly, with subgroupAdd swapped for the shared-memory reduction.\noverride WG: u32 = 64u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read_write> y: array<f32>; // [R, D]\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\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; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.R) { return; }\n let tid = lid.x;\n let base = row * p.D;\n var s = 0.0;\n for (var i = tid; i < p.D; i = i + WG) { let v = x[base + i]; s = s + v * v; }\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.D) + p.eps);\n for (var i = tid; i < p.D; i = i + WG) { y[base + i] = x[base + i] * inv * gamma[i]; }\n}\n",
|
|
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
|
-
"sampler_penalty": "// GPU logits pre-filter for sampling: applies repetition_penalty then no_repeat_ngram bans in place
|
|
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
60
|
"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
61
|
"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
62
|
"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 +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];
|
|
@@ -201,21 +234,44 @@ function softmax(arr) {
|
|
|
201
234
|
return exps.map((x) => x / sum);
|
|
202
235
|
}
|
|
203
236
|
/** Final sampling tail. `candVals` are the K largest PENALTY-FILTERED logits (descending), `candIds`
|
|
204
|
-
* their token ids. Applies temperature to the K values, softmaxes,
|
|
205
|
-
*
|
|
206
|
-
|
|
237
|
+
* their token ids. Applies temperature to the K values, softmaxes, optionally trims the pool with
|
|
238
|
+
* top-p (nucleus) and/or min-p, then draws via the exact transformers.js inverse-CDF weighted pick
|
|
239
|
+
* (x = random()*sum; subtract until <0). `topP` (default 1 = off) keeps the shortest leading run
|
|
240
|
+
* whose cumulative probability reaches topP; `minP` (default 0 = off) keeps tokens with probability
|
|
241
|
+
* >= minP*maxProb - both operate on the already-descending candidates, so each keeps a prefix and
|
|
242
|
+
* the kept set is their shorter prefix. With both off the draw is bit-identical to the plain path
|
|
243
|
+
* (m == k, sum over all K). Returns a token id. */
|
|
244
|
+
function sampleFromCandidates(candIds, candVals, temperature, rng, topP = 1, minP = 0) {
|
|
207
245
|
const k = candVals.length;
|
|
208
246
|
const tv = new Float32Array(k);
|
|
209
247
|
for (let i = 0; i < k; ++i) tv[i] = candVals[i] / temperature;
|
|
210
248
|
const probs = softmax(tv);
|
|
249
|
+
let m = k;
|
|
250
|
+
if (minP > 0) {
|
|
251
|
+
const thresh = minP * probs[0];
|
|
252
|
+
let c = 1;
|
|
253
|
+
while (c < k && probs[c] >= thresh) c++;
|
|
254
|
+
if (c < m) m = c;
|
|
255
|
+
}
|
|
256
|
+
if (topP < 1) {
|
|
257
|
+
let cum = 0;
|
|
258
|
+
let c = 0;
|
|
259
|
+
while (c < k) {
|
|
260
|
+
cum += probs[c];
|
|
261
|
+
c++;
|
|
262
|
+
if (cum >= topP) break;
|
|
263
|
+
}
|
|
264
|
+
if (c < m) m = c;
|
|
265
|
+
}
|
|
266
|
+
if (m < 1) m = 1;
|
|
211
267
|
let sum = 0;
|
|
212
|
-
for (
|
|
268
|
+
for (let i = 0; i < m; ++i) sum += probs[i];
|
|
213
269
|
let x = rng.random() * sum;
|
|
214
|
-
for (let i = 0; i <
|
|
270
|
+
for (let i = 0; i < m; ++i) {
|
|
215
271
|
x -= probs[i];
|
|
216
272
|
if (x < 0) return candIds[i];
|
|
217
273
|
}
|
|
218
|
-
return candIds[
|
|
274
|
+
return candIds[m - 1];
|
|
219
275
|
}
|
|
220
276
|
//#endregion
|
|
221
277
|
//#region src/engine.ts
|
|
@@ -234,6 +290,7 @@ const WGSLS = [
|
|
|
234
290
|
];
|
|
235
291
|
const DEFAULT_MAX_SEQ = 2048;
|
|
236
292
|
const PREFILL_SEG = 256;
|
|
293
|
+
const RECUR_FLUSH = 16;
|
|
237
294
|
const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
|
|
238
295
|
const PARAM_DV = new DataView(PARAM_AB);
|
|
239
296
|
const PARAM_U8 = new Uint8Array(PARAM_AB);
|
|
@@ -1069,6 +1126,14 @@ async function createEngineInner(options, holder) {
|
|
|
1069
1126
|
}
|
|
1070
1127
|
const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
|
|
1071
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;
|
|
1072
1137
|
let kvCapacity = Math.min(maxSeqLen, 512);
|
|
1073
1138
|
const Kc = [], Vc = [];
|
|
1074
1139
|
const Ksc = [], Vsc = [];
|
|
@@ -1299,7 +1364,8 @@ async function createEngineInner(options, holder) {
|
|
|
1299
1364
|
usage: U | CD
|
|
1300
1365
|
}),
|
|
1301
1366
|
bg: null,
|
|
1302
|
-
last: null
|
|
1367
|
+
last: null,
|
|
1368
|
+
bufs: null
|
|
1303
1369
|
};
|
|
1304
1370
|
pool.disp[dispIdx] = slot;
|
|
1305
1371
|
}
|
|
@@ -1308,6 +1374,22 @@ async function createEngineInner(options, holder) {
|
|
|
1308
1374
|
device.queue.writeBuffer(slot.uni, 0, data2);
|
|
1309
1375
|
slot.last = data2.slice();
|
|
1310
1376
|
}
|
|
1377
|
+
if (slot.bg && slot.bufs) {
|
|
1378
|
+
const nb = ins.length + outs.length;
|
|
1379
|
+
if (slot.bufs.length !== nb) slot.bg = null;
|
|
1380
|
+
else {
|
|
1381
|
+
for (let i = 0; i < ins.length; i++) if (slot.bufs[i] !== ins[i]) {
|
|
1382
|
+
slot.bg = null;
|
|
1383
|
+
break;
|
|
1384
|
+
}
|
|
1385
|
+
if (slot.bg) {
|
|
1386
|
+
for (let i = 0; i < outs.length; i++) if (slot.bufs[ins.length + i] !== outs[i]) {
|
|
1387
|
+
slot.bg = null;
|
|
1388
|
+
break;
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1311
1393
|
if (!slot.bg) {
|
|
1312
1394
|
const entries = [{
|
|
1313
1395
|
binding: 0,
|
|
@@ -1325,6 +1407,7 @@ async function createEngineInner(options, holder) {
|
|
|
1325
1407
|
layout: pipelines[name].getBindGroupLayout(0),
|
|
1326
1408
|
entries
|
|
1327
1409
|
});
|
|
1410
|
+
slot.bufs = [...ins, ...outs];
|
|
1328
1411
|
}
|
|
1329
1412
|
pass.setBindGroup(0, slot.bg);
|
|
1330
1413
|
dispIdx++;
|
|
@@ -1634,24 +1717,35 @@ async function createEngineInner(options, holder) {
|
|
|
1634
1717
|
w("linear.dt_bias").buf
|
|
1635
1718
|
], gb, S * NV);
|
|
1636
1719
|
const core = actBuf(S * VALDIM);
|
|
1637
|
-
|
|
1638
|
-
[
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
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
|
+
}
|
|
1655
1749
|
const z = actBuf(S * VALDIM);
|
|
1656
1750
|
fusedMM(pass, w("linear.z"), n1, S, [
|
|
1657
1751
|
z,
|
|
@@ -2038,9 +2132,10 @@ async function createEngineInner(options, holder) {
|
|
|
2038
2132
|
const vocab = W.lm_head.N;
|
|
2039
2133
|
const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
|
|
2040
2134
|
transients = [];
|
|
2135
|
+
const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
|
|
2041
2136
|
try {
|
|
2042
|
-
for (let off = 0; off < S; off +=
|
|
2043
|
-
const seg = ids.slice(off, off +
|
|
2137
|
+
for (let off = 0; off < S; off += prefillSeg) {
|
|
2138
|
+
const seg = ids.slice(off, off + prefillSeg);
|
|
2044
2139
|
const enc = device.createCommandEncoder();
|
|
2045
2140
|
const embedOut = embedBatch(enc, seg);
|
|
2046
2141
|
const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off);
|
|
@@ -2076,18 +2171,19 @@ async function createEngineInner(options, holder) {
|
|
|
2076
2171
|
async function runPrefill(ids, posBase, signal) {
|
|
2077
2172
|
let fn = null;
|
|
2078
2173
|
let lastRow = 0;
|
|
2079
|
-
|
|
2174
|
+
const prefillSeg = (globalThis.__SEG ?? 0) || PREFILL_SEG_HY;
|
|
2175
|
+
for (let off = 0; off < ids.length; off += prefillSeg) {
|
|
2080
2176
|
if (off > 0 && signal?.aborted) {
|
|
2081
2177
|
fullHistory = [];
|
|
2082
2178
|
cacheLen = 0;
|
|
2083
2179
|
return null;
|
|
2084
2180
|
}
|
|
2085
|
-
const seg = ids.slice(off, off +
|
|
2181
|
+
const seg = ids.slice(off, off + prefillSeg);
|
|
2086
2182
|
const enc = device.createCommandEncoder();
|
|
2087
2183
|
fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
|
|
2088
2184
|
lastRow = seg.length - 1;
|
|
2089
2185
|
device.queue.submit([enc.finish()]);
|
|
2090
|
-
if (off +
|
|
2186
|
+
if (off + prefillSeg < ids.length) {
|
|
2091
2187
|
await device.queue.onSubmittedWorkDone();
|
|
2092
2188
|
flushTransients();
|
|
2093
2189
|
}
|
|
@@ -2265,7 +2361,17 @@ async function createEngineInner(options, holder) {
|
|
|
2265
2361
|
const KT = Math.max(K, lpN);
|
|
2266
2362
|
const temperature = genOpts.temperature ?? 1;
|
|
2267
2363
|
const penalty = genOpts.repetitionPenalty ?? 1;
|
|
2364
|
+
const presence = genOpts.presencePenalty ?? 0;
|
|
2365
|
+
const topP = genOpts.topP ?? 1;
|
|
2366
|
+
const minP = genOpts.minP ?? 0;
|
|
2268
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;
|
|
2269
2375
|
const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
|
|
2270
2376
|
const onToken = genOpts.onToken;
|
|
2271
2377
|
const signal = genOpts.signal;
|
|
@@ -2307,7 +2413,7 @@ async function createEngineInner(options, holder) {
|
|
|
2307
2413
|
usage: S_ | CS | CD
|
|
2308
2414
|
});
|
|
2309
2415
|
const writeAffBan = (history) => {
|
|
2310
|
-
const aff = penalty !== 1 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
|
|
2416
|
+
const aff = penalty !== 1 || presence !== 0 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
|
|
2311
2417
|
if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
|
|
2312
2418
|
const ban = ngramN > 0 ? ngramBans(history, ngramN) : [];
|
|
2313
2419
|
if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
|
|
@@ -2321,7 +2427,8 @@ async function createEngineInner(options, holder) {
|
|
|
2321
2427
|
["u", affLen],
|
|
2322
2428
|
["u", banLen],
|
|
2323
2429
|
["f", penalty],
|
|
2324
|
-
["u", 4286578688]
|
|
2430
|
+
["u", 4286578688],
|
|
2431
|
+
["f", presence]
|
|
2325
2432
|
], [affBuf, banBuf], [lg]);
|
|
2326
2433
|
pass.dispatchWorkgroups(1);
|
|
2327
2434
|
if (lpN) {
|
|
@@ -2378,7 +2485,13 @@ async function createEngineInner(options, holder) {
|
|
|
2378
2485
|
const pick = (ciAll, cvAll) => {
|
|
2379
2486
|
const ci = ciAll.subarray(0, K);
|
|
2380
2487
|
const cv = cvAll.subarray(0, K);
|
|
2381
|
-
|
|
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];
|
|
2382
2495
|
chosenLogit = cv[ci.indexOf(tk)];
|
|
2383
2496
|
return tk;
|
|
2384
2497
|
};
|
|
@@ -2395,7 +2508,13 @@ async function createEngineInner(options, holder) {
|
|
|
2395
2508
|
pIds.push(ci[i]);
|
|
2396
2509
|
pVals.push(cv[i]);
|
|
2397
2510
|
}
|
|
2398
|
-
|
|
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];
|
|
2399
2518
|
chosenLogit = pVals[pIds.indexOf(tk)];
|
|
2400
2519
|
return tk;
|
|
2401
2520
|
}
|
|
@@ -2416,7 +2535,13 @@ async function createEngineInner(options, holder) {
|
|
|
2416
2535
|
}
|
|
2417
2536
|
}
|
|
2418
2537
|
if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
|
|
2419
|
-
|
|
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];
|
|
2420
2545
|
chosenLogit = pVals[pIds.indexOf(tk)];
|
|
2421
2546
|
return tk;
|
|
2422
2547
|
};
|
|
@@ -2552,6 +2677,9 @@ async function createEngineInner(options, holder) {
|
|
|
2552
2677
|
const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
|
|
2553
2678
|
const temperature = genOpts.temperature ?? 1;
|
|
2554
2679
|
const penalty = genOpts.repetitionPenalty ?? 1;
|
|
2680
|
+
const presence = genOpts.presencePenalty ?? 0;
|
|
2681
|
+
const topP = genOpts.topP ?? 1;
|
|
2682
|
+
const minP = genOpts.minP ?? 0;
|
|
2555
2683
|
const ngramN = genOpts.noRepeatNgramSize ?? 0;
|
|
2556
2684
|
const pl = typeof genOpts.promptLookup === "object" && genOpts.promptLookup !== null ? genOpts.promptLookup : {};
|
|
2557
2685
|
const ngramSize = Math.max(2, pl.ngramSize ?? 3);
|
|
@@ -2560,7 +2688,7 @@ async function createEngineInner(options, holder) {
|
|
|
2560
2688
|
const onToken = genOpts.onToken;
|
|
2561
2689
|
const signal = genOpts.signal;
|
|
2562
2690
|
const rng = rngIn ?? new MT19937(genOpts.seed);
|
|
2563
|
-
const useChain = sampled || penalty !== 1 || ngramN > 0;
|
|
2691
|
+
const useChain = sampled || penalty !== 1 || presence !== 0 || ngramN > 0;
|
|
2564
2692
|
const lg = device.createBuffer({
|
|
2565
2693
|
size: vocab * 4,
|
|
2566
2694
|
usage: S_ | CS | CD
|
|
@@ -2602,7 +2730,7 @@ async function createEngineInner(options, holder) {
|
|
|
2602
2730
|
usage: S_ | CD
|
|
2603
2731
|
});
|
|
2604
2732
|
const writeAffBan = (h) => {
|
|
2605
|
-
const aff = penalty !== 1 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
|
|
2733
|
+
const aff = penalty !== 1 || presence !== 0 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
|
|
2606
2734
|
if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
|
|
2607
2735
|
const ban = ngramN > 0 ? ngramBans(h, ngramN) : [];
|
|
2608
2736
|
if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
|
|
@@ -2616,7 +2744,8 @@ async function createEngineInner(options, holder) {
|
|
|
2616
2744
|
["u", affLen],
|
|
2617
2745
|
["u", banLen],
|
|
2618
2746
|
["f", penalty],
|
|
2619
|
-
["u", 4286578688]
|
|
2747
|
+
["u", 4286578688],
|
|
2748
|
+
["f", presence]
|
|
2620
2749
|
], [affBuf, banBuf], [lg]);
|
|
2621
2750
|
pass.dispatchWorkgroups(1);
|
|
2622
2751
|
for (let r = 0; r < K; r++) {
|
|
@@ -2629,7 +2758,7 @@ async function createEngineInner(options, holder) {
|
|
|
2629
2758
|
pass.dispatchWorkgroups(1);
|
|
2630
2759
|
}
|
|
2631
2760
|
};
|
|
2632
|
-
const rowDraw = (m, j) => sampled ? sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng) : new Uint32Array(m, j * K * 8, 1)[0];
|
|
2761
|
+
const rowDraw = (m, j) => sampled ? sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng, topP, minP) : new Uint32Array(m, j * K * 8, 1)[0];
|
|
2633
2762
|
transients = [];
|
|
2634
2763
|
try {
|
|
2635
2764
|
const t0 = performance.now();
|
|
@@ -2881,6 +3010,7 @@ async function createEngineInner(options, holder) {
|
|
|
2881
3010
|
const vocab = W.lm_head.N;
|
|
2882
3011
|
const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
|
|
2883
3012
|
const penalty = genOpts.repetitionPenalty ?? 1;
|
|
3013
|
+
const presence = genOpts.presencePenalty ?? 0;
|
|
2884
3014
|
const ngramN = genOpts.noRepeatNgramSize ?? 0;
|
|
2885
3015
|
const lg = device.createBuffer({
|
|
2886
3016
|
size: vocab * 4,
|
|
@@ -2894,7 +3024,7 @@ async function createEngineInner(options, holder) {
|
|
|
2894
3024
|
size: K * 4,
|
|
2895
3025
|
usage: S_ | CS
|
|
2896
3026
|
});
|
|
2897
|
-
const aff = penalty !== 1 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
|
|
3027
|
+
const aff = penalty !== 1 || presence !== 0 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
|
|
2898
3028
|
const ban = ngramN > 0 ? ngramBans(ids, ngramN) : [];
|
|
2899
3029
|
const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
|
|
2900
3030
|
const banBuf = upload(ban.length ? Uint32Array.from(ban) : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
|
|
@@ -2917,7 +3047,8 @@ async function createEngineInner(options, holder) {
|
|
|
2917
3047
|
["u", aff.length],
|
|
2918
3048
|
["u", ban.length],
|
|
2919
3049
|
["f", penalty],
|
|
2920
|
-
["u", 4286578688]
|
|
3050
|
+
["u", 4286578688],
|
|
3051
|
+
["f", presence]
|
|
2921
3052
|
], [affBuf, banBuf], [lg]);
|
|
2922
3053
|
pass.dispatchWorkgroups(1);
|
|
2923
3054
|
for (let r = 0; r < K; r++) {
|
|
@@ -2960,7 +3091,8 @@ async function createEngineInner(options, holder) {
|
|
|
2960
3091
|
};
|
|
2961
3092
|
async function generate(promptTokenIds, genOpts = {}) {
|
|
2962
3093
|
const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
|
|
2963
|
-
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)");
|
|
2964
3096
|
const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
|
|
2965
3097
|
if (genOpts.signal?.aborted) return {
|
|
2966
3098
|
tokens: [],
|
|
@@ -3013,7 +3145,7 @@ async function createEngineInner(options, holder) {
|
|
|
3013
3145
|
}
|
|
3014
3146
|
const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
|
|
3015
3147
|
let r;
|
|
3016
|
-
if (!hasFilter && genOpts.promptLookup === "auto" && maxTokens > 24) {
|
|
3148
|
+
if (!hasFilter && (genOpts.dryMultiplier ?? 0) === 0 && genOpts.promptLookup === "auto" && maxTokens > 24) {
|
|
3017
3149
|
const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
|
|
3018
3150
|
const E = r1.tokens.length;
|
|
3019
3151
|
if (E < 24) r = r1;
|
|
@@ -3055,7 +3187,7 @@ async function createEngineInner(options, holder) {
|
|
|
3055
3187
|
}
|
|
3056
3188
|
};
|
|
3057
3189
|
}
|
|
3058
|
-
} 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);
|
|
3059
3191
|
else if (sampled || hasProcessors || hasFilter) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
|
|
3060
3192
|
else {
|
|
3061
3193
|
const hist = fullHistory;
|