bitgpu 0.16.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++;
@@ -2038,9 +2080,10 @@ async function createEngineInner(options, holder) {
2038
2080
  const vocab = W.lm_head.N;
2039
2081
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
2040
2082
  transients = [];
2083
+ const prefillSeg = A.hybrid ? PREFILL_SEG_HYBRID : PREFILL_SEG;
2041
2084
  try {
2042
- for (let off = 0; off < S; off += PREFILL_SEG) {
2043
- 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);
2044
2087
  const enc = device.createCommandEncoder();
2045
2088
  const embedOut = embedBatch(enc, seg);
2046
2089
  const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off);
@@ -2076,18 +2119,19 @@ async function createEngineInner(options, holder) {
2076
2119
  async function runPrefill(ids, posBase, signal) {
2077
2120
  let fn = null;
2078
2121
  let lastRow = 0;
2079
- 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) {
2080
2124
  if (off > 0 && signal?.aborted) {
2081
2125
  fullHistory = [];
2082
2126
  cacheLen = 0;
2083
2127
  return null;
2084
2128
  }
2085
- const seg = ids.slice(off, off + PREFILL_SEG);
2129
+ const seg = ids.slice(off, off + prefillSeg);
2086
2130
  const enc = device.createCommandEncoder();
2087
2131
  fn = stack(enc, embedBatch(enc, seg), seg.length, posBase + off).fn;
2088
2132
  lastRow = seg.length - 1;
2089
2133
  device.queue.submit([enc.finish()]);
2090
- if (off + PREFILL_SEG < ids.length) {
2134
+ if (off + prefillSeg < ids.length) {
2091
2135
  await device.queue.onSubmittedWorkDone();
2092
2136
  flushTransients();
2093
2137
  }
@@ -2265,6 +2309,9 @@ async function createEngineInner(options, holder) {
2265
2309
  const KT = Math.max(K, lpN);
2266
2310
  const temperature = genOpts.temperature ?? 1;
2267
2311
  const penalty = genOpts.repetitionPenalty ?? 1;
2312
+ const presence = genOpts.presencePenalty ?? 0;
2313
+ const topP = genOpts.topP ?? 1;
2314
+ const minP = genOpts.minP ?? 0;
2268
2315
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2269
2316
  const stopSet = genOpts.stopTokens ? new Set(genOpts.stopTokens) : null;
2270
2317
  const onToken = genOpts.onToken;
@@ -2307,7 +2354,7 @@ async function createEngineInner(options, holder) {
2307
2354
  usage: S_ | CS | CD
2308
2355
  });
2309
2356
  const writeAffBan = (history) => {
2310
- const aff = penalty !== 1 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
2357
+ const aff = penalty !== 1 || presence !== 0 ? affectedIds(history) : /* @__PURE__ */ new Uint32Array(0);
2311
2358
  if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2312
2359
  const ban = ngramN > 0 ? ngramBans(history, ngramN) : [];
2313
2360
  if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
@@ -2321,7 +2368,8 @@ async function createEngineInner(options, holder) {
2321
2368
  ["u", affLen],
2322
2369
  ["u", banLen],
2323
2370
  ["f", penalty],
2324
- ["u", 4286578688]
2371
+ ["u", 4286578688],
2372
+ ["f", presence]
2325
2373
  ], [affBuf, banBuf], [lg]);
2326
2374
  pass.dispatchWorkgroups(1);
2327
2375
  if (lpN) {
@@ -2378,7 +2426,7 @@ async function createEngineInner(options, holder) {
2378
2426
  const pick = (ciAll, cvAll) => {
2379
2427
  const ci = ciAll.subarray(0, K);
2380
2428
  const cv = cvAll.subarray(0, K);
2381
- const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
2429
+ const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng, topP, minP) : ci[0];
2382
2430
  chosenLogit = cv[ci.indexOf(tk)];
2383
2431
  return tk;
2384
2432
  };
@@ -2395,7 +2443,7 @@ async function createEngineInner(options, holder) {
2395
2443
  pIds.push(ci[i]);
2396
2444
  pVals.push(cv[i]);
2397
2445
  }
2398
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
2446
+ const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2399
2447
  chosenLogit = pVals[pIds.indexOf(tk)];
2400
2448
  return tk;
2401
2449
  }
@@ -2416,7 +2464,7 @@ async function createEngineInner(options, holder) {
2416
2464
  }
2417
2465
  }
2418
2466
  if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
2419
- const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
2467
+ const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng, topP, minP) : pIds[0];
2420
2468
  chosenLogit = pVals[pIds.indexOf(tk)];
2421
2469
  return tk;
2422
2470
  };
@@ -2552,6 +2600,9 @@ async function createEngineInner(options, holder) {
2552
2600
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
2553
2601
  const temperature = genOpts.temperature ?? 1;
2554
2602
  const penalty = genOpts.repetitionPenalty ?? 1;
2603
+ const presence = genOpts.presencePenalty ?? 0;
2604
+ const topP = genOpts.topP ?? 1;
2605
+ const minP = genOpts.minP ?? 0;
2555
2606
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2556
2607
  const pl = typeof genOpts.promptLookup === "object" && genOpts.promptLookup !== null ? genOpts.promptLookup : {};
2557
2608
  const ngramSize = Math.max(2, pl.ngramSize ?? 3);
@@ -2560,7 +2611,7 @@ async function createEngineInner(options, holder) {
2560
2611
  const onToken = genOpts.onToken;
2561
2612
  const signal = genOpts.signal;
2562
2613
  const rng = rngIn ?? new MT19937(genOpts.seed);
2563
- const useChain = sampled || penalty !== 1 || ngramN > 0;
2614
+ const useChain = sampled || penalty !== 1 || presence !== 0 || ngramN > 0;
2564
2615
  const lg = device.createBuffer({
2565
2616
  size: vocab * 4,
2566
2617
  usage: S_ | CS | CD
@@ -2602,7 +2653,7 @@ async function createEngineInner(options, holder) {
2602
2653
  usage: S_ | CD
2603
2654
  });
2604
2655
  const writeAffBan = (h) => {
2605
- const aff = penalty !== 1 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
2656
+ const aff = penalty !== 1 || presence !== 0 ? affectedIds(h) : /* @__PURE__ */ new Uint32Array(0);
2606
2657
  if (aff.length) device.queue.writeBuffer(affBuf, 0, aff);
2607
2658
  const ban = ngramN > 0 ? ngramBans(h, ngramN) : [];
2608
2659
  if (ban.length) device.queue.writeBuffer(banBuf, 0, Uint32Array.from(ban));
@@ -2616,7 +2667,8 @@ async function createEngineInner(options, holder) {
2616
2667
  ["u", affLen],
2617
2668
  ["u", banLen],
2618
2669
  ["f", penalty],
2619
- ["u", 4286578688]
2670
+ ["u", 4286578688],
2671
+ ["f", presence]
2620
2672
  ], [affBuf, banBuf], [lg]);
2621
2673
  pass.dispatchWorkgroups(1);
2622
2674
  for (let r = 0; r < K; r++) {
@@ -2629,7 +2681,7 @@ async function createEngineInner(options, holder) {
2629
2681
  pass.dispatchWorkgroups(1);
2630
2682
  }
2631
2683
  };
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];
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];
2633
2685
  transients = [];
2634
2686
  try {
2635
2687
  const t0 = performance.now();
@@ -2881,6 +2933,7 @@ async function createEngineInner(options, holder) {
2881
2933
  const vocab = W.lm_head.N;
2882
2934
  const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
2883
2935
  const penalty = genOpts.repetitionPenalty ?? 1;
2936
+ const presence = genOpts.presencePenalty ?? 0;
2884
2937
  const ngramN = genOpts.noRepeatNgramSize ?? 0;
2885
2938
  const lg = device.createBuffer({
2886
2939
  size: vocab * 4,
@@ -2894,7 +2947,7 @@ async function createEngineInner(options, holder) {
2894
2947
  size: K * 4,
2895
2948
  usage: S_ | CS
2896
2949
  });
2897
- const aff = penalty !== 1 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
2950
+ const aff = penalty !== 1 || presence !== 0 ? affectedIds(ids) : /* @__PURE__ */ new Uint32Array(0);
2898
2951
  const ban = ngramN > 0 ? ngramBans(ids, ngramN) : [];
2899
2952
  const affBuf = upload(aff.length ? aff : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
2900
2953
  const banBuf = upload(ban.length ? Uint32Array.from(ban) : /* @__PURE__ */ new Uint32Array(1), S_ | CD);
@@ -2917,7 +2970,8 @@ async function createEngineInner(options, holder) {
2917
2970
  ["u", aff.length],
2918
2971
  ["u", ban.length],
2919
2972
  ["f", penalty],
2920
- ["u", 4286578688]
2973
+ ["u", 4286578688],
2974
+ ["f", presence]
2921
2975
  ], [affBuf, banBuf], [lg]);
2922
2976
  pass.dispatchWorkgroups(1);
2923
2977
  for (let r = 0; r < K; r++) {