bitgpu 0.3.0 → 0.5.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 +43 -3
- package/dist/index.d.ts +15 -4
- package/dist/index.js +364 -105
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -9,7 +9,7 @@ const SHADERS = {
|
|
|
9
9
|
"attention_wg_kv16": "// attention_wg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_wg.wgsl: the ONLY difference is Kc/Vc are array<f16>, widened to f32 at the read.\nenable f16;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { part = part + q[qb + d] * f32(Kc[kb + d]); }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
|
|
10
10
|
"copy": "// Copy src[0..n) into dst[dstOff..dstOff+n). Used to append K/V into the persistent cache.\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<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 dst[p.dstOff + i] = src[i];\n}\n",
|
|
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
|
-
"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*
|
|
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
|
"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",
|
|
14
14
|
"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",
|
|
15
15
|
"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",
|
|
@@ -23,7 +23,7 @@ const SHADERS = {
|
|
|
23
23
|
"matmul_split": "// Fused binary matmul writing to up to 3 output buffers (qkv or gate/up in one dispatch).\n// Weights for the outputs are concatenated along N (rows N0 | N1 | N2). One thread per\n// output column n routes its result to out0/out1/out2 by range. Vectorized like matmul_binary_vec4.\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: 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>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: 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 Ntot = p.N0 + p.N1 + p.N2;\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * Ntot) { return; }\n let row = idx / Ntot;\n let n = idx % Ntot;\n let xRow = row * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\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 < 4u; w = w + 1u) {\n let word = signbits[wRow + b * 4u + w];\n let xb = xRow + b * 32u + w * 8u;\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n\n if (n < p.N0) { out0[row * p.N0 + n] = acc; }\n else if (n < p.N0 + p.N1) { out1[row * p.N1 + (n - p.N0)] = acc; }\n else { out2[row * p.N2 + (n - p.N0 - p.N1)] = acc; }\n}\n",
|
|
24
24
|
"matmul_split_sg": "// Subgroup split-K GEMV for decode (M=1), fused: one subgroup (= one workgroup) per output\n// column; lanes split the K dimension and reduce with subgroupAdd (register-only, no barriers).\n// Cuts each matmul's latency ~SG-fold vs one-thread-per-output (the real decode bottleneck:\n// kernels run at full latency in the dependent chain). Routes to out0/out1/out2 by range (qkv / gate-up).\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: 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> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x;\n if (n >= Ntot) { return; }\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n\n var acc = 0.0;\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\n }\n let total = subgroupAdd(acc);\n if (lane == 0u) {\n if (n < p.N0) { out0[n] = total; }\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\n else { out2[n - p.N0 - p.N1] = total; }\n }\n}\n",
|
|
25
25
|
"matmul_split_sm": "// Small-batch (M = 2..9) subgroup split-K GEMV, fused qkv / gate-up. The speculative-decode\n// verify pass computes M drafted rows in one forward; the scalar prefill kernels re-read the\n// weights per output thread, so a k-row pass cost ~k GEMVs. Here each weight word is loaded\n// ONCE per (column, k-chunk) and dotted with all M activation rows (activations are ~8 KB/row,\n// cache-resident). Per row the loop stride and accumulation expression are IDENTICAL to\n// matmul_split_sg, so each row's partials - and therefore the subgroupAdd result - match the\n// M=1 decode path bit-for-bit.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32, M: 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] row-major\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>; // [M, N0]\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>; // [M, N1]\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>; // [M, N2]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x;\n if (n >= Ntot) { return; } // uniform per workgroup: the whole subgroup exits together\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n\n var acc: array<f32, 9>; // M <= 9\n for (var m = 0u; m < p.M; m = m + 1u) { acc[m] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n let s = scales[sbase + (k / 128u)];\n for (var m = 0u; m < p.M; m = m + 1u) {\n acc[m] = acc[m] + dot(x[m * Kvec + gi], sv) * s;\n }\n }\n for (var m = 0u; m < p.M; m = m + 1u) { // p.M is uniform: collective calls stay uniform\n let total = subgroupAdd(acc[m]);\n if (lane == 0u) {\n if (n < p.N0) { out0[m * p.N0 + n] = total; }\n else if (n < p.N0 + p.N1) { out1[m * p.N1 + (n - p.N0)] = total; }\n else { out2[m * p.N2 + (n - p.N0 - p.N1)] = total; }\n }\n }\n}\n",
|
|
26
|
-
"matmul_split_tiled": "// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\n// Weights concatenated along N (N0|N1|N2); each
|
|
26
|
+
"matmul_split_tiled": "// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\n// Weights concatenated along N (N0|N1|N2); each output element routes individually to\n// out0/out1/out2 by its global column, so N0/N1/N2 need no alignment. Same vec4 design as\n// matmul_resid_tiled.\nconst BM: u32 = 64u;\nconst BN: u32 = 64u;\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: 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>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\nvar<workgroup> xs: array<vec4<f32>, 256>;\nvar<workgroup> ws: array<vec4<f32>, 256>;\n\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let tid = lid.x;\n let tileM = wg.y * BM;\n let tileN = wg.x * BN;\n let tr = (tid / 16u) * 4u;\n let tc = (tid % 16u) * 4u;\n let Kv = p.K / 4u;\n var acc: array<f32, 16>;\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\n\n let Ksteps = Kv / BKV;\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\n let k0v = ks * BKV;\n for (var e = tid; e < BM * BKV; e = e + 256u) {\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\n }\n for (var e = tid; e < BN * BKV; e = e + 256u) {\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\n var wv = vec4<f32>(0.0);\n if (gn < Ntot) {\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\n let s = scales[gn * p.nb + (k / 128u)];\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\n }\n ws[e] = wv;\n }\n workgroupBarrier();\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\n var xr: array<vec4<f32>, 4>;\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let w = ws[(tc + tn) * BKV + kv];\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\n }\n }\n workgroupBarrier();\n }\n\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\n let gm = tileM + tr + tm;\n if (gm >= p.M) { continue; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let gn = tileN + tc + tn;\n if (gn >= Ntot) { continue; }\n let v = acc[tm * 4u + tn];\n if (gn < p.N0) { out0[gm * p.N0 + gn] = v; }\n else if (gn < p.N0 + p.N1) { out1[gm * p.N1 + (gn - p.N0)] = v; }\n else { out2[gm * p.N2 + (gn - p.N0 - p.N1)] = v; }\n }\n }\n}\n",
|
|
27
27
|
"matmul_split_wg": "// No-subgroup fallback: split-K GEMV for decode (M=1), workgroup-shared-memory reduction instead\n// of subgroupAdd. One workgroup per output column; WG threads split K and tree-reduce via shared\n// memory + barriers. ~WG-fold faster than one-thread-per-output (the v1 path). Routes qkv / gate-up.\noverride WG: u32 = 64u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: 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> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\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 Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (n >= Ntot) { return; }\n let tid = lid.x;\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n var acc = 0.0;\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\n }\n sdata[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) {\n let total = sdata[0];\n if (n < p.N0) { out0[n] = total; }\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\n else { out2[n - p.N0 - p.N1] = total; }\n }\n}\n",
|
|
28
28
|
"matmul_swiglu_mr_sg": "// Multi-row fused gate/up GEMV + SwiGLU for decode (M=1). Each workgroup computes ROWS\n// intermediate indices; per K-step it issues 2*ROWS independent weight loads (gate row n and up\n// row F+n for each of the ROWS) before the dots, giving the bandwidth-bound decode GEMV more\n// in-flight memory requests. One subgroup per workgroup; lanes split K; reduced with subgroupAdd.\nenable subgroups;\noverride SG: u32 = 32u;\noverride ROWS: u32 = 4u;\nstruct Params { K: u32, nb: u32, F: u32, gridX: u32, _p0: u32, _p1: 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> signbits: array<u32>; // [2F, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [2F, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [F]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let nBase = (wg.y * p.gridX + wg.x) * ROWS;\n let Kvec = p.K / 4u;\n let wStride = p.K / 32u;\n\n var g: array<f32, 8>; // ROWS <= 8\n var u: array<f32, 8>;\n for (var r = 0u; r < ROWS; r = r + 1u) { g[r] = 0.0; u[r] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let xv = x[gi];\n let widx = k >> 5u;\n let sh = k & 31u;\n let sc = k / 128u;\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n if (n < p.F) {\n let gw = (signbits[n * wStride + widx] >> sh) & 0xfu;\n let gv = vec4<f32>(select(-1.0, 1.0, (gw & 1u) != 0u), select(-1.0, 1.0, (gw & 2u) != 0u),\n select(-1.0, 1.0, (gw & 4u) != 0u), select(-1.0, 1.0, (gw & 8u) != 0u));\n g[r] = g[r] + dot(xv, gv) * scales[n * p.nb + sc];\n let uw = (signbits[(p.F + n) * wStride + widx] >> sh) & 0xfu;\n let uv = vec4<f32>(select(-1.0, 1.0, (uw & 1u) != 0u), select(-1.0, 1.0, (uw & 2u) != 0u),\n select(-1.0, 1.0, (uw & 4u) != 0u), select(-1.0, 1.0, (uw & 8u) != 0u));\n u[r] = u[r] + dot(xv, uv) * scales[(p.F + n) * p.nb + sc];\n }\n }\n }\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n let gt = subgroupAdd(g[r]);\n let ut = subgroupAdd(u[r]);\n if (lane == 0u && n < p.F) { y[n] = (gt / (1.0 + exp(-gt))) * ut; }\n }\n}\n",
|
|
29
29
|
"rmsnorm_rope_sg": "// Fused per-head RMSNorm + RoPE for decode (S=1). One subgroup (= one workgroup) per head row;\n// lanes split head_dim, reduce sum-of-squares with subgroupAdd, then apply rope. rotate_half\n// pairs (d, d+-D/2): with SG>=32 and D=128 a lane owns d in {lane, lane+32, lane+64, lane+96},\n// so every (d, d+-64) pair is held by the same lane (no cross-lane reads for the rotate).\n// outOff/outStride let the K result write straight into the KV cache at its position.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outOff: u32, outStride: u32, _p: 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> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [outOff + R*outStride]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let ob = p.outOff + row * p.outStride;\n for (var i = lane; i < p.D; i = i + SG) {\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n y[ob + i] = nd * cos[i] + rot * sin[i];\n }\n}\n",
|
|
@@ -196,6 +196,7 @@ const WGSLS = [
|
|
|
196
196
|
"copy"
|
|
197
197
|
];
|
|
198
198
|
const DEFAULT_MAX_SEQ = 2048;
|
|
199
|
+
const PREFILL_SEG = 256;
|
|
199
200
|
const PARAM_AB = /* @__PURE__ */ new ArrayBuffer(64);
|
|
200
201
|
const PARAM_DV = new DataView(PARAM_AB);
|
|
201
202
|
const PARAM_U8 = new Uint8Array(PARAM_AB);
|
|
@@ -211,19 +212,17 @@ const eqBytes = (a, b) => {
|
|
|
211
212
|
for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false;
|
|
212
213
|
return true;
|
|
213
214
|
};
|
|
214
|
-
function concat(Cls, arrs) {
|
|
215
|
-
let n = 0;
|
|
216
|
-
for (const a of arrs) n += a.length;
|
|
217
|
-
const o = new Cls(n);
|
|
218
|
-
let p = 0;
|
|
219
|
-
for (const a of arrs) {
|
|
220
|
-
o.set(a, p);
|
|
221
|
-
p += a.length;
|
|
222
|
-
}
|
|
223
|
-
return o;
|
|
224
|
-
}
|
|
225
215
|
/** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
|
|
226
216
|
async function createEngine(options) {
|
|
217
|
+
const holder = {};
|
|
218
|
+
try {
|
|
219
|
+
return await createEngineInner(options, holder);
|
|
220
|
+
} catch (e) {
|
|
221
|
+
holder.device?.destroy();
|
|
222
|
+
throw e;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
async function createEngineInner(options, holder) {
|
|
227
226
|
const opts = typeof options === "string" ? { modelUrl: options } : options;
|
|
228
227
|
const modelDir = opts.modelUrl ? opts.modelUrl.replace(/\/$/, "") : null;
|
|
229
228
|
if (!modelDir && !opts.manifestUrl) throw new Error("createEngine: provide modelUrl or manifestUrl");
|
|
@@ -266,26 +265,26 @@ async function createEngine(options) {
|
|
|
266
265
|
const manifest = await fetchJson(opts.manifestUrl ?? `${modelDir}/manifest.json`);
|
|
267
266
|
opts.onProgress?.({ phase: "weights" });
|
|
268
267
|
const dataUrl = opts.dataUrl ?? `${modelDir}/${manifest.data_file}`;
|
|
269
|
-
|
|
270
|
-
let [data, aux] = await Promise.all([fetchBytes(dataUrl), fetchBytes(auxUrl)]);
|
|
268
|
+
let aux = await fetchBytes(opts.auxUrl ?? `${modelDir}/${manifest.aux_file}`);
|
|
271
269
|
const A = manifest.arch;
|
|
272
270
|
const T = manifest.tensors;
|
|
273
271
|
const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
|
|
274
272
|
if (A.act !== "silu") throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`);
|
|
275
273
|
if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`);
|
|
274
|
+
if (A.heads % A.kv_heads !== 0) throw new Error(`bitgpu: heads ${A.heads} not divisible by kv_heads ${A.kv_heads} (GQA kernels assume an integer group size)`);
|
|
276
275
|
if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
|
|
276
|
+
if (!T.cos_cache || !T.sin_cache) throw new Error("bitgpu: manifest is missing the baked cos_cache/sin_cache RoPE tensors");
|
|
277
277
|
for (const [name, t] of Object.entries(T)) if (t.block !== void 0 && t.block !== 128) throw new Error(`bitgpu: tensor ${name} has block ${t.block} (kernels assume 128)`);
|
|
278
278
|
const readRef = (ref) => {
|
|
279
|
-
|
|
280
|
-
if (ref.off + ref.len >
|
|
279
|
+
if (ref.src !== "aux") throw new Error("bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes");
|
|
280
|
+
if (ref.off + ref.len > aux.byteLength) throw new Error(`bitgpu: tensor range ${ref.off}+${ref.len} exceeds the aux file (${aux.byteLength} bytes); the download is truncated or the manifest does not match it`);
|
|
281
281
|
const V = VIEW[ref.dtype];
|
|
282
|
-
if (V === Uint8Array) return new Uint8Array(
|
|
282
|
+
if (V === Uint8Array) return new Uint8Array(aux, ref.off, ref.len);
|
|
283
283
|
const bpe = V.BYTES_PER_ELEMENT;
|
|
284
|
-
if (ref.off % bpe === 0) return new V(
|
|
285
|
-
return new V(
|
|
284
|
+
if (ref.off % bpe === 0) return new V(aux, ref.off, ref.len / bpe);
|
|
285
|
+
return new V(aux.slice(ref.off, ref.off + ref.len));
|
|
286
286
|
};
|
|
287
287
|
const readU8 = (ref) => readRef(ref);
|
|
288
|
-
const readF32 = (ref) => readRef(ref);
|
|
289
288
|
const adapter = await navigator.gpu.requestAdapter({ powerPreference });
|
|
290
289
|
if (!adapter) throw new WebGPUUnavailableError("No suitable WebGPU adapter was found.");
|
|
291
290
|
const hasSG = adapter.features.has("subgroups");
|
|
@@ -299,13 +298,64 @@ async function createEngine(options) {
|
|
|
299
298
|
const tiledPrefill = (S) => FORCETILE || !NOTILE && S >= 64;
|
|
300
299
|
const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
|
|
301
300
|
const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
|
|
302
|
-
const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && !forceNoSG;
|
|
301
|
+
const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
|
|
303
302
|
const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
|
|
304
303
|
const KVB = kv16 ? 2 : 4;
|
|
305
304
|
const features = [];
|
|
306
305
|
if (useSG) features.push("subgroups");
|
|
307
306
|
if (kv16) features.push("shader-f16");
|
|
308
|
-
const
|
|
307
|
+
const DEFAULT_BINDING = 134217728;
|
|
308
|
+
const DEFAULT_BUFFER = 268435456;
|
|
309
|
+
let needBind = 0;
|
|
310
|
+
let weightBytes = 0;
|
|
311
|
+
const track = (bytes) => {
|
|
312
|
+
const b = bytes + 3 & -4;
|
|
313
|
+
needBind = Math.max(needBind, b);
|
|
314
|
+
weightBytes += b;
|
|
315
|
+
};
|
|
316
|
+
for (const t of Object.values(T)) if (t.kind === "q2") {
|
|
317
|
+
track(t.weight.len * 2);
|
|
318
|
+
track(t.scales.len);
|
|
319
|
+
} else if (t.kind === "f32" && t.weight) track(t.weight.len);
|
|
320
|
+
const fusedLen = (names, f) => names.reduce((n, nm) => n + T[nm][f].len, 0);
|
|
321
|
+
for (let li = 0; li < A.layers; li++) {
|
|
322
|
+
const groups = [
|
|
323
|
+
[
|
|
324
|
+
`layers.${li}.attn.q_proj`,
|
|
325
|
+
`layers.${li}.attn.k_proj`,
|
|
326
|
+
`layers.${li}.attn.v_proj`
|
|
327
|
+
],
|
|
328
|
+
[`layers.${li}.mlp.gate_proj`, `layers.${li}.mlp.up_proj`],
|
|
329
|
+
[`layers.${li}.attn.o_proj`],
|
|
330
|
+
[`layers.${li}.mlp.down_proj`]
|
|
331
|
+
];
|
|
332
|
+
for (const g of groups) {
|
|
333
|
+
track(fusedLen(g, "weight"));
|
|
334
|
+
track(fusedLen(g, "scales"));
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
for (const r of [
|
|
338
|
+
T.embed_tokens.weight,
|
|
339
|
+
T.embed_tokens.scales,
|
|
340
|
+
T.embed_tokens.zp,
|
|
341
|
+
manifest.luts.tgt4
|
|
342
|
+
]) track(r.len);
|
|
343
|
+
const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB;
|
|
344
|
+
needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4);
|
|
345
|
+
const requiredLimits = {};
|
|
346
|
+
if (needBind > DEFAULT_BINDING) {
|
|
347
|
+
if (needBind > adapter.limits.maxStorageBufferBindingSize) throw new GpuOutOfMemoryError(`this model needs a ${Math.ceil(needBind / 1048576)} MiB storage binding but the adapter's maxStorageBufferBindingSize is ${Math.floor(adapter.limits.maxStorageBufferBindingSize / 1048576)} MiB`);
|
|
348
|
+
requiredLimits.maxStorageBufferBindingSize = needBind;
|
|
349
|
+
}
|
|
350
|
+
if (needBind > DEFAULT_BUFFER) {
|
|
351
|
+
if (needBind > adapter.limits.maxBufferSize) throw new GpuOutOfMemoryError(`this model needs a ${Math.ceil(needBind / 1048576)} MiB buffer but the adapter's maxBufferSize is ${Math.floor(adapter.limits.maxBufferSize / 1048576)} MiB`);
|
|
352
|
+
requiredLimits.maxBufferSize = needBind;
|
|
353
|
+
}
|
|
354
|
+
const device = await adapter.requestDevice({
|
|
355
|
+
requiredFeatures: features,
|
|
356
|
+
requiredLimits: Object.keys(requiredLimits).length ? requiredLimits : void 0
|
|
357
|
+
});
|
|
358
|
+
holder.device = device;
|
|
309
359
|
const lost = device.lost.then((info) => {
|
|
310
360
|
const li = {
|
|
311
361
|
reason: String(info.reason ?? "unknown"),
|
|
@@ -449,105 +499,272 @@ async function createEngine(options) {
|
|
|
449
499
|
const resetCache = () => {
|
|
450
500
|
fullHistory = [];
|
|
451
501
|
};
|
|
502
|
+
if (manifest.luts.tgt2.src !== "aux") throw new Error("bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)");
|
|
452
503
|
const tgt2 = readU8(manifest.luts.tgt2);
|
|
453
|
-
let tgt4 = readU8(manifest.luts.tgt4);
|
|
454
504
|
const signTable = /* @__PURE__ */ new Uint8Array(256);
|
|
455
505
|
for (let b = 0; b < 256; b++) {
|
|
456
506
|
let bits = 0;
|
|
457
507
|
for (let j = 0; j < 8; j++) bits |= ((tgt2[2 * b + (j >> 2)] >> 2 * (j & 3) & 3) >> 1 & 1) << j;
|
|
458
508
|
signTable[b] = bits;
|
|
459
509
|
}
|
|
460
|
-
const
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
510
|
+
const routes = [];
|
|
511
|
+
const gbuf = (len) => device.createBuffer({
|
|
512
|
+
size: len + 3 & -4,
|
|
513
|
+
usage: S_ | CD
|
|
514
|
+
});
|
|
515
|
+
const gpuSink = (buf, base) => {
|
|
516
|
+
let written = 0;
|
|
517
|
+
let carry = /* @__PURE__ */ new Uint8Array(0);
|
|
465
518
|
return {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
519
|
+
push(bytes) {
|
|
520
|
+
let all = bytes;
|
|
521
|
+
if (carry.length) {
|
|
522
|
+
all = new Uint8Array(carry.length + bytes.length);
|
|
523
|
+
all.set(carry);
|
|
524
|
+
all.set(bytes, carry.length);
|
|
525
|
+
}
|
|
526
|
+
const n = all.length & -4;
|
|
527
|
+
if (n) device.queue.writeBuffer(buf, base + written, all, 0, n);
|
|
528
|
+
carry = all.subarray(n).slice();
|
|
529
|
+
written += n;
|
|
530
|
+
},
|
|
531
|
+
finish() {
|
|
532
|
+
if (!carry.length) return;
|
|
533
|
+
const pad = /* @__PURE__ */ new Uint8Array(4);
|
|
534
|
+
pad.set(carry);
|
|
535
|
+
device.queue.writeBuffer(buf, base + written, pad);
|
|
536
|
+
written += 4;
|
|
537
|
+
carry = /* @__PURE__ */ new Uint8Array(0);
|
|
538
|
+
}
|
|
471
539
|
};
|
|
472
540
|
};
|
|
541
|
+
const wire = (ref, push, finish) => {
|
|
542
|
+
if (ref.src === "aux") {
|
|
543
|
+
push(new Uint8Array(readRef(ref).buffer, ref.off, ref.len));
|
|
544
|
+
finish();
|
|
545
|
+
} else routes.push({
|
|
546
|
+
off: ref.off,
|
|
547
|
+
len: ref.len,
|
|
548
|
+
push,
|
|
549
|
+
finish
|
|
550
|
+
});
|
|
551
|
+
};
|
|
552
|
+
const wireRaw = (ref, buf, base = 0) => {
|
|
553
|
+
const s = gpuSink(buf, base);
|
|
554
|
+
wire(ref, s.push, s.finish);
|
|
555
|
+
};
|
|
556
|
+
const wireSign = (ref, buf, base = 0) => {
|
|
557
|
+
const s = gpuSink(buf, base);
|
|
558
|
+
wire(ref, (b) => {
|
|
559
|
+
const o = new Uint8Array(b.length);
|
|
560
|
+
for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]];
|
|
561
|
+
s.push(o);
|
|
562
|
+
}, s.finish);
|
|
563
|
+
};
|
|
564
|
+
const wireQ2 = (ref, buf) => {
|
|
565
|
+
const s = gpuSink(buf, 0);
|
|
566
|
+
wire(ref, (b) => {
|
|
567
|
+
const o = new Uint8Array(b.length * 2);
|
|
568
|
+
for (let i = 0; i < b.length; i++) {
|
|
569
|
+
o[2 * i] = tgt2[2 * b[i]];
|
|
570
|
+
o[2 * i + 1] = tgt2[2 * b[i] + 1];
|
|
571
|
+
}
|
|
572
|
+
s.push(o);
|
|
573
|
+
}, s.finish);
|
|
574
|
+
};
|
|
575
|
+
const wireCpu = (ref) => {
|
|
576
|
+
const dst = new Uint8Array(ref.len);
|
|
577
|
+
let w = 0;
|
|
578
|
+
wire(ref, (b) => {
|
|
579
|
+
dst.set(b, w);
|
|
580
|
+
w += b.length;
|
|
581
|
+
}, () => void 0);
|
|
582
|
+
return dst;
|
|
583
|
+
};
|
|
584
|
+
const wireCpuGpu = (ref) => {
|
|
585
|
+
const buf = gbuf(ref.len);
|
|
586
|
+
const s = gpuSink(buf, 0);
|
|
587
|
+
const dst = new Uint8Array(ref.len);
|
|
588
|
+
let w = 0;
|
|
589
|
+
wire(ref, (b) => {
|
|
590
|
+
dst.set(b, w);
|
|
591
|
+
w += b.length;
|
|
592
|
+
s.push(b);
|
|
593
|
+
}, s.finish);
|
|
594
|
+
return {
|
|
595
|
+
cpu: dst,
|
|
596
|
+
buf
|
|
597
|
+
};
|
|
598
|
+
};
|
|
599
|
+
device.pushErrorScope("validation");
|
|
473
600
|
device.pushErrorScope("out-of-memory");
|
|
474
601
|
const W = {};
|
|
602
|
+
const zpChecks = [];
|
|
475
603
|
for (const [name, t] of Object.entries(T)) if (t.kind === "q2") {
|
|
476
|
-
const
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
W[name] = {
|
|
604
|
+
const codes = gbuf(t.weight.len * 2);
|
|
605
|
+
wireQ2(t.weight, codes);
|
|
606
|
+
const scales = gbuf(t.scales.len);
|
|
607
|
+
wireRaw(t.scales, scales);
|
|
608
|
+
const w = {
|
|
482
609
|
N: t.N,
|
|
483
610
|
K: t.K,
|
|
484
611
|
nb: t.K / 128,
|
|
485
612
|
zp: 2,
|
|
486
|
-
codes
|
|
487
|
-
scales
|
|
613
|
+
codes,
|
|
614
|
+
scales
|
|
615
|
+
};
|
|
616
|
+
if (t.zp) {
|
|
617
|
+
const zpBytes = wireCpu(t.zp);
|
|
618
|
+
zpChecks.push(() => {
|
|
619
|
+
const b0 = zpBytes[0];
|
|
620
|
+
for (let i = 1; i < zpBytes.length; i++) if (zpBytes[i] !== b0) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points (the q2 kernels assume one zp for the whole tensor)`);
|
|
621
|
+
const zp = b0 & 3;
|
|
622
|
+
if (b0 !== zp * 85) throw new Error(`bitgpu: tensor ${name} has non-uniform 2-bit zero-points within a byte (the q2 kernels assume one zp for the whole tensor)`);
|
|
623
|
+
w.zp = zp;
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
W[name] = w;
|
|
627
|
+
} else if (t.kind === "f32" && t.weight) {
|
|
628
|
+
const buf = gbuf(t.weight.len);
|
|
629
|
+
wireRaw(t.weight, buf);
|
|
630
|
+
W[name] = { buf };
|
|
631
|
+
}
|
|
632
|
+
const fuse = (parts) => {
|
|
633
|
+
const sign = gbuf(parts.reduce((n, p) => n + p.weight.len, 0));
|
|
634
|
+
const scales = gbuf(parts.reduce((n, p) => n + p.scales.len, 0));
|
|
635
|
+
let so = 0;
|
|
636
|
+
let co = 0;
|
|
637
|
+
for (const p of parts) {
|
|
638
|
+
wireSign(p.weight, sign, so);
|
|
639
|
+
so += p.weight.len;
|
|
640
|
+
wireRaw(p.scales, scales, co);
|
|
641
|
+
co += p.scales.len;
|
|
642
|
+
}
|
|
643
|
+
return {
|
|
644
|
+
sign,
|
|
645
|
+
scales
|
|
488
646
|
};
|
|
489
|
-
}
|
|
647
|
+
};
|
|
490
648
|
for (let li = 0; li < A.layers; li++) {
|
|
491
|
-
const q =
|
|
649
|
+
const q = T[`layers.${li}.attn.q_proj`], k = T[`layers.${li}.attn.k_proj`], v = T[`layers.${li}.attn.v_proj`];
|
|
492
650
|
W[`layers.${li}.attn.qkv`] = {
|
|
493
651
|
K: q.K,
|
|
494
|
-
nb: q.
|
|
652
|
+
nb: q.K / 128,
|
|
495
653
|
N0: q.N,
|
|
496
654
|
N1: k.N,
|
|
497
655
|
N2: v.N,
|
|
498
|
-
|
|
499
|
-
q
|
|
500
|
-
k
|
|
501
|
-
v
|
|
502
|
-
])
|
|
503
|
-
scales: upload(concat(Float32Array, [
|
|
504
|
-
q.scales,
|
|
505
|
-
k.scales,
|
|
506
|
-
v.scales
|
|
507
|
-
]))
|
|
656
|
+
...fuse([
|
|
657
|
+
q,
|
|
658
|
+
k,
|
|
659
|
+
v
|
|
660
|
+
])
|
|
508
661
|
};
|
|
509
|
-
const g =
|
|
662
|
+
const g = T[`layers.${li}.mlp.gate_proj`], u = T[`layers.${li}.mlp.up_proj`];
|
|
510
663
|
W[`layers.${li}.mlp.gateup`] = {
|
|
511
664
|
K: g.K,
|
|
512
|
-
nb: g.
|
|
665
|
+
nb: g.K / 128,
|
|
513
666
|
N0: g.N,
|
|
514
667
|
N1: u.N,
|
|
515
668
|
N2: 0,
|
|
516
|
-
|
|
517
|
-
scales: upload(concat(Float32Array, [g.scales, u.scales]))
|
|
669
|
+
...fuse([g, u])
|
|
518
670
|
};
|
|
519
671
|
for (const nm of [`layers.${li}.attn.o_proj`, `layers.${li}.mlp.down_proj`]) {
|
|
520
|
-
const r =
|
|
672
|
+
const r = T[nm];
|
|
521
673
|
W[nm] = {
|
|
522
674
|
N: r.N,
|
|
523
675
|
K: r.K,
|
|
524
|
-
nb: r.
|
|
525
|
-
|
|
526
|
-
scales: upload(r.scales)
|
|
676
|
+
nb: r.K / 128,
|
|
677
|
+
...fuse([r])
|
|
527
678
|
};
|
|
528
679
|
}
|
|
529
680
|
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
const
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
681
|
+
const embW = wireCpuGpu(T.embed_tokens.weight);
|
|
682
|
+
const embS = wireCpuGpu(T.embed_tokens.scales);
|
|
683
|
+
const embZ = wireCpuGpu(T.embed_tokens.zp);
|
|
684
|
+
const tgt4W = wireCpuGpu(manifest.luts.tgt4);
|
|
685
|
+
const cosBytes = wireCpu(T.cos_cache);
|
|
686
|
+
const sinBytes = wireCpu(T.sin_cache);
|
|
687
|
+
const embWq = embW.cpu;
|
|
688
|
+
const embScales = new Float32Array(embS.cpu.buffer);
|
|
689
|
+
const embZp = embZ.cpu;
|
|
690
|
+
const tgt4 = tgt4W.cpu;
|
|
691
|
+
const cosCache = new Float32Array(cosBytes.buffer);
|
|
692
|
+
const sinCache = new Float32Array(sinBytes.buffer);
|
|
693
|
+
const ropePositions = cosCache.length / (A.head_dim / 2);
|
|
694
|
+
if (maxSeqLen > ropePositions) throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's baked RoPE cache (${ropePositions} positions); lower maxSeqLen or re-export with a longer cache`);
|
|
695
|
+
const embWqG = embW.buf, tgt4G = tgt4W.buf, embScalesG = embS.buf, embZpG = embZ.buf;
|
|
696
|
+
routes.sort((a, b) => a.off - b.off || a.len - b.len);
|
|
697
|
+
const merged = [];
|
|
698
|
+
for (const r of routes) {
|
|
699
|
+
const last = merged[merged.length - 1];
|
|
700
|
+
if (last && last.off === r.off && last.len === r.len) {
|
|
701
|
+
const lp = last.push, lf = last.finish;
|
|
702
|
+
last.push = (b) => {
|
|
703
|
+
lp(b);
|
|
704
|
+
r.push(b);
|
|
705
|
+
};
|
|
706
|
+
last.finish = () => {
|
|
707
|
+
lf();
|
|
708
|
+
r.finish();
|
|
709
|
+
};
|
|
710
|
+
} else if (last && r.off < last.off + last.len) throw new Error("bitgpu: partially overlapping data-file tensor ranges (unsupported by the streaming loader)");
|
|
711
|
+
else merged.push(r);
|
|
712
|
+
}
|
|
713
|
+
const needed = merged.length ? merged[merged.length - 1].off + merged[merged.length - 1].len : 0;
|
|
714
|
+
const reader = (opts.fetchStream ? await opts.fetchStream(dataUrl) : opts.fetchArrayBuffer ? new Response(await opts.fetchArrayBuffer(dataUrl)).body : await (async () => {
|
|
715
|
+
const res = await fetch(dataUrl);
|
|
716
|
+
if (!res.ok) throw new Error(`bitgpu: fetch ${dataUrl} failed: HTTP ${res.status}`);
|
|
717
|
+
return res.body ?? new Response(await res.arrayBuffer()).body;
|
|
718
|
+
})()).getReader();
|
|
719
|
+
let cursor = 0;
|
|
720
|
+
let ri = 0;
|
|
721
|
+
for (;;) {
|
|
722
|
+
const { done, value } = await reader.read();
|
|
723
|
+
if (done) break;
|
|
724
|
+
let bo = 0;
|
|
725
|
+
while (bo < value.byteLength && ri < merged.length) {
|
|
726
|
+
const r = merged[ri];
|
|
727
|
+
if (cursor >= r.off + r.len) {
|
|
728
|
+
ri++;
|
|
729
|
+
continue;
|
|
730
|
+
}
|
|
731
|
+
if (cursor < r.off) {
|
|
732
|
+
const skip = Math.min(r.off - cursor, value.byteLength - bo);
|
|
733
|
+
cursor += skip;
|
|
734
|
+
bo += skip;
|
|
735
|
+
continue;
|
|
736
|
+
}
|
|
737
|
+
const n = Math.min(r.off + r.len - cursor, value.byteLength - bo);
|
|
738
|
+
r.push(value.subarray(bo, bo + n));
|
|
739
|
+
cursor += n;
|
|
740
|
+
bo += n;
|
|
741
|
+
if (cursor === r.off + r.len) {
|
|
742
|
+
r.finish();
|
|
743
|
+
ri++;
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
cursor += value.byteLength - bo;
|
|
747
|
+
opts.onProgress?.({
|
|
748
|
+
phase: "weights",
|
|
749
|
+
loaded: Math.min(cursor, needed),
|
|
750
|
+
total: needed
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
if (cursor < needed) throw new Error(`bitgpu: the data file ended at ${cursor} bytes but tensors extend to ${needed}; the download is truncated or the manifest does not match it`);
|
|
754
|
+
for (const check of zpChecks) check();
|
|
755
|
+
zpChecks.length = 0;
|
|
540
756
|
aux = null;
|
|
541
757
|
function embedDequant(ids) {
|
|
542
758
|
const Hh = A.hidden, out = new Float32Array(ids.length * Hh);
|
|
759
|
+
const rowBytes = Hh >> 3, scaleRow = Hh >> 7, zpRow = scaleRow + 1 >> 1;
|
|
543
760
|
for (let r = 0; r < ids.length; r++) {
|
|
544
761
|
const id = ids[r];
|
|
545
|
-
for (let i = 0; i <
|
|
546
|
-
const byte = tgt4[4 * embWq[id *
|
|
762
|
+
for (let i = 0; i < rowBytes; i++) for (let qd = 0; qd < 4; qd++) {
|
|
763
|
+
const byte = tgt4[4 * embWq[id * rowBytes + i] + qd], baseK = (i * 4 + qd) * 2;
|
|
547
764
|
for (let c = 0; c < 2; c++) {
|
|
548
765
|
const k = baseK + c, code = byte >> 4 * c & 15, blk = k / 128 | 0;
|
|
549
|
-
const zp = embZp[id *
|
|
550
|
-
out[r * Hh + k] = (code - zp) * embScales[id *
|
|
766
|
+
const zp = embZp[id * zpRow + (blk / 2 | 0)] >> 4 * (blk & 1) & 15;
|
|
767
|
+
out[r * Hh + k] = (code - zp) * embScales[id * scaleRow + blk];
|
|
551
768
|
}
|
|
552
769
|
}
|
|
553
770
|
}
|
|
@@ -581,7 +798,9 @@ async function createEngine(options) {
|
|
|
581
798
|
}));
|
|
582
799
|
}
|
|
583
800
|
const loadOom = await device.popErrorScope();
|
|
584
|
-
|
|
801
|
+
const loadVal = await device.popErrorScope();
|
|
802
|
+
if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`);
|
|
803
|
+
if (loadVal) throw new Error(`bitgpu: WebGPU validation error while loading weights: ${loadVal.message}`);
|
|
585
804
|
async function ensureKvCapacity(needed) {
|
|
586
805
|
if (needed <= kvCapacity) return;
|
|
587
806
|
const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
|
|
@@ -1139,28 +1358,41 @@ async function createEngine(options) {
|
|
|
1139
1358
|
}
|
|
1140
1359
|
async function forward(ids) {
|
|
1141
1360
|
const S = ids.length;
|
|
1361
|
+
if (S === 0) throw new Error("forward: no tokens to process");
|
|
1362
|
+
if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`);
|
|
1363
|
+
fullHistory = [];
|
|
1142
1364
|
await ensureKvCapacity(S);
|
|
1365
|
+
const vocab = W.lm_head.N;
|
|
1366
|
+
const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
|
|
1143
1367
|
transients = [];
|
|
1144
1368
|
try {
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1369
|
+
for (let off = 0; off < S; off += PREFILL_SEG) {
|
|
1370
|
+
const seg = ids.slice(off, off + PREFILL_SEG);
|
|
1371
|
+
const embedOut = upload(embedDequant(seg), S_ | CD | CS);
|
|
1372
|
+
const enc = device.createCommandEncoder();
|
|
1373
|
+
const { fn, layer0: l0 } = stack(enc, embedOut, seg.length, off);
|
|
1374
|
+
const lg = device.createBuffer({
|
|
1375
|
+
size: seg.length * vocab * 4,
|
|
1376
|
+
usage: S_ | CS
|
|
1377
|
+
});
|
|
1378
|
+
transients.push(lg);
|
|
1379
|
+
const pass = enc.beginComputePass();
|
|
1380
|
+
lmHead(pass, fn, seg.length, lg);
|
|
1381
|
+
pass.end();
|
|
1382
|
+
device.queue.submit([enc.finish()]);
|
|
1383
|
+
await device.queue.onSubmittedWorkDone();
|
|
1384
|
+
embed.set(await readback(embedOut, seg.length * Hd), off * Hd);
|
|
1385
|
+
layer0.set(await readback(l0, seg.length * Hd), off * Hd);
|
|
1386
|
+
finalnorm.set(await readback(fn, seg.length * Hd), off * Hd);
|
|
1387
|
+
logits.set(await readback(lg, seg.length * vocab), off * vocab);
|
|
1388
|
+
flushTransients();
|
|
1389
|
+
}
|
|
1158
1390
|
return {
|
|
1159
|
-
embed
|
|
1160
|
-
layer0
|
|
1161
|
-
finalnorm
|
|
1162
|
-
logits
|
|
1163
|
-
vocab
|
|
1391
|
+
embed,
|
|
1392
|
+
layer0,
|
|
1393
|
+
finalnorm,
|
|
1394
|
+
logits,
|
|
1395
|
+
vocab,
|
|
1164
1396
|
sequenceLength: S
|
|
1165
1397
|
};
|
|
1166
1398
|
} finally {
|
|
@@ -1168,7 +1400,6 @@ async function createEngine(options) {
|
|
|
1168
1400
|
transients = null;
|
|
1169
1401
|
}
|
|
1170
1402
|
}
|
|
1171
|
-
const PREFILL_SEG = 256;
|
|
1172
1403
|
async function runPrefill(ids, posBase, signal) {
|
|
1173
1404
|
let fn = null;
|
|
1174
1405
|
let lastRow = 0;
|
|
@@ -1329,6 +1560,7 @@ async function createEngine(options) {
|
|
|
1329
1560
|
}
|
|
1330
1561
|
async function generateSampledImpl(ids, posBase, nTokens, genOpts, history) {
|
|
1331
1562
|
await ensureKvCapacity(posBase + ids.length + nTokens);
|
|
1563
|
+
const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
|
|
1332
1564
|
const vocab = W.lm_head.N;
|
|
1333
1565
|
const K = Math.max(1, Math.min(genOpts.topK ?? 20, vocab));
|
|
1334
1566
|
const temperature = genOpts.temperature ?? 1;
|
|
@@ -1409,6 +1641,7 @@ async function createEngine(options) {
|
|
|
1409
1641
|
cv
|
|
1410
1642
|
};
|
|
1411
1643
|
};
|
|
1644
|
+
const pick = (ci, cv) => sampled ? sampleFromCandidates(ci, cv, temperature, rng) : ci[0];
|
|
1412
1645
|
transients = [];
|
|
1413
1646
|
try {
|
|
1414
1647
|
const t0 = performance.now();
|
|
@@ -1436,7 +1669,7 @@ async function createEngine(options) {
|
|
|
1436
1669
|
device.queue.submit([encP.finish()]);
|
|
1437
1670
|
await device.queue.onSubmittedWorkDone();
|
|
1438
1671
|
const first = await readCands();
|
|
1439
|
-
const firstTok =
|
|
1672
|
+
const firstTok = pick(first.ci, first.cv);
|
|
1440
1673
|
flushTransients();
|
|
1441
1674
|
const prefillMs = performance.now() - t0;
|
|
1442
1675
|
const gen = [];
|
|
@@ -1489,7 +1722,7 @@ async function createEngine(options) {
|
|
|
1489
1722
|
t = performance.now();
|
|
1490
1723
|
const { ci, cv } = await readCands();
|
|
1491
1724
|
rbMs += performance.now() - t;
|
|
1492
|
-
const tk =
|
|
1725
|
+
const tk = pick(ci, cv);
|
|
1493
1726
|
total += 1;
|
|
1494
1727
|
if (stopSet?.has(tk)) {
|
|
1495
1728
|
stopped = true;
|
|
@@ -1543,6 +1776,7 @@ async function createEngine(options) {
|
|
|
1543
1776
|
const onToken = genOpts.onToken;
|
|
1544
1777
|
const signal = genOpts.signal;
|
|
1545
1778
|
const rng = new MT19937(genOpts.seed);
|
|
1779
|
+
const useChain = sampled || penalty !== 1 || ngramN > 0;
|
|
1546
1780
|
const lg = device.createBuffer({
|
|
1547
1781
|
size: vocab * 4,
|
|
1548
1782
|
usage: S_ | CS | CD
|
|
@@ -1607,7 +1841,7 @@ async function createEngine(options) {
|
|
|
1607
1841
|
pass.dispatchWorkgroups(1);
|
|
1608
1842
|
}
|
|
1609
1843
|
};
|
|
1610
|
-
const rowDraw = (m, j) => sampleFromCandidates(new Uint32Array(m, j * K * 8, K), new Float32Array(m, j * K * 8 + K * 4, K), temperature, rng);
|
|
1844
|
+
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];
|
|
1611
1845
|
transients = [];
|
|
1612
1846
|
try {
|
|
1613
1847
|
const t0 = performance.now();
|
|
@@ -1630,7 +1864,7 @@ async function createEngine(options) {
|
|
|
1630
1864
|
const encP = device.createCommandEncoder();
|
|
1631
1865
|
const lastP = actBuf(Hd);
|
|
1632
1866
|
encP.copyBufferToBuffer(pfx.fn, pfx.lastRow * Hd * 4, lastP, 0, Hd * 4);
|
|
1633
|
-
const pf =
|
|
1867
|
+
const pf = useChain ? writeAffBan(history) : null;
|
|
1634
1868
|
let pass = encP.beginComputePass();
|
|
1635
1869
|
lmHead(pass, lastP, 1, lg);
|
|
1636
1870
|
if (pf) samplerChain(pass, pf.affLen, pf.banLen);
|
|
@@ -1688,7 +1922,7 @@ async function createEngine(options) {
|
|
|
1688
1922
|
lmHead(pass, r.fn, S, lgAll);
|
|
1689
1923
|
pass.end();
|
|
1690
1924
|
SMALLM = 0;
|
|
1691
|
-
if (!
|
|
1925
|
+
if (!useChain) {
|
|
1692
1926
|
for (let j = 0; j < S; j++) {
|
|
1693
1927
|
enc.copyBufferToBuffer(lgAll, j * vocab * 4, lg, 0, vocab * 4);
|
|
1694
1928
|
const p = enc.beginComputePass();
|
|
@@ -1721,7 +1955,7 @@ async function createEngine(options) {
|
|
|
1721
1955
|
gpuMs += performance.now() - t;
|
|
1722
1956
|
t = performance.now();
|
|
1723
1957
|
const emitted = [];
|
|
1724
|
-
if (!
|
|
1958
|
+
if (!useChain) {
|
|
1725
1959
|
const outs = await readbackU32(idsOut, S);
|
|
1726
1960
|
for (let j = 0; j < S; j++) {
|
|
1727
1961
|
const tk = outs[j];
|
|
@@ -1914,6 +2148,7 @@ async function createEngine(options) {
|
|
|
1914
2148
|
};
|
|
1915
2149
|
async function generate(promptTokenIds, genOpts = {}) {
|
|
1916
2150
|
const sampled = genOpts.temperature != null && genOpts.temperature > 0 && genOpts.temperature !== 1;
|
|
2151
|
+
const hasProcessors = (genOpts.repetitionPenalty ?? 1) !== 1 || (genOpts.noRepeatNgramSize ?? 0) > 0;
|
|
1917
2152
|
const reuse = (genOpts.reuseCache ?? false) && fullHistory.length > 0;
|
|
1918
2153
|
if (genOpts.signal?.aborted) return {
|
|
1919
2154
|
tokens: [],
|
|
@@ -1934,16 +2169,40 @@ async function createEngine(options) {
|
|
|
1934
2169
|
const maxTokens = Math.min(genOpts.maxTokens ?? 256, room);
|
|
1935
2170
|
if (reuse) fullHistory.push(...promptTokenIds);
|
|
1936
2171
|
else fullHistory = [...promptTokenIds];
|
|
2172
|
+
if (maxTokens < 1) {
|
|
2173
|
+
await ensureKvCapacity(posBase + prefillTokens.length);
|
|
2174
|
+
transients = [];
|
|
2175
|
+
try {
|
|
2176
|
+
const t0 = performance.now();
|
|
2177
|
+
await runPrefill(prefillTokens, posBase, genOpts.signal);
|
|
2178
|
+
await device.queue.onSubmittedWorkDone();
|
|
2179
|
+
return {
|
|
2180
|
+
tokens: [],
|
|
2181
|
+
prefillMs: performance.now() - t0,
|
|
2182
|
+
decodeMs: 0,
|
|
2183
|
+
tokensPerSecond: 0,
|
|
2184
|
+
timing: {
|
|
2185
|
+
recordMs: 0,
|
|
2186
|
+
gpuMs: 0,
|
|
2187
|
+
readbackMs: 0
|
|
2188
|
+
}
|
|
2189
|
+
};
|
|
2190
|
+
} finally {
|
|
2191
|
+
flushTransients();
|
|
2192
|
+
transients = null;
|
|
2193
|
+
}
|
|
2194
|
+
}
|
|
1937
2195
|
let r;
|
|
1938
2196
|
if (genOpts.promptLookup) r = await generatePldImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
|
|
1939
|
-
else if (sampled) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
|
|
2197
|
+
else if (sampled || hasProcessors) r = await generateSampledImpl(prefillTokens, posBase, maxTokens, genOpts, fullHistory);
|
|
1940
2198
|
else {
|
|
2199
|
+
const hist = fullHistory;
|
|
1941
2200
|
r = await generateImpl(prefillTokens, posBase, maxTokens, null, SYNC_N, {
|
|
1942
2201
|
stopTokens: genOpts.stopTokens,
|
|
1943
2202
|
onToken: genOpts.onToken,
|
|
1944
2203
|
signal: genOpts.signal
|
|
1945
2204
|
});
|
|
1946
|
-
|
|
2205
|
+
hist.push(...r.tokens);
|
|
1947
2206
|
}
|
|
1948
2207
|
return {
|
|
1949
2208
|
tokens: r.tokens,
|