bitgpu 0.10.0 → 0.12.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 +90 -34
- package/dist/chat.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +293 -55
- package/dist/index.js.map +1 -1
- package/dist/{types-CcgsXirU.d.ts → types-Bl0FS_nX.d.ts} +31 -6
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,10 +5,16 @@ const SHADERS = {
|
|
|
5
5
|
"argmax_masked": "// Masked argmax: like argmax.wgsl but skips any id already chosen in a prior round, and writes BOTH\n// the winning id and its logit value. Calling it K times (roundCount = 0..K-1, all in one compute\n// pass so each round sees the prior rounds' writes) yields the exact top-K (id, logit) pairs in\n// descending order = ONNX TopK over the (penalty-filtered) logits, which is what the transformers.js\n// sampler consumes. Then only K pairs are read back (not the full vocab), and the CPU does\n// temperature + softmax + multinomial. Single workgroup, no subgroup ops -> all devices. Tie-break =\n// lowest index (strict >), matching argmax.wgsl / ORT TopK in practice.\noverride WG: u32 = 256u;\nstruct Params { N: u32, roundCount: u32, _0: u32, _1: 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> candIds: array<u32>; // [K]; reads 0..roundCount-1, writes [roundCount]\n@group(0) @binding(3) var<storage, read_write> candVals: array<f32>; // [K]; writes [roundCount]\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) {\n var skip = false;\n for (var r = 0u; r < p.roundCount; r = r + 1u) { if (candIds[r] == i) { skip = true; break; } }\n if (!skip) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { candIds[p.roundCount] = sidx[0]; candVals[p.roundCount] = sval[0]; }\n}\n",
|
|
6
6
|
"attention_sg": "// Causal GQA attention, subgroup-parallel: one subgroup (= one workgroup) per (query, head).\n// Lanes split head_dim; flash-style online softmax over the cached positions; the per-position\n// score (q.k) is reduced with subgroupAdd. Fixes the decode bottleneck where attention ran only\n// H threads. SG = device subgroup size (16/32/64, so head_dim/SG <= 8). Reads K/V from the cache.\nenable subgroups;\noverride SG: u32 = 32u;\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<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\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 let dper = p.D / SG; // <= 8 for SG>=16, D=128\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 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 < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * Kc[kb + d]; }\n let score = subgroupAdd(part) * inv; // full q.k dot, broadcast to all lanes\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 < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
|
|
7
7
|
"attention_sg_kv16": "// attention_sg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_sg.wgsl: the ONLY difference is Kc/Vc are array<f16> and each cached value is\n// widened to f32 at the read. All arithmetic (dot, softmax, accumulation) stays f32, so the\n// precision loss is exactly one rounding of K/V at cache-write time, nothing compounding.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\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]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\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 let dper = p.D / SG;\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 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 < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * f32(Kc[kb + d]); }\n let score = subgroupAdd(part) * inv;\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 < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
|
|
8
|
+
"attention_sg_kv16_roll": "// attention_sg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv16.wgsl: the ONLY\n// difference is the K rotation in the score loop; each cached f16 value is widened to f32 at\n// the read and rotated with the same `k*cos + rot*sin` operand order as rmsnorm_rope_sg.\n// The engine only selects this kernel when SG <= D/2 (partner dim stays in-lane).\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\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] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\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 let dper = p.D / SG;\n let half = p.D / 2u;\n let hs = half / SG; // strides from a dim to its rotate partner\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 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 kd: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = f32(Kc[kb + lane + t * SG]); }\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) {\n let d = lane + t * SG;\n var rot: f32;\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\n }\n let score = subgroupAdd(part) * inv;\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 < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
|
|
8
9
|
"attention_sg_kv8": "// attention_sg with a q8 KV cache (kvCache: 'q8'). Keep in lockstep with attention_sg.wgsl: the\n// ONLY difference is Kc/Vc are packed snorm8 words dequantized at the read with their per-block\n// f32 scales (32-element blocks, q8_0-style; see copy_kv8.wgsl). All arithmetic (dot, softmax,\n// accumulation) stays f32. Each lane owns whole packed words, so q is read in matching groups\n// of 4.\nenable subgroups;\noverride SG: u32 = 32u;\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> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\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 let W4 = p.D / 4u;\n let B32 = p.D / 32u;\n\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = vec4<f32>(0.0); }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * B32;\n var part = 0.0;\n for (var w = lane; w < W4; w = w + SG) {\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\n part = part + dot(qv, kw);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\n acc[wi] = acc[wi] * corr + wgt * vw;\n wi = wi + 1u;\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let o = acc[wi] / l;\n out[ob + w * 4u] = o.x;\n out[ob + w * 4u + 1u] = o.y;\n out[ob + w * 4u + 2u] = o.z;\n out[ob + w * 4u + 3u] = o.w;\n wi = wi + 1u;\n }\n}\n",
|
|
10
|
+
"attention_sg_kv8_roll": "// attention_sg_kv8 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv8.wgsl: the ONLY\n// difference is the K rotation in the score loop. The cache holds UNROPED quantized keys -\n// the whole point: the packed bytes are immutable, so eviction never requantizes (llama.cpp's\n// K-shift cannot do this on a quantized cache at all). A word's rotate partner is the word\n// D/8 away (all 4 dims of a word share one half), dequantized from global with its own scale.\nenable subgroups;\noverride SG: u32 = 32u;\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] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\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 let W4 = p.D / 4u;\n let B32 = p.D / 32u;\n let half = p.D / 2u;\n let hw = half / 4u; // words from a word to its rotate partner\n\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = vec4<f32>(0.0); }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * B32;\n var part = 0.0;\n for (var w = lane; w < W4; w = w + SG) {\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\n let wp = select(w - hw, w + hw, w < hw);\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\n let rot = select(kp, -kp, w < hw);\n let cb = j * half + select(w - hw, w, w < hw) * 4u;\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\n part = part + dot(qv, kw * cs + rot * sn);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\n acc[wi] = acc[wi] * corr + wgt * vw;\n wi = wi + 1u;\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let o = acc[wi] / l;\n out[ob + w * 4u] = o.x;\n out[ob + w * 4u + 1u] = o.y;\n out[ob + w * 4u + 2u] = o.z;\n out[ob + w * 4u + 3u] = o.w;\n wi = wi + 1u;\n }\n}\n",
|
|
11
|
+
"attention_sg_roll": "// attention_sg for the rolling-window / attention-sinks mode (overflow: 'sinks'): the cache\n// holds UNROPED keys, and each cached row j is rotated AT READ by its cache-relative position\n// (StreamingLLM-style; the cache bytes are immutable, so eviction compaction never re-rotates\n// or requantizes anything). Keep in lockstep with attention_sg.wgsl: the ONLY difference is\n// the K rotation in the score loop, written as `k*cos + rot*sin` with the same operand order\n// as rmsnorm_rope_sg so the f32 path stays bit-identical to the roped-at-write kernels until\n// the first eviction. cosT/sinT are the aux rope tables, [positions, D/2].\n// Lane math: d = lane + t*SG, partner d±D/2 is (D/2)/SG strides away IN THE SAME LANE (the\n// engine only selects this kernel when SG <= D/2).\nenable subgroups;\noverride SG: u32 = 32u;\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] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\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 let dper = p.D / SG;\n let half = p.D / 2u;\n let hs = half / SG; // strides from a dim to its rotate partner\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 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 kd: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = Kc[kb + lane + t * SG]; }\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) {\n let d = lane + t * SG;\n var rot: f32;\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\n }\n let score = subgroupAdd(part) * inv;\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 < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
|
|
9
12
|
"attention_wg": "// Causal GQA attention, no-subgroup fallback: one workgroup per (query, head); threads split\n// head_dim; flash-style online softmax over the cached positions; the per-position q.k score\n// is tree-reduced via shared memory. Replaces attention_cache on this path: its single thread\n// per (query, head) walked the WHOLE context serially, so fallback decode degraded linearly\n// with conversation length and prefill attention was latency-bound. Mirrors attention_sg with\n// subgroupAdd swapped for the shared-memory reduction. Fixed workgroup of 64: the per-thread\n// accumulator covers head_dim <= 128 (enforced at manifest validation) in 2 strides.\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<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [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] * 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; // full q.k dot, visible to all threads\n workgroupBarrier(); // red[0] consumed before the next position overwrites it\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 * 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
13
|
"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",
|
|
14
|
+
"attention_wg_kv16_roll": "// attention_wg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_wg_kv16.wgsl: the ONLY\n// differences are the shared-memory K stage (kk, widened to f32) - the rotate partner d±D/2\n// may live in another thread's stride - and the rotation in the score loop, written as\n// `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\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] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\nvar<workgroup> kk: array<f32, 128>;\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 let half = p.D / 2u;\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 for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { kk[d] = f32(Kc[kb + d]); }\n }\n workgroupBarrier();\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) {\n var rot: f32;\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\n }\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(); // red[0] + kk consumed before the next position overwrites them\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",
|
|
11
15
|
"attention_wg_kv8": "// attention_wg with a q8 KV cache (kvCache: 'q8'): the no-subgroup fallback reader for the\n// packed-snorm8 cache (see copy_kv8.wgsl for the write side). Keep in lockstep with\n// attention_wg.wgsl: same online softmax, all arithmetic f32; each thread owns one packed word\n// (D <= 128 -> at most 32 words, so threads 32..63 only carry zeros through the reduction).\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> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) 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 t = 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 let W4 = p.D / 4u;\n\n var qv = vec4<f32>(0.0);\n if (t < W4) {\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\n }\n var acc = vec4<f32>(0.0);\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\n var part = 0.0;\n if (t < W4) {\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\n part = dot(qv, kw);\n }\n red[t] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (t < s) { red[t] = red[t] + red[t + 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 wgt = exp(score - mnew);\n l = l * corr + wgt;\n if (t < W4) {\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\n acc = acc * corr + wgt * vw;\n }\n m = mnew;\n }\n if (t < W4) {\n let ob = (qi * p.H + h) * p.D;\n let o = acc / l;\n out[ob + t * 4u] = o.x;\n out[ob + t * 4u + 1u] = o.y;\n out[ob + t * 4u + 2u] = o.z;\n out[ob + t * 4u + 3u] = o.w;\n }\n}\n",
|
|
16
|
+
"attention_wg_kv8_roll": "// attention_wg_kv8 for the rolling-window / attention-sinks mode: the no-subgroup fallback of\n// attention_sg_kv8_roll (see there and attention_sg_roll.wgsl for the rope-at-read scheme).\n// Keep in lockstep with attention_wg_kv8.wgsl: the ONLY difference is the K rotation in the\n// score loop; each thread's word rotates against its partner word D/8 away, dequantized from\n// global with its own scale.\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] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(8) 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 t = 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 let W4 = p.D / 4u;\n let half = p.D / 2u;\n let hw = half / 4u; // words from a word to its rotate partner\n\n var qv = vec4<f32>(0.0);\n if (t < W4) {\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\n }\n var acc = vec4<f32>(0.0);\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\n var part = 0.0;\n if (t < W4) {\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\n let wp = select(t - hw, t + hw, t < hw);\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\n let rot = select(kp, -kp, t < hw);\n let cb = j * half + select(t - hw, t, t < hw) * 4u;\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\n part = dot(qv, kw * cs + rot * sn);\n }\n red[t] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (t < s) { red[t] = red[t] + red[t + 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 wgt = exp(score - mnew);\n l = l * corr + wgt;\n if (t < W4) {\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\n acc = acc * corr + wgt * vw;\n }\n m = mnew;\n }\n if (t < W4) {\n let ob = (qi * p.H + h) * p.D;\n let o = acc / l;\n out[ob + t * 4u] = o.x;\n out[ob + t * 4u + 1u] = o.y;\n out[ob + t * 4u + 2u] = o.z;\n out[ob + t * 4u + 3u] = o.w;\n }\n}\n",
|
|
17
|
+
"attention_wg_roll": "// attention_wg for the rolling-window / attention-sinks mode: no-subgroup fallback of\n// attention_sg_roll (see there for the rope-at-read scheme). Keep in lockstep with\n// attention_wg.wgsl: the ONLY differences are the shared-memory K stage (kk) - the rotate\n// partner d±D/2 may live in another thread's stride - and the rotation in the score loop,\n// written as `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\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] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\nvar<workgroup> kk: array<f32, 128>;\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 let half = p.D / 2u;\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 for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { kk[d] = Kc[kb + d]; }\n }\n workgroupBarrier();\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) {\n var rot: f32;\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\n }\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; // full q.k dot, visible to all threads\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\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 * 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",
|
|
12
18
|
"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",
|
|
13
19
|
"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",
|
|
14
20
|
"copy_kv8": "// q8 cache append (kvCache: 'q8'): quantize f32 K/V rows into the packed-snorm8 cache, one f32\n// scale per 32-element block (llama.cpp q8_0-style). One 64-thread workgroup per row of D\n// elements: thread t owns packed word t (4 consecutive values), the workgroup reduces per-block\n// absolute maxima through shared memory, then packs with pack4x8snorm. Replaces copy/copy_kv16\n// at every cache-append site under q8. All attention arithmetic stays f32; the precision loss is\n// exactly one snorm8 rounding of K/V at write time, nothing compounding.\nstruct Params { rows: u32, D: u32, dstRow0: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, D]\n@group(0) @binding(2) var<storage, read_write> dstQ: array<u32>; // packed 4 x snorm8 per word\n@group(0) @binding(3) var<storage, read_write> dstS: array<f32>; // [.., D/32] block scales\n\nvar<workgroup> wabs: array<f32, 32>; // per-word abs max (D <= 128 -> at most 32 words)\nvar<workgroup> wblk: array<f32, 4>; // per-block scale (D/32 <= 4 blocks)\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.rows) { return; }\n let t = lid.x;\n let W4 = p.D / 4u;\n let base = row * p.D;\n var v = vec4<f32>(0.0);\n if (t < W4) {\n v = vec4<f32>(src[base + t * 4u], src[base + t * 4u + 1u], src[base + t * 4u + 2u], src[base + t * 4u + 3u]);\n wabs[t] = max(max(abs(v.x), abs(v.y)), max(abs(v.z), abs(v.w)));\n }\n workgroupBarrier();\n if (t < p.D / 32u) {\n var m = 0.0;\n for (var i = 0u; i < 8u; i = i + 1u) { m = max(m, wabs[t * 8u + i]); }\n let s = max(m, 1e-30); // an all-zero block packs zeros, never NaN\n wblk[t] = s;\n dstS[(p.dstRow0 + row) * (p.D / 32u) + t] = s;\n }\n workgroupBarrier();\n if (t < W4) {\n dstQ[(p.dstRow0 + row) * W4 + t] = pack4x8snorm(v / wblk[t >> 3u]);\n }\n}\n",
|
|
@@ -228,6 +234,38 @@ const eqBytes = (a, b) => {
|
|
|
228
234
|
for (let i = 0; i < b.length; i++) if (a[i] !== b[i]) return false;
|
|
229
235
|
return true;
|
|
230
236
|
};
|
|
237
|
+
/** Synthesize f32 rope tables ([positions, head_dim/2]) from arch.rope for manifests without
|
|
238
|
+
* baked caches (v2/GGUF). Plain rope or YaRN (transformers formula: beta_fast 32, beta_slow 1,
|
|
239
|
+
* mscale = 0.1*ln(factor)+1). Angles accumulate in f64 and round once to f32 per entry -
|
|
240
|
+
* tools/reference.py implements the identical recipe for fixture generation. */
|
|
241
|
+
function synthRope(A, positions) {
|
|
242
|
+
const half = A.head_dim / 2;
|
|
243
|
+
const rope = A.rope;
|
|
244
|
+
const base = rope.rope_theta;
|
|
245
|
+
const factor = rope.rope_type === "yarn" ? rope.factor ?? 1 : 1;
|
|
246
|
+
const inv = new Float64Array(half);
|
|
247
|
+
const orig = rope.original_max_position_embeddings ?? 0;
|
|
248
|
+
const lo = factor === 1 ? 0 : Math.max(0, Math.floor(A.head_dim * Math.log(orig / (64 * Math.PI)) / (2 * Math.log(base))));
|
|
249
|
+
const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil(A.head_dim * Math.log(orig / (2 * Math.PI)) / (2 * Math.log(base))));
|
|
250
|
+
for (let j = 0; j < half; j++) {
|
|
251
|
+
const pf = base ** (2 * j / A.head_dim);
|
|
252
|
+
if (factor === 1) {
|
|
253
|
+
inv[j] = 1 / pf;
|
|
254
|
+
continue;
|
|
255
|
+
}
|
|
256
|
+
const ramp = Math.min(1, Math.max(0, (j - lo) / (hi - lo)));
|
|
257
|
+
inv[j] = 1 / (factor * pf) * ramp + 1 / pf * (1 - ramp);
|
|
258
|
+
}
|
|
259
|
+
const mscale = factor === 1 ? 1 : Math.fround(.1 * Math.log(factor) + 1);
|
|
260
|
+
const cos = new Float32Array(positions * half);
|
|
261
|
+
const sin = new Float32Array(positions * half);
|
|
262
|
+
for (let p = 0; p < positions; p++) for (let j = 0; j < half; j++) {
|
|
263
|
+
const a = p * inv[j];
|
|
264
|
+
cos[p * half + j] = Math.fround(Math.cos(a) * mscale);
|
|
265
|
+
sin[p * half + j] = Math.fround(Math.sin(a) * mscale);
|
|
266
|
+
}
|
|
267
|
+
return [cos, sin];
|
|
268
|
+
}
|
|
231
269
|
/** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
|
|
232
270
|
async function createEngine(options) {
|
|
233
271
|
const holder = {};
|
|
@@ -289,8 +327,33 @@ async function createEngineInner(options, holder) {
|
|
|
289
327
|
if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim} (kernels assume <= 128)`);
|
|
290
328
|
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)`);
|
|
291
329
|
if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
|
|
292
|
-
if (
|
|
293
|
-
|
|
330
|
+
if (manifest.version !== void 0 && manifest.version !== 1 && manifest.version !== 2) throw new Error(`bitgpu: unsupported manifest version ${manifest.version} (this engine reads versions 1 and 2)`);
|
|
331
|
+
if (!T.cos_cache !== !T.sin_cache) throw new Error("bitgpu: manifest has only one of cos_cache/sin_cache");
|
|
332
|
+
if (!T.cos_cache && !(A.rope && A.rope.rope_theta)) throw new Error("bitgpu: manifest has neither baked cos_cache/sin_cache RoPE tensors nor arch.rope parameters");
|
|
333
|
+
for (const [name, t] of Object.entries(T)) {
|
|
334
|
+
if (t.block !== void 0 && t.block !== 128) throw new Error(`bitgpu: tensor ${name} has block ${t.block} (kernels assume 128)`);
|
|
335
|
+
if (t.container === void 0) continue;
|
|
336
|
+
if (t.container !== "q1_0") throw new Error(`bitgpu: tensor ${name} has unknown container '${t.container}'`);
|
|
337
|
+
const N = t.N ?? t.rows;
|
|
338
|
+
const K = t.K ?? t.cols;
|
|
339
|
+
if (!N || !K || K % 128 !== 0) throw new Error(`bitgpu: tensor ${name}: q1_0 container needs N/K (or rows/cols) with K a multiple of 128`);
|
|
340
|
+
const r = t.weight;
|
|
341
|
+
if (!r || r.src !== "data" || r.len !== N * (K / 128) * 18) throw new Error(`bitgpu: tensor ${name}: q1_0 region is ${r?.len} bytes in '${r?.src}', expected ${N * (K / 128) * 18} in the data file`);
|
|
342
|
+
t.q1_0 = r;
|
|
343
|
+
t.weight = {
|
|
344
|
+
dtype: "UINT8",
|
|
345
|
+
src: r.src,
|
|
346
|
+
off: r.off,
|
|
347
|
+
len: N * (K / 8)
|
|
348
|
+
};
|
|
349
|
+
t.scales = {
|
|
350
|
+
dtype: "FLOAT",
|
|
351
|
+
src: r.src,
|
|
352
|
+
off: r.off,
|
|
353
|
+
len: N * (K / 128) * 4
|
|
354
|
+
};
|
|
355
|
+
t.zp = void 0;
|
|
356
|
+
}
|
|
294
357
|
const readRef = (ref) => {
|
|
295
358
|
if (ref.src !== "aux") throw new Error("bitgpu: internal - readRef reads aux-file refs; data-file tensors stream through routes");
|
|
296
359
|
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`);
|
|
@@ -317,6 +380,9 @@ async function createEngineInner(options, holder) {
|
|
|
317
380
|
const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
|
|
318
381
|
const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
|
|
319
382
|
const kv8 = opts.kvCache === "q8";
|
|
383
|
+
const roll = opts.overflow === "sinks";
|
|
384
|
+
const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0;
|
|
385
|
+
if (roll && maxSeqLen < SINKS + 64) throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`);
|
|
320
386
|
const KVB = kv16 ? 2 : kv8 ? 1 : 4;
|
|
321
387
|
const features = [];
|
|
322
388
|
if (useSG) features.push("subgroups");
|
|
@@ -351,12 +417,13 @@ async function createEngineInner(options, holder) {
|
|
|
351
417
|
track(fusedLen(g, "scales"));
|
|
352
418
|
}
|
|
353
419
|
}
|
|
420
|
+
const embZpLen = T.embed_tokens.zp?.len ?? T.embed_tokens.rows * (T.embed_tokens.cols / 128) / 2;
|
|
354
421
|
for (const r of [
|
|
355
422
|
T.embed_tokens.weight,
|
|
356
423
|
T.embed_tokens.scales,
|
|
357
|
-
T.embed_tokens.zp,
|
|
358
424
|
manifest.luts.tgt4
|
|
359
425
|
]) track(r.len);
|
|
426
|
+
track(embZpLen);
|
|
360
427
|
if (kv8 && A.head_dim % 32 !== 0) throw new Error(`bitgpu: kvCache 'q8' needs head_dim divisible by 32 (got ${A.head_dim}); use 'f16' or 'f32' for this model`);
|
|
361
428
|
const kvLayerBytes = maxSeqLen * A.kv_heads * A.head_dim * KVB;
|
|
362
429
|
needBind = Math.max(needBind, kvLayerBytes, PREFILL_SEG * Math.max(A.heads * A.head_dim, A.intermediate) * 4, 32 * A.vocab * 4);
|
|
@@ -453,7 +520,14 @@ async function createEngineInner(options, holder) {
|
|
|
453
520
|
if (useSG) for (const n of ["attention_sg_kv8", "rmsnorm_rope_sg_kv8"]) specs.push([n, { SG: sgMax }]);
|
|
454
521
|
else specs.push(["attention_wg_kv8"]);
|
|
455
522
|
}
|
|
456
|
-
const
|
|
523
|
+
const rollSG = useSG && sgMax <= A.head_dim / 2;
|
|
524
|
+
if (roll) {
|
|
525
|
+
const rollAtt = kv16 ? "attention_sg_kv16_roll" : kv8 ? "attention_sg_kv8_roll" : "attention_sg_roll";
|
|
526
|
+
const rollAttWg = kv16 ? "attention_wg_kv16_roll" : kv8 ? "attention_wg_kv8_roll" : "attention_wg_roll";
|
|
527
|
+
if (rollSG) specs.push([rollAtt, { SG: sgMax }]);
|
|
528
|
+
else specs.push([rollAttWg]);
|
|
529
|
+
}
|
|
530
|
+
const ATT = roll ? kv16 ? rollSG ? "attention_sg_kv16_roll" : "attention_wg_kv16_roll" : kv8 ? rollSG ? "attention_sg_kv8_roll" : "attention_wg_kv8_roll" : rollSG ? "attention_sg_roll" : "attention_wg_roll" : kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : kv8 ? useSG ? "attention_sg_kv8" : "attention_wg_kv8" : useSG ? "attention_sg" : "attention_wg";
|
|
457
531
|
const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
|
|
458
532
|
const COPY_KV = kv16 ? "copy_kv16" : "copy";
|
|
459
533
|
await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
|
|
@@ -521,8 +595,10 @@ async function createEngineInner(options, holder) {
|
|
|
521
595
|
usage: S_
|
|
522
596
|
});
|
|
523
597
|
let fullHistory = [];
|
|
598
|
+
let cacheLen = 0;
|
|
524
599
|
const resetCache = () => {
|
|
525
600
|
fullHistory = [];
|
|
601
|
+
cacheLen = 0;
|
|
526
602
|
};
|
|
527
603
|
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)");
|
|
528
604
|
const tgt2 = readU8(manifest.luts.tgt2);
|
|
@@ -578,24 +654,65 @@ async function createEngineInner(options, holder) {
|
|
|
578
654
|
const s = gpuSink(buf, base);
|
|
579
655
|
wire(ref, s.push, s.finish);
|
|
580
656
|
};
|
|
657
|
+
const xfSign = (push) => (b) => {
|
|
658
|
+
const o = new Uint8Array(b.length);
|
|
659
|
+
for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]];
|
|
660
|
+
push(o);
|
|
661
|
+
};
|
|
662
|
+
const xfQ2 = (push) => (b) => {
|
|
663
|
+
const o = new Uint8Array(b.length * 2);
|
|
664
|
+
for (let i = 0; i < b.length; i++) {
|
|
665
|
+
o[2 * i] = tgt2[2 * b[i]];
|
|
666
|
+
o[2 * i + 1] = tgt2[2 * b[i] + 1];
|
|
667
|
+
}
|
|
668
|
+
push(o);
|
|
669
|
+
};
|
|
581
670
|
const wireSign = (ref, buf, base = 0) => {
|
|
582
671
|
const s = gpuSink(buf, base);
|
|
583
|
-
wire(ref, (
|
|
584
|
-
const o = new Uint8Array(b.length);
|
|
585
|
-
for (let i = 0; i < b.length; i++) o[i] = signTable[b[i]];
|
|
586
|
-
s.push(o);
|
|
587
|
-
}, s.finish);
|
|
672
|
+
wire(ref, xfSign(s.push), s.finish);
|
|
588
673
|
};
|
|
589
674
|
const wireQ2 = (ref, buf) => {
|
|
590
675
|
const s = gpuSink(buf, 0);
|
|
591
|
-
wire(ref, (
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
676
|
+
wire(ref, xfQ2(s.push), s.finish);
|
|
677
|
+
};
|
|
678
|
+
const f16f32 = (h) => {
|
|
679
|
+
const s = h & 32768 ? -1 : 1;
|
|
680
|
+
const e = h >> 10 & 31;
|
|
681
|
+
const m = h & 1023;
|
|
682
|
+
if (e === 0) return s * m * 2 ** -24;
|
|
683
|
+
if (e === 31) return m ? NaN : s * Infinity;
|
|
684
|
+
return s * (1024 + m) * 2 ** (e - 25);
|
|
685
|
+
};
|
|
686
|
+
const wireQ10 = (region, signPush, signFinish, scalePush, scaleFinish) => {
|
|
687
|
+
let phase = 0;
|
|
688
|
+
let scaleLo = 0;
|
|
689
|
+
const push = (b) => {
|
|
690
|
+
const signs = new Uint8Array(b.length);
|
|
691
|
+
const scales = new Float32Array((b.length >> 4) + 2);
|
|
692
|
+
let sn = 0;
|
|
693
|
+
let cn = 0;
|
|
694
|
+
for (let i = 0; i < b.length; i++) if (phase === 0) {
|
|
695
|
+
scaleLo = b[i];
|
|
696
|
+
phase = 1;
|
|
697
|
+
} else if (phase === 1) {
|
|
698
|
+
scales[cn++] = f16f32(scaleLo | b[i] << 8);
|
|
699
|
+
phase = 2;
|
|
700
|
+
} else {
|
|
701
|
+
signs[sn++] = b[i];
|
|
702
|
+
phase = phase === 17 ? 0 : phase + 1;
|
|
703
|
+
}
|
|
704
|
+
if (sn) signPush(signs.subarray(0, sn));
|
|
705
|
+
if (cn) scalePush(new Uint8Array(scales.buffer, 0, cn * 4));
|
|
706
|
+
};
|
|
707
|
+
routes.push({
|
|
708
|
+
off: region.off,
|
|
709
|
+
len: region.len,
|
|
710
|
+
push,
|
|
711
|
+
finish: () => {
|
|
712
|
+
signFinish();
|
|
713
|
+
scaleFinish();
|
|
596
714
|
}
|
|
597
|
-
|
|
598
|
-
}, s.finish);
|
|
715
|
+
});
|
|
599
716
|
};
|
|
600
717
|
const wireCpu = (ref) => {
|
|
601
718
|
const dst = new Uint8Array(ref.len);
|
|
@@ -612,9 +729,15 @@ async function createEngineInner(options, holder) {
|
|
|
612
729
|
const zpChecks = [];
|
|
613
730
|
for (const [name, t] of Object.entries(T)) if (t.kind === "q2") {
|
|
614
731
|
const codes = gbuf(t.weight.len * 2);
|
|
615
|
-
wireQ2(t.weight, codes);
|
|
616
732
|
const scales = gbuf(t.scales.len);
|
|
617
|
-
|
|
733
|
+
if (t.q1_0) {
|
|
734
|
+
const cs = gpuSink(codes, 0);
|
|
735
|
+
const ss = gpuSink(scales, 0);
|
|
736
|
+
wireQ10(t.q1_0, xfQ2(cs.push), cs.finish, ss.push, ss.finish);
|
|
737
|
+
} else {
|
|
738
|
+
wireQ2(t.weight, codes);
|
|
739
|
+
wireRaw(t.scales, scales);
|
|
740
|
+
}
|
|
618
741
|
const w = {
|
|
619
742
|
N: t.N,
|
|
620
743
|
K: t.K,
|
|
@@ -645,9 +768,15 @@ async function createEngineInner(options, holder) {
|
|
|
645
768
|
let so = 0;
|
|
646
769
|
let co = 0;
|
|
647
770
|
for (const p of parts) {
|
|
648
|
-
|
|
771
|
+
if (p.q1_0) {
|
|
772
|
+
const ws = gpuSink(sign, so);
|
|
773
|
+
const ss = gpuSink(scales, co);
|
|
774
|
+
wireQ10(p.q1_0, xfSign(ws.push), ws.finish, ss.push, ss.finish);
|
|
775
|
+
} else {
|
|
776
|
+
wireSign(p.weight, sign, so);
|
|
777
|
+
wireRaw(p.scales, scales, co);
|
|
778
|
+
}
|
|
649
779
|
so += p.weight.len;
|
|
650
|
-
wireRaw(p.scales, scales, co);
|
|
651
780
|
co += p.scales.len;
|
|
652
781
|
}
|
|
653
782
|
return {
|
|
@@ -693,16 +822,37 @@ async function createEngineInner(options, holder) {
|
|
|
693
822
|
wireRaw(ref, buf);
|
|
694
823
|
return buf;
|
|
695
824
|
};
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
825
|
+
let embWqG;
|
|
826
|
+
let embScalesG;
|
|
827
|
+
let embZpG;
|
|
828
|
+
if (T.embed_tokens.q1_0) {
|
|
829
|
+
embWqG = gbuf(T.embed_tokens.weight.len);
|
|
830
|
+
embScalesG = gbuf(T.embed_tokens.scales.len);
|
|
831
|
+
const ws = gpuSink(embWqG, 0);
|
|
832
|
+
const ss = gpuSink(embScalesG, 0);
|
|
833
|
+
wireQ10(T.embed_tokens.q1_0, ws.push, ws.finish, ss.push, ss.finish);
|
|
834
|
+
embZpG = gbuf(embZpLen);
|
|
835
|
+
device.queue.writeBuffer(embZpG, 0, new Uint8Array(embZpLen + 3 & -4).fill(136));
|
|
836
|
+
} else {
|
|
837
|
+
embWqG = wireGpu(T.embed_tokens.weight);
|
|
838
|
+
embScalesG = wireGpu(T.embed_tokens.scales);
|
|
839
|
+
embZpG = wireGpu(T.embed_tokens.zp);
|
|
840
|
+
}
|
|
699
841
|
const tgt4G = wireGpu(manifest.luts.tgt4);
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
842
|
+
let cosCache;
|
|
843
|
+
let sinCache;
|
|
844
|
+
if (T.cos_cache) {
|
|
845
|
+
const cosBytes = wireCpu(T.cos_cache);
|
|
846
|
+
const sinBytes = wireCpu(T.sin_cache);
|
|
847
|
+
cosCache = new Float32Array(cosBytes.buffer);
|
|
848
|
+
sinCache = new Float32Array(sinBytes.buffer);
|
|
849
|
+
const ropePositions = cosCache.length / (A.head_dim / 2);
|
|
850
|
+
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`);
|
|
851
|
+
} else {
|
|
852
|
+
const cap = A.max_positions ?? 40960;
|
|
853
|
+
if (maxSeqLen > cap) throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's max_positions (${cap})`);
|
|
854
|
+
[cosCache, sinCache] = synthRope(A, maxSeqLen);
|
|
855
|
+
}
|
|
706
856
|
routes.sort((a, b) => a.off - b.off || a.len - b.len);
|
|
707
857
|
const merged = [];
|
|
708
858
|
for (const r of routes) {
|
|
@@ -822,6 +972,30 @@ async function createEngineInner(options, holder) {
|
|
|
822
972
|
}));
|
|
823
973
|
}
|
|
824
974
|
}
|
|
975
|
+
let rollCosT = null, rollSinT = null, rollOnes = null, rollZeros = null;
|
|
976
|
+
if (roll) {
|
|
977
|
+
const R2 = Dh / 2;
|
|
978
|
+
rollCosT = device.createBuffer({
|
|
979
|
+
size: maxSeqLen * R2 * 4,
|
|
980
|
+
usage: S_ | CD
|
|
981
|
+
});
|
|
982
|
+
rollSinT = device.createBuffer({
|
|
983
|
+
size: maxSeqLen * R2 * 4,
|
|
984
|
+
usage: S_ | CD
|
|
985
|
+
});
|
|
986
|
+
device.queue.writeBuffer(rollCosT, 0, cosCache.buffer, cosCache.byteOffset, maxSeqLen * R2 * 4);
|
|
987
|
+
device.queue.writeBuffer(rollSinT, 0, sinCache.buffer, sinCache.byteOffset, maxSeqLen * R2 * 4);
|
|
988
|
+
rollOnes = device.createBuffer({
|
|
989
|
+
size: Dh * 4,
|
|
990
|
+
usage: S_ | CD
|
|
991
|
+
});
|
|
992
|
+
rollZeros = device.createBuffer({
|
|
993
|
+
size: Dh * 4,
|
|
994
|
+
usage: S_ | CD
|
|
995
|
+
});
|
|
996
|
+
device.queue.writeBuffer(rollOnes, 0, new Float32Array(Dh).fill(1));
|
|
997
|
+
device.queue.writeBuffer(rollZeros, 0, new Float32Array(Dh));
|
|
998
|
+
}
|
|
825
999
|
const loadOom = await device.popErrorScope();
|
|
826
1000
|
const loadVal = await device.popErrorScope();
|
|
827
1001
|
if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`);
|
|
@@ -888,6 +1062,35 @@ async function createEngineInner(options, holder) {
|
|
|
888
1062
|
kvCapacity = newCap;
|
|
889
1063
|
poolInvalidate();
|
|
890
1064
|
}
|
|
1065
|
+
let evictScratch = null;
|
|
1066
|
+
function evict(fill, need) {
|
|
1067
|
+
const recent = fill - SINKS;
|
|
1068
|
+
const batch = Math.min(recent, Math.max(need, Math.ceil((maxSeqLen - SINKS) / 4)));
|
|
1069
|
+
const keep = recent - batch;
|
|
1070
|
+
if (keep <= 0) return SINKS;
|
|
1071
|
+
const rowK = KV * Dh * KVB;
|
|
1072
|
+
const rowS = kv8 ? KV * (Dh / 32) * 4 : 0;
|
|
1073
|
+
if (!evictScratch || evictScratch.size < keep * rowK) {
|
|
1074
|
+
evictScratch?.destroy();
|
|
1075
|
+
evictScratch = device.createBuffer({
|
|
1076
|
+
size: keep * rowK,
|
|
1077
|
+
usage: CS | CD
|
|
1078
|
+
});
|
|
1079
|
+
}
|
|
1080
|
+
const enc = device.createCommandEncoder();
|
|
1081
|
+
const groups = [];
|
|
1082
|
+
for (let li = 0; li < A.layers; li++) {
|
|
1083
|
+
groups.push([Kc[li], rowK], [Vc[li], rowK]);
|
|
1084
|
+
if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS]);
|
|
1085
|
+
}
|
|
1086
|
+
for (const [buf, row] of groups) {
|
|
1087
|
+
enc.copyBufferToBuffer(buf, (SINKS + batch) * row, evictScratch, 0, keep * row);
|
|
1088
|
+
enc.copyBufferToBuffer(evictScratch, 0, buf, SINKS * row, keep * row);
|
|
1089
|
+
}
|
|
1090
|
+
device.queue.submit([enc.finish()]);
|
|
1091
|
+
return SINKS + keep;
|
|
1092
|
+
}
|
|
1093
|
+
const evictFor = (fill, n) => roll && fill + n > maxSeqLen ? evict(fill, fill + n - maxSeqLen) : fill;
|
|
891
1094
|
async function readback(buf, n) {
|
|
892
1095
|
const rb = device.createBuffer({
|
|
893
1096
|
size: n * 4,
|
|
@@ -1175,17 +1378,21 @@ async function createEngineInner(options, holder) {
|
|
|
1175
1378
|
["u", 0]
|
|
1176
1379
|
], [src], data, rows * Dh);
|
|
1177
1380
|
}
|
|
1178
|
-
const attIns = (qr, li) =>
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1381
|
+
const attIns = (qr, li) => {
|
|
1382
|
+
const ins = kv8 ? [
|
|
1383
|
+
qr,
|
|
1384
|
+
Kc[li],
|
|
1385
|
+
Vc[li],
|
|
1386
|
+
Ksc[li],
|
|
1387
|
+
Vsc[li]
|
|
1388
|
+
] : [
|
|
1389
|
+
qr,
|
|
1390
|
+
Kc[li],
|
|
1391
|
+
Vc[li]
|
|
1392
|
+
];
|
|
1393
|
+
if (roll) ins.push(rollCosT, rollSinT);
|
|
1394
|
+
return ins;
|
|
1395
|
+
};
|
|
1189
1396
|
function layer(pass, li, h, S, posBase, cos, sin) {
|
|
1190
1397
|
const Ltot = posBase + S;
|
|
1191
1398
|
const n1 = actBuf(S * Hd);
|
|
@@ -1225,6 +1432,7 @@ async function createEngineInner(options, holder) {
|
|
|
1225
1432
|
cos,
|
|
1226
1433
|
sin
|
|
1227
1434
|
], qr, H);
|
|
1435
|
+
const kcos = roll ? rollOnes : cos, ksin = roll ? rollZeros : sin;
|
|
1228
1436
|
if (kv8) {
|
|
1229
1437
|
setup(pass, "rmsnorm_rope_sg_kv8", [
|
|
1230
1438
|
["u", KV],
|
|
@@ -1236,8 +1444,8 @@ async function createEngineInner(options, holder) {
|
|
|
1236
1444
|
], [
|
|
1237
1445
|
k,
|
|
1238
1446
|
W[`layers.${li}.attn.k_norm`].buf,
|
|
1239
|
-
|
|
1240
|
-
|
|
1447
|
+
kcos,
|
|
1448
|
+
ksin
|
|
1241
1449
|
], [Kc[li], Ksc[li]]);
|
|
1242
1450
|
pass.dispatchWorkgroups(isFull("rmsnorm_rope_sg_kv8") ? KV : 1);
|
|
1243
1451
|
} else runN(pass, ROPE_K, [
|
|
@@ -1250,8 +1458,8 @@ async function createEngineInner(options, holder) {
|
|
|
1250
1458
|
], [
|
|
1251
1459
|
k,
|
|
1252
1460
|
W[`layers.${li}.attn.k_norm`].buf,
|
|
1253
|
-
|
|
1254
|
-
|
|
1461
|
+
kcos,
|
|
1462
|
+
ksin
|
|
1255
1463
|
], Kc[li], KV);
|
|
1256
1464
|
cap(li, "qr", qr);
|
|
1257
1465
|
const att = actBuf(H * Dh);
|
|
@@ -1306,7 +1514,7 @@ async function createEngineInner(options, holder) {
|
|
|
1306
1514
|
cos,
|
|
1307
1515
|
sin
|
|
1308
1516
|
], qr, S * H * Dh);
|
|
1309
|
-
run(pass, "rope", [
|
|
1517
|
+
if (!roll) run(pass, "rope", [
|
|
1310
1518
|
["u", S],
|
|
1311
1519
|
["u", KV],
|
|
1312
1520
|
["u", Dh],
|
|
@@ -1316,7 +1524,7 @@ async function createEngineInner(options, holder) {
|
|
|
1316
1524
|
cos,
|
|
1317
1525
|
sin
|
|
1318
1526
|
], kr, S * KV * Dh);
|
|
1319
|
-
appendKV(pass, kr, 0, li, S * KV, posBase * KV);
|
|
1527
|
+
appendKV(pass, roll ? kn : kr, 0, li, S * KV, posBase * KV);
|
|
1320
1528
|
appendKV(pass, v, 1, li, S * KV, posBase * KV);
|
|
1321
1529
|
cap(li, "qr", qr);
|
|
1322
1530
|
const att = actBuf(S * H * Dh);
|
|
@@ -1429,6 +1637,7 @@ async function createEngineInner(options, holder) {
|
|
|
1429
1637
|
if (S === 0) throw new Error("forward: no tokens to process");
|
|
1430
1638
|
if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`);
|
|
1431
1639
|
fullHistory = [];
|
|
1640
|
+
cacheLen = 0;
|
|
1432
1641
|
await ensureKvCapacity(S);
|
|
1433
1642
|
const vocab = W.lm_head.N;
|
|
1434
1643
|
const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
|
|
@@ -1474,6 +1683,7 @@ async function createEngineInner(options, holder) {
|
|
|
1474
1683
|
for (let off = 0; off < ids.length; off += PREFILL_SEG) {
|
|
1475
1684
|
if (off > 0 && signal?.aborted) {
|
|
1476
1685
|
fullHistory = [];
|
|
1686
|
+
cacheLen = 0;
|
|
1477
1687
|
return null;
|
|
1478
1688
|
}
|
|
1479
1689
|
const seg = ids.slice(off, off + PREFILL_SEG);
|
|
@@ -1551,14 +1761,16 @@ async function createEngineInner(options, holder) {
|
|
|
1551
1761
|
ctl?.onToken?.(firstTok);
|
|
1552
1762
|
}
|
|
1553
1763
|
poolInvalidate();
|
|
1764
|
+
let slot = posBase + ids.length;
|
|
1554
1765
|
while (total < nTokens && !stopped) {
|
|
1555
1766
|
if (ctl?.signal?.aborted) break;
|
|
1556
1767
|
const batch = Math.min(syncN, nTokens - total);
|
|
1768
|
+
slot = evictFor(slot, batch);
|
|
1557
1769
|
poolUse("decode");
|
|
1558
1770
|
let t = performance.now();
|
|
1559
1771
|
const enc = device.createCommandEncoder();
|
|
1560
1772
|
for (let j = 0; j < batch; j++) {
|
|
1561
|
-
const idxOut = total + j, pos =
|
|
1773
|
+
const idxOut = total + j, pos = slot + j;
|
|
1562
1774
|
let pass = enc.beginComputePass();
|
|
1563
1775
|
runN(pass, "embed_gather", [
|
|
1564
1776
|
["u", Hd],
|
|
@@ -1594,17 +1806,21 @@ async function createEngineInner(options, holder) {
|
|
|
1594
1806
|
t = performance.now();
|
|
1595
1807
|
const toks = await readbackU32(tokBuf, total + batch);
|
|
1596
1808
|
rbMs += performance.now() - t;
|
|
1809
|
+
let fed = batch;
|
|
1597
1810
|
for (let j = 0; j < batch; j++) {
|
|
1598
1811
|
const tk = toks[total + j];
|
|
1599
1812
|
if (stopSet?.has(tk)) {
|
|
1600
1813
|
stopped = true;
|
|
1814
|
+
fed = j;
|
|
1601
1815
|
break;
|
|
1602
1816
|
}
|
|
1603
1817
|
gen.push(tk);
|
|
1604
1818
|
ctl?.onToken?.(tk);
|
|
1605
1819
|
}
|
|
1606
1820
|
total += batch;
|
|
1821
|
+
slot += fed;
|
|
1607
1822
|
}
|
|
1823
|
+
cacheLen = slot;
|
|
1608
1824
|
const decodeMs = performance.now() - t1, nd = Math.max(1, gen.length - 1);
|
|
1609
1825
|
return {
|
|
1610
1826
|
prefillMs,
|
|
@@ -1832,10 +2048,12 @@ async function createEngineInner(options, holder) {
|
|
|
1832
2048
|
const t1 = performance.now();
|
|
1833
2049
|
let total = 1;
|
|
1834
2050
|
poolInvalidate();
|
|
2051
|
+
let slot = posBase + ids.length;
|
|
1835
2052
|
while (total < nTokens && !stopped) {
|
|
1836
2053
|
if (signal?.aborted) break;
|
|
1837
2054
|
poolUse("decode");
|
|
1838
|
-
|
|
2055
|
+
slot = evictFor(slot, 1);
|
|
2056
|
+
const idxOut = total, pos = slot;
|
|
1839
2057
|
let t = performance.now();
|
|
1840
2058
|
const { affLen, banLen } = writeAffBan(history);
|
|
1841
2059
|
const enc = device.createCommandEncoder();
|
|
@@ -1879,7 +2097,9 @@ async function createEngineInner(options, holder) {
|
|
|
1879
2097
|
recordLp(ci, cv, lse);
|
|
1880
2098
|
onToken?.(tk);
|
|
1881
2099
|
device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk]));
|
|
2100
|
+
slot += 1;
|
|
1882
2101
|
}
|
|
2102
|
+
cacheLen = slot;
|
|
1883
2103
|
const decodeMs = performance.now() - t1;
|
|
1884
2104
|
const nd = Math.max(1, gen.length - 1);
|
|
1885
2105
|
return {
|
|
@@ -2061,6 +2281,7 @@ async function createEngineInner(options, holder) {
|
|
|
2061
2281
|
const t1 = performance.now();
|
|
2062
2282
|
while (total < nTokens && !stopped) {
|
|
2063
2283
|
if (signal?.aborted) break;
|
|
2284
|
+
pos = evictFor(pos, maxDraft + 1);
|
|
2064
2285
|
const kMax = Math.min(maxDraft, nTokens - total - 1, maxSeqLen - 1 - pos);
|
|
2065
2286
|
const drafts = kMax > 0 ? draftNgram(history, ngramSize, kMax) : [];
|
|
2066
2287
|
const S = drafts.length + 1;
|
|
@@ -2164,6 +2385,7 @@ async function createEngineInner(options, holder) {
|
|
|
2164
2385
|
pos += emitted.length;
|
|
2165
2386
|
tLast = emitted[emitted.length - 1];
|
|
2166
2387
|
}
|
|
2388
|
+
cacheLen = pos;
|
|
2167
2389
|
const decodeMs = performance.now() - t1;
|
|
2168
2390
|
const nd = Math.max(1, gen.length - 1);
|
|
2169
2391
|
return {
|
|
@@ -2306,6 +2528,7 @@ async function createEngineInner(options, holder) {
|
|
|
2306
2528
|
useSubgroups: useSG,
|
|
2307
2529
|
subgroupSize: sgMax,
|
|
2308
2530
|
kvCache: kv16 ? "f16" : kv8 ? "q8" : "f32",
|
|
2531
|
+
overflow: roll ? "sinks" : "error",
|
|
2309
2532
|
maxSeqLen,
|
|
2310
2533
|
adapter: {
|
|
2311
2534
|
vendor: info.vendor,
|
|
@@ -2333,12 +2556,18 @@ async function createEngineInner(options, holder) {
|
|
|
2333
2556
|
readbackMs: 0
|
|
2334
2557
|
}
|
|
2335
2558
|
};
|
|
2336
|
-
|
|
2559
|
+
let posBase = reuse ? roll ? cacheLen : fullHistory.length - 1 : 0;
|
|
2337
2560
|
const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds;
|
|
2338
2561
|
if (prefillTokens.length === 0) throw new Error("generate: no tokens to process");
|
|
2562
|
+
if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {
|
|
2563
|
+
if (SINKS + prefillTokens.length + 1 > maxSeqLen) throw new Error(`generate: prompt length ${prefillTokens.length} exceeds the rolling window (maxSeqLen ${maxSeqLen} minus ${SINKS} sinks); trim the prompt`);
|
|
2564
|
+
await ensureKvCapacity(Math.min(maxSeqLen, posBase + prefillTokens.length));
|
|
2565
|
+
posBase = evict(posBase, posBase + prefillTokens.length + 1 - maxSeqLen);
|
|
2566
|
+
cacheLen = posBase;
|
|
2567
|
+
}
|
|
2339
2568
|
const room = maxSeqLen - posBase - prefillTokens.length;
|
|
2340
2569
|
if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`);
|
|
2341
|
-
const maxTokens = Math.min(genOpts.maxTokens ?? 256, room);
|
|
2570
|
+
const maxTokens = roll ? genOpts.maxTokens ?? 256 : Math.min(genOpts.maxTokens ?? 256, room);
|
|
2342
2571
|
if (reuse) fullHistory.push(...promptTokenIds);
|
|
2343
2572
|
else fullHistory = [...promptTokenIds];
|
|
2344
2573
|
if (maxTokens < 1) {
|
|
@@ -2348,6 +2577,7 @@ async function createEngineInner(options, holder) {
|
|
|
2348
2577
|
const t0 = performance.now();
|
|
2349
2578
|
await runPrefill(prefillTokens, posBase, genOpts.signal);
|
|
2350
2579
|
await device.queue.onSubmittedWorkDone();
|
|
2580
|
+
cacheLen = posBase + prefillTokens.length - 1;
|
|
2351
2581
|
return {
|
|
2352
2582
|
tokens: [],
|
|
2353
2583
|
prefillMs: performance.now() - t0,
|
|
@@ -2443,6 +2673,7 @@ async function createEngineInner(options, holder) {
|
|
|
2443
2673
|
await runPrefill(ids, 0);
|
|
2444
2674
|
await device.queue.onSubmittedWorkDone();
|
|
2445
2675
|
fullHistory = [...ids];
|
|
2676
|
+
cacheLen = ids.length - 1;
|
|
2446
2677
|
return { prefillMs: performance.now() - t0 };
|
|
2447
2678
|
} finally {
|
|
2448
2679
|
flushTransients();
|
|
@@ -2454,7 +2685,7 @@ async function createEngineInner(options, holder) {
|
|
|
2454
2685
|
const snapshotBytes = (len) => A.layers * 2 * len * (kvRowBytes + scRowBytes);
|
|
2455
2686
|
async function saveCache() {
|
|
2456
2687
|
if (fullHistory.length === 0) return null;
|
|
2457
|
-
const len = fullHistory.length - 1;
|
|
2688
|
+
const len = roll ? cacheLen : fullHistory.length - 1;
|
|
2458
2689
|
const data = new ArrayBuffer(snapshotBytes(len));
|
|
2459
2690
|
if (len > 0) {
|
|
2460
2691
|
const rb = device.createBuffer({
|
|
@@ -2482,7 +2713,7 @@ async function createEngineInner(options, holder) {
|
|
|
2482
2713
|
rb.destroy();
|
|
2483
2714
|
}
|
|
2484
2715
|
return {
|
|
2485
|
-
version: 1,
|
|
2716
|
+
version: roll ? 2 : 1,
|
|
2486
2717
|
kvCache: capabilities.kvCache,
|
|
2487
2718
|
model: {
|
|
2488
2719
|
layers: A.layers,
|
|
@@ -2492,17 +2723,23 @@ async function createEngineInner(options, holder) {
|
|
|
2492
2723
|
vocab: A.vocab
|
|
2493
2724
|
},
|
|
2494
2725
|
ids: [...fullHistory],
|
|
2726
|
+
...roll ? { roll: {
|
|
2727
|
+
sinkTokens: SINKS,
|
|
2728
|
+
cacheLen
|
|
2729
|
+
} } : {},
|
|
2495
2730
|
data
|
|
2496
2731
|
};
|
|
2497
2732
|
}
|
|
2498
2733
|
async function restoreCache(snap) {
|
|
2499
|
-
if (!snap || snap.version !== 1) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`);
|
|
2734
|
+
if (!snap || snap.version !== 1 && snap.version !== 2) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`);
|
|
2735
|
+
if (snap.version === 2 !== roll) throw new Error(snap.version === 2 ? "restoreCache: snapshot was saved under overflow 'sinks' (unroped keys); this engine runs overflow 'error'" : "restoreCache: snapshot was saved under overflow 'error' (roped keys); this engine runs overflow 'sinks'");
|
|
2736
|
+
if (snap.version === 2 && snap.roll?.sinkTokens !== SINKS) throw new Error(`restoreCache: snapshot uses ${snap.roll?.sinkTokens} sink tokens but this engine uses ${SINKS}`);
|
|
2500
2737
|
if (snap.kvCache !== capabilities.kvCache) throw new Error(`restoreCache: snapshot was saved under kvCache '${snap.kvCache}' but this engine runs '${capabilities.kvCache}' - snapshots do not convert across modes`);
|
|
2501
2738
|
const m = snap.model;
|
|
2502
2739
|
if (!m || m.layers !== A.layers || m.kvHeads !== KV || m.headDim !== Dh || m.hidden !== Hd || m.vocab !== A.vocab) throw new Error("restoreCache: snapshot is from a different model (architecture mismatch)");
|
|
2503
2740
|
if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error("restoreCache: snapshot holds no tokens");
|
|
2504
|
-
|
|
2505
|
-
|
|
2741
|
+
const len = snap.version === 2 ? snap.roll.cacheLen : snap.ids.length - 1;
|
|
2742
|
+
if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
|
|
2506
2743
|
if (snap.data.byteLength !== snapshotBytes(len)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`);
|
|
2507
2744
|
await ensureKvCapacity(len);
|
|
2508
2745
|
let off = 0;
|
|
@@ -2519,6 +2756,7 @@ async function createEngineInner(options, holder) {
|
|
|
2519
2756
|
}
|
|
2520
2757
|
}
|
|
2521
2758
|
fullHistory = [...snap.ids];
|
|
2759
|
+
cacheLen = len;
|
|
2522
2760
|
}
|
|
2523
2761
|
let opChain = Promise.resolve();
|
|
2524
2762
|
const serialize = (fn) => {
|