bitgpu 0.7.0 → 0.9.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 +97 -9
- package/THIRD_PARTY_LICENSES.md +2 -2
- package/dist/chat.d.ts +261 -33
- package/dist/chat.js +821 -74
- package/dist/chat.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +75 -21
- package/dist/index.js.map +1 -1
- package/dist/{types-CsoJYJlG.d.ts → types-C5f2IKgm.d.ts} +25 -2
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as ForwardResult, c as LoadProgress, i as EngineOptions, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo } from "./types-
|
|
1
|
+
import { a as ForwardResult, c as LoadProgress, i as EngineOptions, l as TokenLogprobs, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo } from "./types-C5f2IKgm.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. */
|
|
@@ -20,5 +20,5 @@ declare class GpuOutOfMemoryError extends Error {
|
|
|
20
20
|
constructor(message: string);
|
|
21
21
|
}
|
|
22
22
|
//#endregion
|
|
23
|
-
export { type DeviceLostInfo, type Engine, type EngineCapabilities, type EngineOptions, type ForwardResult, type GenerateOptions, type GenerateResult, GpuOutOfMemoryError, type LoadProgress, WebGPUUnavailableError, createEngine };
|
|
23
|
+
export { type DeviceLostInfo, type Engine, type EngineCapabilities, type EngineOptions, type ForwardResult, type GenerateOptions, type GenerateResult, GpuOutOfMemoryError, type LoadProgress, type TokenLogprobs, WebGPUUnavailableError, createEngine };
|
|
24
24
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -11,6 +11,7 @@ const SHADERS = {
|
|
|
11
11
|
"copy_kv16": "// copy with an f16-STORAGE destination (kvCache: 'f16'): appends f32 K/V rows into the f16\n// cache (one f32 -> f16 rounding per value). Keep in lockstep with copy.wgsl.\nenable f16;\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f16>;\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 dst[p.dstOff + i] = f16(src[i]);\n}\n",
|
|
12
12
|
"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",
|
|
13
13
|
"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",
|
|
14
|
+
"logsumexp": "// log-sum-exp over the (penalty-filtered) logits, the softmax normalizer that turns a raw logit\n// into a true logprob on the CPU: logprob(id) = logit[id] - lse. Runs AFTER sampler_penalty and\n// BEFORE the argmax_masked rounds (those mask their winners in place, which would corrupt the\n// sum). Two-phase single-workgroup reduction: strided max, then strided sum of exp(x - max);\n// entries at the -inf sentinel (banned ids) contribute nothing. Only one f32 is read back.\noverride WG: u32 = 256u;\nstruct Params { N: u32, _0: u32, _1: u32, _2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> outLse: array<f32>; // outLse[0] = max + log(sum)\n\nconst NEG_SENTINEL: f32 = -3.0e38; // below any real logit; banned entries sit at f32 -inf\n\nvar<workgroup> sval: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var m = -3.4e38;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL && v > m) { m = v; }\n }\n sval[tid] = m;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s && sval[tid + s] > sval[tid]) { sval[tid] = sval[tid + s]; }\n workgroupBarrier();\n }\n let gmax = sval[0];\n workgroupBarrier();\n var acc = 0.0;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL) { acc = acc + exp(v - gmax); }\n }\n sval[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sval[tid] = sval[tid] + sval[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) { outLse[0] = gmax + log(sval[0]); }\n}\n",
|
|
14
15
|
"matmul_binary_vec4": "// Binary matmul, vectorized: y[M,N] = x[M,K] @ W[N,K]^T, W = (+/-1) * per-block scale.\n// One thread per output; the K loop processes a 32-bit sign word at a time and the\n// activations as vec4 via dot() (4 weights per FMA instead of 1 scalar op). M-agnostic\n// (works for prefill M=S and decode M=1). x is bound as vec4 (K must be a multiple of 4).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\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.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xRow = m * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let wordsPerBlock = p.block / 32u; // 4 for block=128\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n for (var w = 0u; w < wordsPerBlock; w = w + 1u) {\n let word = signbits[wRow + b * wordsPerBlock + w];\n let xb = xRow + b * (p.block / 4u) + w * 8u; // vec4 base for this word (32 weights = 8 vec4)\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(\n select(-1.0, 1.0, (bits4 & 1u) != 0u),\n select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u),\n select(-1.0, 1.0, (bits4 & 8u) != 0u),\n );\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
|
|
15
16
|
"matmul_q2": "// 2-bit dequant matmul (lm_head): y[M,N] = x[M,K] @ W[N,K]^T, W[n,k] = (code - zp) * scale[n, k/block].\n// codes are 2-bit, 4 per byte, packed into u32 words. Correctness-first (one thread per output, fp32).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, zp: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [M, K]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\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.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xbase = m * p.K;\n let cbyteBase = n * (p.K / 4u); // byte offset of row n in the codes stream\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n let k0 = b * p.block;\n for (var j = 0u; j < p.block; j = j + 1u) {\n let k = k0 + j;\n let byteIdx = cbyteBase + (k >> 2u);\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let code = (byte >> (2u * (k & 3u))) & 3u;\n bsum = bsum + (f32(code) - zpf) * x[xbase + k];\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
|
|
16
17
|
"matmul_q2_sg": "// Subgroup split-K GEMV for the 2-bit lm_head (M=1 decode). One subgroup per output column,\n// lanes split K (vec4), reduce with subgroupAdd. value = (code - zp) * per-block scale.\n// 2D dispatch since N (vocab) > 65535.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { N: u32, K: u32, nb: u32, zp: u32, gridX: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [N]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let n = wg.y * p.gridX + wg.x;\n if (n >= p.N) { return; }\n let cbase = n * (p.K / 4u); // byte offset of row n in the codes stream\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n let Kvec = p.K / 4u;\n\n var acc = 0.0;\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let byteIdx = cbase + gi;\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let cv = vec4<f32>(f32(byte & 3u) - zpf, f32((byte >> 2u) & 3u) - zpf,\n f32((byte >> 4u) & 3u) - zpf, f32((byte >> 6u) & 3u) - zpf);\n acc = acc + dot(x[gi], cv) * scales[sbase + (gi >> 5u)]; // block = (gi*4)/128 = gi/32\n }\n let total = subgroupAdd(acc);\n if (lane == 0u) { y[n] = total; }\n}\n",
|
|
@@ -407,7 +408,8 @@ async function createEngineInner(options, holder) {
|
|
|
407
408
|
["embed_gather"],
|
|
408
409
|
["embed_gather_batch"],
|
|
409
410
|
["sampler_penalty"],
|
|
410
|
-
["argmax_masked"]
|
|
411
|
+
["argmax_masked"],
|
|
412
|
+
["logsumexp"]
|
|
411
413
|
];
|
|
412
414
|
if (useSG) {
|
|
413
415
|
for (const n of [
|
|
@@ -1563,6 +1565,8 @@ async function createEngineInner(options, holder) {
|
|
|
1563
1565
|
const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
|
|
1564
1566
|
const vocab = W.lm_head.N;
|
|
1565
1567
|
const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
|
|
1568
|
+
const lpN = Math.max(0, Math.min(Math.floor(genOpts.logprobs ?? 0), 32, vocab));
|
|
1569
|
+
const KT = Math.max(K, lpN);
|
|
1566
1570
|
const temperature = genOpts.temperature ?? 1;
|
|
1567
1571
|
const penalty = genOpts.repetitionPenalty ?? 1;
|
|
1568
1572
|
const ngramN = genOpts.noRepeatNgramSize ?? 0;
|
|
@@ -1579,11 +1583,15 @@ async function createEngineInner(options, holder) {
|
|
|
1579
1583
|
usage: S_ | CS
|
|
1580
1584
|
});
|
|
1581
1585
|
const candIds = device.createBuffer({
|
|
1582
|
-
size:
|
|
1586
|
+
size: KT * 4,
|
|
1583
1587
|
usage: S_ | CS
|
|
1584
1588
|
});
|
|
1585
1589
|
const candVals = device.createBuffer({
|
|
1586
|
-
size:
|
|
1590
|
+
size: KT * 4,
|
|
1591
|
+
usage: S_ | CS
|
|
1592
|
+
});
|
|
1593
|
+
const lseBuf = device.createBuffer({
|
|
1594
|
+
size: 4,
|
|
1587
1595
|
usage: S_ | CS
|
|
1588
1596
|
});
|
|
1589
1597
|
const affBuf = device.createBuffer({
|
|
@@ -1595,7 +1603,7 @@ async function createEngineInner(options, holder) {
|
|
|
1595
1603
|
usage: S_ | CD
|
|
1596
1604
|
});
|
|
1597
1605
|
const rbBuf = device.createBuffer({
|
|
1598
|
-
size:
|
|
1606
|
+
size: KT * 8 + (lpN ? 4 : 0),
|
|
1599
1607
|
usage: GPUBufferUsage.MAP_READ | CD
|
|
1600
1608
|
});
|
|
1601
1609
|
const embG = device.createBuffer({
|
|
@@ -1620,7 +1628,16 @@ async function createEngineInner(options, holder) {
|
|
|
1620
1628
|
["u", 4286578688]
|
|
1621
1629
|
], [affBuf, banBuf], [lg]);
|
|
1622
1630
|
pass.dispatchWorkgroups(1);
|
|
1623
|
-
|
|
1631
|
+
if (lpN) {
|
|
1632
|
+
setup(pass, "logsumexp", [
|
|
1633
|
+
["u", vocab],
|
|
1634
|
+
["u", 0],
|
|
1635
|
+
["u", 0],
|
|
1636
|
+
["u", 0]
|
|
1637
|
+
], [lg], [lseBuf]);
|
|
1638
|
+
pass.dispatchWorkgroups(1);
|
|
1639
|
+
}
|
|
1640
|
+
for (let r = 0; r < KT; r++) {
|
|
1624
1641
|
setup(pass, "argmax_masked", [
|
|
1625
1642
|
["u", vocab],
|
|
1626
1643
|
["u", r],
|
|
@@ -1630,21 +1647,50 @@ async function createEngineInner(options, holder) {
|
|
|
1630
1647
|
pass.dispatchWorkgroups(1);
|
|
1631
1648
|
}
|
|
1632
1649
|
};
|
|
1650
|
+
const copyCands = (enc) => {
|
|
1651
|
+
enc.copyBufferToBuffer(candIds, 0, rbBuf, 0, KT * 4);
|
|
1652
|
+
enc.copyBufferToBuffer(candVals, 0, rbBuf, KT * 4, KT * 4);
|
|
1653
|
+
if (lpN) enc.copyBufferToBuffer(lseBuf, 0, rbBuf, KT * 8, 4);
|
|
1654
|
+
};
|
|
1633
1655
|
const readCands = async () => {
|
|
1634
1656
|
await rbBuf.mapAsync(GPUMapMode.READ);
|
|
1635
1657
|
const mapped = rbBuf.getMappedRange();
|
|
1636
|
-
const ci = new Uint32Array(mapped.slice(0,
|
|
1637
|
-
const cv = new Float32Array(mapped.slice(
|
|
1658
|
+
const ci = new Uint32Array(mapped.slice(0, KT * 4));
|
|
1659
|
+
const cv = new Float32Array(mapped.slice(KT * 4, KT * 8));
|
|
1660
|
+
const lse = lpN ? new Float32Array(mapped.slice(KT * 8, KT * 8 + 4))[0] : 0;
|
|
1638
1661
|
rbBuf.unmap();
|
|
1639
1662
|
return {
|
|
1640
1663
|
ci,
|
|
1641
|
-
cv
|
|
1664
|
+
cv,
|
|
1665
|
+
lse
|
|
1642
1666
|
};
|
|
1643
1667
|
};
|
|
1644
|
-
|
|
1668
|
+
let chosenLogit = 0;
|
|
1669
|
+
const lpOut = lpN ? [] : null;
|
|
1670
|
+
const recordLp = (ci, cv, lse) => {
|
|
1671
|
+
if (!lpOut) return;
|
|
1672
|
+
const top = [];
|
|
1673
|
+
for (let i = 0; i < lpN; i++) top.push({
|
|
1674
|
+
id: ci[i],
|
|
1675
|
+
logprob: cv[i] - lse
|
|
1676
|
+
});
|
|
1677
|
+
lpOut.push({
|
|
1678
|
+
logprob: chosenLogit - lse,
|
|
1679
|
+
top
|
|
1680
|
+
});
|
|
1681
|
+
};
|
|
1682
|
+
const pick = (ciAll, cvAll) => {
|
|
1683
|
+
const ci = ciAll.subarray(0, K);
|
|
1684
|
+
const cv = cvAll.subarray(0, K);
|
|
1685
|
+
const tk = sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
|
|
1686
|
+
chosenLogit = cv[ci.indexOf(tk)];
|
|
1687
|
+
return tk;
|
|
1688
|
+
};
|
|
1645
1689
|
const filter = genOpts.candidateFilter;
|
|
1646
|
-
const chooseToken = async (
|
|
1647
|
-
if (!filter) return pick(
|
|
1690
|
+
const chooseToken = async (ciAll, cvAll) => {
|
|
1691
|
+
if (!filter) return pick(ciAll, cvAll);
|
|
1692
|
+
const ci = ciAll.subarray(0, K);
|
|
1693
|
+
const cv = cvAll.subarray(0, K);
|
|
1648
1694
|
const perm = new Set(filter(ci, cv));
|
|
1649
1695
|
if (perm.size > 0) {
|
|
1650
1696
|
const pIds = [];
|
|
@@ -1653,9 +1699,12 @@ async function createEngineInner(options, holder) {
|
|
|
1653
1699
|
pIds.push(ci[i]);
|
|
1654
1700
|
pVals.push(cv[i]);
|
|
1655
1701
|
}
|
|
1656
|
-
|
|
1702
|
+
const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
|
|
1703
|
+
chosenLogit = pVals[pIds.indexOf(tk)];
|
|
1704
|
+
return tk;
|
|
1657
1705
|
}
|
|
1658
1706
|
const all = await readback(lg, vocab);
|
|
1707
|
+
for (let i = 0; i < ciAll.length; i++) all[ciAll[i]] = cvAll[i];
|
|
1659
1708
|
const order = Array.from(all.keys()).sort((a, b) => all[b] - all[a] || a - b);
|
|
1660
1709
|
const pIds = [];
|
|
1661
1710
|
const pVals = [];
|
|
@@ -1671,7 +1720,9 @@ async function createEngineInner(options, holder) {
|
|
|
1671
1720
|
}
|
|
1672
1721
|
}
|
|
1673
1722
|
if (pIds.length === 0) throw new Error("bitgpu: candidateFilter permitted no token in the entire vocabulary");
|
|
1674
|
-
|
|
1723
|
+
const tk = sampled ? sampleFromCandidates(pIds, pVals, temperature, rng) : pIds[0];
|
|
1724
|
+
chosenLogit = pVals[pIds.indexOf(tk)];
|
|
1725
|
+
return tk;
|
|
1675
1726
|
};
|
|
1676
1727
|
transients = [];
|
|
1677
1728
|
try {
|
|
@@ -1696,8 +1747,7 @@ async function createEngineInner(options, holder) {
|
|
|
1696
1747
|
lmHead(pass, lastP, 1, lg);
|
|
1697
1748
|
samplerChain(pass, pf.affLen, pf.banLen);
|
|
1698
1749
|
pass.end();
|
|
1699
|
-
encP
|
|
1700
|
-
encP.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
|
|
1750
|
+
copyCands(encP);
|
|
1701
1751
|
device.queue.submit([encP.finish()]);
|
|
1702
1752
|
const first = await readCands();
|
|
1703
1753
|
const firstTok = await chooseToken(first.ci, first.cv);
|
|
@@ -1708,6 +1758,7 @@ async function createEngineInner(options, holder) {
|
|
|
1708
1758
|
if (!stopped) {
|
|
1709
1759
|
gen.push(firstTok);
|
|
1710
1760
|
history.push(firstTok);
|
|
1761
|
+
recordLp(first.ci, first.cv, first.lse);
|
|
1711
1762
|
onToken?.(firstTok);
|
|
1712
1763
|
device.queue.writeBuffer(tokBuf, 0, new Uint32Array([firstTok]));
|
|
1713
1764
|
}
|
|
@@ -1743,12 +1794,11 @@ async function createEngineInner(options, holder) {
|
|
|
1743
1794
|
lmHead(p2, last, 1, lg);
|
|
1744
1795
|
samplerChain(p2, affLen, banLen);
|
|
1745
1796
|
p2.end();
|
|
1746
|
-
enc
|
|
1747
|
-
enc.copyBufferToBuffer(candVals, 0, rbBuf, K * 4, K * 4);
|
|
1797
|
+
copyCands(enc);
|
|
1748
1798
|
device.queue.submit([enc.finish()]);
|
|
1749
1799
|
recMs += performance.now() - t;
|
|
1750
1800
|
t = performance.now();
|
|
1751
|
-
const { ci, cv } = await readCands();
|
|
1801
|
+
const { ci, cv, lse } = await readCands();
|
|
1752
1802
|
gpuMs += performance.now() - t;
|
|
1753
1803
|
t = performance.now();
|
|
1754
1804
|
const tk = await chooseToken(ci, cv);
|
|
@@ -1760,6 +1810,7 @@ async function createEngineInner(options, holder) {
|
|
|
1760
1810
|
}
|
|
1761
1811
|
gen.push(tk);
|
|
1762
1812
|
history.push(tk);
|
|
1813
|
+
recordLp(ci, cv, lse);
|
|
1763
1814
|
onToken?.(tk);
|
|
1764
1815
|
device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk]));
|
|
1765
1816
|
}
|
|
@@ -1774,7 +1825,8 @@ async function createEngineInner(options, holder) {
|
|
|
1774
1825
|
recMs: recMs / nd,
|
|
1775
1826
|
gpuMs: gpuMs / nd,
|
|
1776
1827
|
rbMs: rbMs / nd,
|
|
1777
|
-
rng
|
|
1828
|
+
rng,
|
|
1829
|
+
...lpOut ? { lp: lpOut } : {}
|
|
1778
1830
|
};
|
|
1779
1831
|
} finally {
|
|
1780
1832
|
poolUse(null);
|
|
@@ -1785,6 +1837,7 @@ async function createEngineInner(options, holder) {
|
|
|
1785
1837
|
lg,
|
|
1786
1838
|
candIds,
|
|
1787
1839
|
candVals,
|
|
1840
|
+
lseBuf,
|
|
1788
1841
|
affBuf,
|
|
1789
1842
|
banBuf,
|
|
1790
1843
|
rbBuf,
|
|
@@ -2245,7 +2298,7 @@ async function createEngineInner(options, holder) {
|
|
|
2245
2298
|
transients = null;
|
|
2246
2299
|
}
|
|
2247
2300
|
}
|
|
2248
|
-
const hasFilter = !!genOpts.candidateFilter;
|
|
2301
|
+
const hasFilter = !!genOpts.candidateFilter || (genOpts.logprobs ?? 0) > 0;
|
|
2249
2302
|
let r;
|
|
2250
2303
|
if (!hasFilter && genOpts.promptLookup === "auto" && maxTokens > 24) {
|
|
2251
2304
|
const r1 = await generatePldImpl(prefillTokens, posBase, 24, genOpts, fullHistory);
|
|
@@ -2310,7 +2363,8 @@ async function createEngineInner(options, holder) {
|
|
|
2310
2363
|
gpuMs: r.gpuMs,
|
|
2311
2364
|
readbackMs: r.rbMs
|
|
2312
2365
|
},
|
|
2313
|
-
...r.spec ? { speculation: r.spec } : {}
|
|
2366
|
+
...r.spec ? { speculation: r.spec } : {},
|
|
2367
|
+
...r.lp ? { logprobs: r.lp } : {}
|
|
2314
2368
|
};
|
|
2315
2369
|
}
|
|
2316
2370
|
async function prefill(ids) {
|