bitgpu 0.15.0 → 0.17.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-Wg8VrdrL.js";
1
+ import { u as Manifest } from "./types-BkfIJ42d.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-Wg8VrdrL.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-BkfIJ42d.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
@@ -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\n// on the full vocab logit buffer, so only a tiny top-K candidate set has to be read back (not all\n// ~151k logits). Matches transformers.js exactly: rep_penalty over the DEDUPED prompt+generated id\n// set (logit<0 ? *penalty : /penalty), then ngram-banned next-tokens set to -Infinity. Both id lists\n// are computed on the CPU each step (exact, since at syncN=1 the full history is known) and uploaded.\n// Temperature is NOT applied here: top-k is invariant under the monotonic divide, so temperature is\n// applied on the CPU to just the K candidate values before softmax (bit-identical, one less pass).\n// Single workgroup, no subgroup ops -> all devices. The storageBarrier guarantees every penalty\n// write lands before any ban write, so a token that is both repeated and ngram-banned ends at -inf\n// (ban wins, matching the reference order rep_penalty -> 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 };\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 if (v < 0.0) { logits[t] = v * p.penalty; } else { logits[t] = v / p.penalty; }\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",
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"
@@ -201,21 +201,44 @@ function softmax(arr) {
201
201
  return exps.map((x) => x / sum);
202
202
  }
203
203
  /** Final sampling tail. `candVals` are the K largest PENALTY-FILTERED logits (descending), `candIds`
204
- * their token ids. Applies temperature to the K values, softmaxes, then draws via the exact
205
- * transformers.js inverse-CDF weighted pick (x = random()*sum; subtract until <0). Returns a token id. */
206
- function sampleFromCandidates(candIds, candVals, temperature, rng) {
204
+ * their token ids. Applies temperature to the K values, softmaxes, optionally trims the pool with
205
+ * top-p (nucleus) and/or min-p, then draws via the exact transformers.js inverse-CDF weighted pick
206
+ * (x = random()*sum; subtract until <0). `topP` (default 1 = off) keeps the shortest leading run
207
+ * whose cumulative probability reaches topP; `minP` (default 0 = off) keeps tokens with probability
208
+ * >= minP*maxProb - both operate on the already-descending candidates, so each keeps a prefix and
209
+ * the kept set is their shorter prefix. With both off the draw is bit-identical to the plain path
210
+ * (m == k, sum over all K). Returns a token id. */
211
+ function sampleFromCandidates(candIds, candVals, temperature, rng, topP = 1, minP = 0) {
207
212
  const k = candVals.length;
208
213
  const tv = new Float32Array(k);
209
214
  for (let i = 0; i < k; ++i) tv[i] = candVals[i] / temperature;
210
215
  const probs = softmax(tv);
216
+ let m = k;
217
+ if (minP > 0) {
218
+ const thresh = minP * probs[0];
219
+ let c = 1;
220
+ while (c < k && probs[c] >= thresh) c++;
221
+ if (c < m) m = c;
222
+ }
223
+ if (topP < 1) {
224
+ let cum = 0;
225
+ let c = 0;
226
+ while (c < k) {
227
+ cum += probs[c];
228
+ c++;
229
+ if (cum >= topP) break;
230
+ }
231
+ if (c < m) m = c;
232
+ }
233
+ if (m < 1) m = 1;
211
234
  let sum = 0;
212
- for (const pr of probs) sum += pr;
235
+ for (let i = 0; i < m; ++i) sum += probs[i];
213
236
  let x = rng.random() * sum;
214
- for (let i = 0; i < k; ++i) {
237
+ for (let i = 0; i < m; ++i) {
215
238
  x -= probs[i];
216
239
  if (x < 0) return candIds[i];
217
240
  }
218
- return candIds[k - 1];
241
+ return candIds[m - 1];
219
242
  }
220
243
  //#endregion
221
244
  //#region src/engine.ts
@@ -234,6 +257,7 @@ const WGSLS = [
234
257
  ];
235
258
  const DEFAULT_MAX_SEQ = 2048;
236
259
  const PREFILL_SEG = 256;
260
+ const PREFILL_SEG_HYBRID = 16;
237
261
  const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
238
262
  const PARAM_DV = new DataView(PARAM_AB);
239
263
  const PARAM_U8 = new Uint8Array(PARAM_AB);
@@ -1299,7 +1323,8 @@ async function createEngineInner(options, holder) {
1299
1323
  usage: U | CD
1300
1324
  }),
1301
1325
  bg: null,
1302
- last: null
1326
+ last: null,
1327
+ bufs: null
1303
1328
  };
1304
1329
  pool.disp[dispIdx] = slot;
1305
1330
  }
@@ -1308,6 +1333,22 @@ async function createEngineInner(options, holder) {
1308
1333
  device.queue.writeBuffer(slot.uni, 0, data2);
1309
1334
  slot.last = data2.slice();
1310
1335
  }
1336
+ if (slot.bg && slot.bufs) {
1337
+ const nb = ins.length + outs.length;
1338
+ if (slot.bufs.length !== nb) slot.bg = null;
1339
+ else {
1340
+ for (let i = 0; i < ins.length; i++) if (slot.bufs[i] !== ins[i]) {
1341
+ slot.bg = null;
1342
+ break;
1343
+ }
1344
+ if (slot.bg) {
1345
+ for (let i = 0; i < outs.length; i++) if (slot.bufs[ins.length + i] !== outs[i]) {
1346
+ slot.bg = null;
1347
+ break;
1348
+ }
1349
+ }
1350
+ }
1351
+ }
1311
1352
  if (!slot.bg) {
1312
1353
  const entries = [{
1313
1354
  binding: 0,
@@ -1325,6 +1366,7 @@ async function createEngineInner(options, holder) {
1325
1366
  layout: pipelines[name].getBindGroupLayout(0),
1326
1367
  entries
1327
1368
  });
1369
+ slot.bufs = [...ins, ...outs];
1328
1370
  }
1329
1371
  pass.setBindGroup(0, slot.bg);
1330
1372
  dispIdx++;
@@ -1383,11 +1425,11 @@ async function createEngineInner(options, holder) {
1383
1425
  ["f", A.rms_eps],
1384
1426
  ["u", 0]
1385
1427
  ], [x, W[g].buf], out, R);
1386
- function fusedMM(pass, w, inBuf, S, outs) {
1428
+ function fusedMM(pass, w, inBuf, S, outs, af = false) {
1387
1429
  const Ntot = w.N0 + w.N1 + w.N2;
1388
1430
  if (useSG && S === 1) {
1389
1431
  const gx = Math.min(Ntot, 65535);
1390
- runWG(pass, "matmul_split_sg", [
1432
+ runWG(pass, af ? "matmul_split_sg_af16" : "matmul_split_sg", [
1391
1433
  ["u", w.K],
1392
1434
  ["u", w.nb],
1393
1435
  ["u", w.N0],
@@ -1564,8 +1606,9 @@ async function createEngineInner(options, holder) {
1564
1606
  const w = (r) => W[`layers.${li}.${r}`];
1565
1607
  const ls = posBase > 0 ? 1 : 0;
1566
1608
  const par = hyPar;
1567
- const n1 = actBuf(S * Hd);
1568
- rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1);
1609
+ const af = actF16 && S === 1 && !FORCE_SLOW;
1610
+ const n1 = af ? actBuf16(S * Hd) : actBuf(S * Hd);
1611
+ rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1, af);
1569
1612
  let h2;
1570
1613
  if (hy.layer_types[li] === "linear") {
1571
1614
  const mixed = actBuf(S * CONVDIM);
@@ -1573,7 +1616,7 @@ async function createEngineInner(options, holder) {
1573
1616
  mixed,
1574
1617
  dummy,
1575
1618
  dummy2
1576
- ]);
1619
+ ], af);
1577
1620
  const convd = actBuf(S * CONVDIM);
1578
1621
  const cvSt = (CONVK - 1) * CONVDIM;
1579
1622
  setup(pass, "conv1d_causal", [
@@ -1614,12 +1657,12 @@ async function createEngineInner(options, holder) {
1614
1657
  a,
1615
1658
  dummy,
1616
1659
  dummy2
1617
- ]);
1660
+ ], af);
1618
1661
  fusedMM(pass, w("linear.b"), n1, S, [
1619
1662
  b,
1620
1663
  dummy,
1621
1664
  dummy2
1622
- ]);
1665
+ ], af);
1623
1666
  const gb = actBuf(2 * S * NV);
1624
1667
  run(pass, "deltanet_gbeta", [
1625
1668
  ["u", S],
@@ -1656,7 +1699,7 @@ async function createEngineInner(options, holder) {
1656
1699
  z,
1657
1700
  dummy,
1658
1701
  dummy2
1659
- ]);
1702
+ ], af);
1660
1703
  const normed = actBuf(S * VALDIM);
1661
1704
  runN(pass, "deltanet_norm_gate", [
1662
1705
  ["u", S * NV],
@@ -1676,7 +1719,7 @@ async function createEngineInner(options, holder) {
1676
1719
  qg,
1677
1720
  dummy,
1678
1721
  dummy2
1679
- ]);
1722
+ ], af);
1680
1723
  const query = actBuf(S * H * Dh), gate = actBuf(S * H * Dh);
1681
1724
  run(pass, "split_head", [
1682
1725
  ["u", S],
@@ -1707,7 +1750,7 @@ async function createEngineInner(options, holder) {
1707
1750
  kk,
1708
1751
  dummy,
1709
1752
  dummy2
1710
- ]);
1753
+ ], af);
1711
1754
  const kn = actBuf(S * KV * Dh), kr = actBuf(S * KV * Dh);
1712
1755
  rms(pass, kk, `layers.${li}.attn.k_norm`, S * KV, Dh, kn);
1713
1756
  run(pass, "rope_partial", [
@@ -1725,7 +1768,7 @@ async function createEngineInner(options, holder) {
1725
1768
  vv,
1726
1769
  dummy,
1727
1770
  dummy2
1728
- ]);
1771
+ ], af);
1729
1772
  appendKV(pass, kr, 0, li, S * KV, posBase * KV);
1730
1773
  appendKV(pass, vv, 1, li, S * KV, posBase * KV);
1731
1774
  const att = actBuf(S * H * Dh);
@@ -1761,19 +1804,19 @@ async function createEngineInner(options, holder) {
1761
1804
  h2 = actBuf(S * Hd);
1762
1805
  residMM(pass, w("attn.o_proj"), gated, h, S, h2);
1763
1806
  }
1764
- const n2 = actBuf(S * Hd);
1765
- rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2);
1807
+ const n2 = af ? actBuf16(S * Hd) : actBuf(S * Hd);
1808
+ rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2, af);
1766
1809
  const g = actBuf(S * F), u = actBuf(S * F);
1767
1810
  fusedMM(pass, w("mlp.gate_proj"), n2, S, [
1768
1811
  g,
1769
1812
  dummy,
1770
1813
  dummy2
1771
- ]);
1814
+ ], af);
1772
1815
  fusedMM(pass, w("mlp.up_proj"), n2, S, [
1773
1816
  u,
1774
1817
  dummy,
1775
1818
  dummy2
1776
- ]);
1819
+ ], af);
1777
1820
  const sw = actBuf(S * F);
1778
1821
  run(pass, "swiglu", [
1779
1822
  ["u", S * F],
@@ -2037,9 +2080,10 @@ async function createEngineInner(options, holder) {
2037
2080
  const vocab = W.lm_head.N;
2038
2081
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
2039
2082
  transients = [];
2083
+ const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2040
2084
  try {
2041
- for (let off = 0; off < S; off += PREFILL_SEG) {
2042
- const seg = ids.slice(off, off + PREFILL_SEG);
2085
+ for (let off = 0; off < S; off += prefillSeg) {
2086
+ const seg = ids.slice(off, off + prefillSeg);
2043
2087
  const enc = device.createCommandEncoder();
2044
2088
  const embedOut = embedBatch(enc, seg);
2045
2089
  const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off);
@@ -2075,18 +2119,19 @@ async function createEngineInner(options, holder) {
2075
2119
  async function runPrefill(ids, posBase, signal) {
2076
2120
  let fn = null;
2077
2121
  let lastRow = 0;
2078
- for (let off = 0; off < ids.length; off += PREFILL_SEG) {
2122
+ const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2123
+ for (let off = 0; off < ids.length; off += prefillSeg) {
2079
2124
  if (off > 0 && signal?.aborted) {
2080
2125
  fullHistory = [];
2081
2126
  cacheLen = 0;
2082
2127
  return null;
2083
2128
  }
2084
- const seg = ids.slice(off, off + PREFILL_SEG);
2129
+ const seg = ids.slice(off, off + prefillSeg);
2085
2130
  const enc = device.createCommandEncoder();
2086
2131
  fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
2087
2132
  lastRow = seg.length - 1;
2088
2133
  device.queue.submit([enc.finish()]);
2089
- if (off + PREFILL_SEG < ids.length) {
2134
+ if (off + prefillSeg < ids.length) {
2090
2135
  await device.queue.onSubmittedWorkDone();
2091
2136
  flushTransients();
2092
2137
  }
@@ -2264,6 +2309,9 @@ async function createEngineInner(options, holder) {
2264
2309
  const KT = Math.max(K, lpN);
2265
2310
  const temperature = genOpts.temperature ?? 1;
2266
2311
  const penalty = genOpts.repetitionPenalty ?? 1;
2312
+ const presence = genOpts.presencePenalty ?? 0;
2313
+ const topP = genOpts.topP ?? 1;
2314
+ const minP = genOpts.minP ?? 0;
2267
2315
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2268
2316
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2269
2317
  const onToken = genOpts.onToken;
@@ -2306,7 +2354,7 @@ async function createEngineInner(options, holder) {
2306
2354
  usage: S_ | CS | CD
2307
2355
  });
2308
2356
  const writeAffBan = (history) => {
2309
- const aff = penalty !== 1 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
2357
+ const aff = penalty !== 1 || presence !== 0 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
2310
2358
  if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2311
2359
  const ban = ngramN > 0 ? ngramBans(history, ngramN) : [];
2312
2360
  if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
@@ -2320,7 +2368,8 @@ async function createEngineInner(options, holder) {
2320
2368
  ["u", affLen],
2321
2369
  ["u", banLen],
2322
2370
  ["f", penalty],
2323
- ["u", 4286578688]
2371
+ ["u", 4286578688],
2372
+ ["f", presence]
2324
2373
  ], [affBuf, banBuf], [lg]);
2325
2374
  pass.dispatchWorkgroups(1);
2326
2375
  if (lpN) {
@@ -2377,7 +2426,7 @@ async function createEngineInner(options, holder) {
2377
2426
  const pick = (ciAll, cvAll) => {
2378
2427
  const ci = ciAll.subarray(0, K);
2379
2428
  const cv = cvAll.subarray(0, K);
2380
- const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
2429
+ const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng, topP, minP) : ci[0];
2381
2430
  chosenLogit = cv[ci.indexOf(tk)];
2382
2431
  return tk;
2383
2432
  };
@@ -2394,7 +2443,7 @@ async function createEngineInner(options, holder) {
2394
2443
  pIds.push(ci[i]);
2395
2444
  pVals.push(cv[i]);
2396
2445
  }
2397
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
2446
+ const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2398
2447
  chosenLogit = pVals[pIds.indexOf(tk)];
2399
2448
  return tk;
2400
2449
  }
@@ -2415,7 +2464,7 @@ async function createEngineInner(options, holder) {
2415
2464
  }
2416
2465
  }
2417
2466
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
2418
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
2467
+ const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2419
2468
  chosenLogit = pVals[pIds.indexOf(tk)];
2420
2469
  return tk;
2421
2470
  };
@@ -2551,6 +2600,9 @@ async function createEngineInner(options, holder) {
2551
2600
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
2552
2601
  const temperature = genOpts.temperature ?? 1;
2553
2602
  const penalty = genOpts.repetitionPenalty ?? 1;
2603
+ const presence = genOpts.presencePenalty ?? 0;
2604
+ const topP = genOpts.topP ?? 1;
2605
+ const minP = genOpts.minP ?? 0;
2554
2606
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2555
2607
  const pl = typeof genOpts.promptLookup === "object" && genOpts.promptLookup !== null ? genOpts.promptLookup : {};
2556
2608
  const ngramSize = Math.max(2, pl.ngramSize ?? 3);
@@ -2559,7 +2611,7 @@ async function createEngineInner(options, holder) {
2559
2611
  const onToken = genOpts.onToken;
2560
2612
  const signal = genOpts.signal;
2561
2613
  const rng = rngIn ?? new MT19937(genOpts.seed);
2562
- const useChain = sampled || penalty !== 1 || ngramN > 0;
2614
+ const useChain = sampled || penalty !== 1 || presence !== 0 || ngramN > 0;
2563
2615
  const lg = device.createBuffer({
2564
2616
  size: vocab * 4,
2565
2617
  usage: S_ | CS | CD
@@ -2601,7 +2653,7 @@ async function createEngineInner(options, holder) {
2601
2653
  usage: S_ | CD
2602
2654
  });
2603
2655
  const writeAffBan = (h) => {
2604
- const aff = penalty !== 1 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
2656
+ const aff = penalty !== 1 || presence !== 0 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
2605
2657
  if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2606
2658
  const ban = ngramN > 0 ? ngramBans(h, ngramN) : [];
2607
2659
  if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
@@ -2615,7 +2667,8 @@ async function createEngineInner(options, holder) {
2615
2667
  ["u", affLen],
2616
2668
  ["u", banLen],
2617
2669
  ["f", penalty],
2618
- ["u", 4286578688]
2670
+ ["u", 4286578688],
2671
+ ["f", presence]
2619
2672
  ], [affBuf, banBuf], [lg]);
2620
2673
  pass.dispatchWorkgroups(1);
2621
2674
  for (let r = 0; r < K; r++) {
@@ -2628,7 +2681,7 @@ async function createEngineInner(options, holder) {
2628
2681
  pass.dispatchWorkgroups(1);
2629
2682
  }
2630
2683
  };
2631
- 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];
2684
+ 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];
2632
2685
  transients = [];
2633
2686
  try {
2634
2687
  const t0 = performance.now();
@@ -2880,6 +2933,7 @@ async function createEngineInner(options, holder) {
2880
2933
  const vocab = W.lm_head.N;
2881
2934
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
2882
2935
  const penalty = genOpts.repetitionPenalty ?? 1;
2936
+ const presence = genOpts.presencePenalty ?? 0;
2883
2937
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2884
2938
  const lg = device.createBuffer({
2885
2939
  size: vocab * 4,
@@ -2893,7 +2947,7 @@ async function createEngineInner(options, holder) {
2893
2947
  size: K * 4,
2894
2948
  usage: S_ | CS
2895
2949
  });
2896
- const aff = penalty !== 1 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
2950
+ const aff = penalty !== 1 || presence !== 0 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
2897
2951
  const ban = ngramN > 0 ? ngramBans(ids, ngramN) : [];
2898
2952
  const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
2899
2953
  const banBuf = upload(ban.length ? Uint32Array.from(ban) : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
@@ -2916,7 +2970,8 @@ async function createEngineInner(options, holder) {
2916
2970
  ["u", aff.length],
2917
2971
  ["u", ban.length],
2918
2972
  ["f", penalty],
2919
- ["u", 4286578688]
2973
+ ["u", 4286578688],
2974
+ ["f", presence]
2920
2975
  ], [affBuf, banBuf], [lg]);
2921
2976
  pass.dispatchWorkgroups(1);
2922
2977
  for (let r = 0; r < K; r++) {