bitgpu 0.14.0 → 0.15.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 +19 -4
- package/dist/chat.d.ts +1 -1
- package/dist/gguf.d.ts +1 -1
- package/dist/gguf.js +175 -1
- package/dist/gguf.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +394 -42
- package/dist/index.js.map +1 -1
- package/dist/{types-iFADjEuf.d.ts → types-Wg8VrdrL.d.ts} +25 -2
- package/package.json +3 -1
package/dist/index.js
CHANGED
|
@@ -3,6 +3,9 @@ const SHADERS = {
|
|
|
3
3
|
"add": "// Elementwise residual add: y[i] = a[i] + b[i].\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> a: array<f32>;\n@group(0) @binding(2) var<storage, read> b: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n y[i] = a[i] + b[i];\n}\n",
|
|
4
4
|
"argmax": "// GPU argmax over the logits, writing one token id into a GPU buffer so the token never leaves the\n// GPU (enables the deferred-sync decode loop). Single workgroup, WG threads strided-scan the N\n// logits tracking (maxVal, maxIdx), then a shared-mem tree reduction. Tie-break = LOWEST index, to\n// match the CPU argmax (strict > keeps the first max). No subgroup ops -> all devices.\noverride WG: u32 = 256u;\nstruct Params { N: u32, outIdx: 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> outTok: array<u32>; // outTok[p.outIdx] = argmax\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) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\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) { outTok[p.outIdx] = sidx[0]; }\n}\n",
|
|
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
|
+
"attention_online": "// Causal GQA attention with online (flash) softmax, head-dim up to the workgroup size (256) - the\n// Qwen3.5 full-attention layers use head_dim 256, past the <=128 the register-array kernels assume.\n// One workgroup per query (s,h); thread d owns output dim d. Streams keys j<=s keeping running\n// max/sum/acc, so no O(S) score storage. Output gate + RoPE + QK-norm are applied separately.\noverride WGD: u32 = 256u; // threads == head_dim D\nstruct Params { S: u32, H: u32, KV: u32, D: u32, scale: f32, _p0: u32, _p1: u32, _p2: u32 };\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> k: array<f32>; // [S, KV, D]\n@group(0) @binding(3) var<storage, read> v: array<f32>; // [S, KV, D]\n@group(0) @binding(4) var<storage, read_write> outp: array<f32>; // [S, H, D]\nvar<workgroup> qsh: array<f32, 256>;\nvar<workgroup> red: array<f32, 256>;\n\n@compute @workgroup_size(WGD)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let qi = wg.x; // query flat index = s*H + h\n let s = qi / p.H;\n let h = qi % p.H;\n let hkv = h / (p.H / p.KV); // GQA: which kv head\n let d = lid.x;\n let D = p.D;\n if (d < D) { qsh[d] = q[qi * D + d]; }\n workgroupBarrier();\n\n var m = -1e30;\n var l = 0.0;\n var acc = 0.0;\n for (var j = 0u; j <= s; j = j + 1u) {\n red[d] = select(0.0, qsh[d] * k[(j * p.KV + hkv) * D + d], d < D);\n workgroupBarrier();\n for (var st = WGD / 2u; st > 0u; st = st >> 1u) {\n if (d < st) { red[d] = red[d] + red[d + st]; }\n workgroupBarrier();\n }\n let score = red[0] * p.scale;\n let mn = max(m, score);\n let corr = exp(m - mn);\n let pj = exp(score - mn);\n l = l * corr + pj;\n if (d < D) { acc = acc * corr + pj * v[(j * p.KV + hkv) * D + d]; }\n m = mn;\n workgroupBarrier(); // before next j overwrites red\n }\n if (d < D) { outp[qi * D + d] = acc / l; }\n}\n",
|
|
7
|
+
"attention_online_cache": "// Causal GQA attention (online/flash softmax, head_dim up to 256) reading K/V from the persistent\n// f32 cache (Kc/Vc, layout [pos*KV + kv_head, D]) - the Qwen3.5 full-attention path for both prefill\n// and decode. One workgroup per query (s,h); thread d owns output dim d. The query at absolute\n// position posBase+s attends to cache positions 0 .. posBase+s (causal). Keys are cached already\n// RoPE'd, so no read-time rotation.\noverride WGD: u32 = 256u; // threads == head_dim D\nstruct Params { S: u32, H: u32, KV: u32, D: u32, scale: f32, posBase: u32, _p1: u32, _p2: u32 };\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>; // cache [cap*KV, D]\n@group(0) @binding(3) var<storage, read> vc: array<f32>; // cache [cap*KV, D]\n@group(0) @binding(4) var<storage, read_write> outp: array<f32>; // [S, H, D]\nvar<workgroup> qsh: array<f32, 256>;\nvar<workgroup> red: array<f32, 256>;\n\n@compute @workgroup_size(WGD)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let qi = wg.x; // query flat index = s*H + h\n let s = qi / p.H;\n let h = qi % p.H;\n let hkv = h / (p.H / p.KV);\n let d = lid.x;\n let D = p.D;\n if (d < D) { qsh[d] = q[qi * D + d]; }\n workgroupBarrier();\n\n var m = -1e30;\n var l = 0.0;\n var acc = 0.0;\n let last = p.posBase + s; // inclusive: attend cache positions 0..last\n for (var j = 0u; j <= last; j = j + 1u) {\n red[d] = select(0.0, qsh[d] * kc[(j * p.KV + hkv) * D + d], d < D);\n workgroupBarrier();\n for (var st = WGD / 2u; st > 0u; st = st >> 1u) {\n if (d < st) { red[d] = red[d] + red[d + st]; }\n workgroupBarrier();\n }\n let score = red[0] * p.scale;\n let mn = max(m, score);\n let corr = exp(m - mn);\n let pj = exp(score - mn);\n l = l * corr + pj;\n if (d < D) { acc = acc * corr + pj * vc[(j * p.KV + hkv) * D + d]; }\n m = mn;\n workgroupBarrier();\n }\n if (d < D) { outp[qi * D + d] = acc / l; }\n}\n",
|
|
8
|
+
"attention_online_cache_kv8": "// q8 variant of attention_online_cache: the Qwen3.5 full-attention path reading K/V from the packed\n// snorm8 cache (kcQ/vcQ = 4 x snorm8 per u32 word, kcS/vcS = one f32 scale per 32-element block,\n// llama.cpp q8_0-style, written by copy_kv8). Each element is dequantized with one unpack4x8snorm +\n// block-scale multiply at read time; all online-softmax arithmetic stays f32, so this matches the f32\n// attention_online_cache exactly except for the single snorm8 rounding of K/V at write (nothing\n// compounds). Same structure: one workgroup per query (s,h), thread d owns output dim d. head_dim <=256.\noverride WGD: u32 = 256u; // threads == head_dim D\nstruct Params { S: u32, H: u32, KV: u32, D: u32, scale: f32, posBase: u32, _p1: u32, _p2: u32 };\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> kcQ: array<u32>; // cache [cap*KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> kcS: array<f32>; // cache [cap*KV, D/32] block scales\n@group(0) @binding(4) var<storage, read> vcQ: array<u32>; // cache [cap*KV, D/4]\n@group(0) @binding(5) var<storage, read> vcS: array<f32>; // cache [cap*KV, D/32]\n@group(0) @binding(6) var<storage, read_write> outp: array<f32>; // [S, H, D]\nvar<workgroup> qsh: array<f32, 256>;\nvar<workgroup> red: array<f32, 256>;\n\n@compute @workgroup_size(WGD)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let qi = wg.x; // query flat index = s*H + h\n let s = qi / p.H;\n let h = qi % p.H;\n let hkv = h / (p.H / p.KV);\n let d = lid.x;\n let D = p.D;\n let W4 = D / 4u;\n let NB = D / 32u;\n if (d < D) { qsh[d] = q[qi * D + d]; }\n workgroupBarrier();\n\n var m = -1e30;\n var l = 0.0;\n var acc = 0.0;\n let last = p.posBase + s; // inclusive: attend cache positions 0..last\n for (var j = 0u; j <= last; j = j + 1u) {\n let row = j * p.KV + hkv;\n var kval = 0.0;\n if (d < D) { kval = unpack4x8snorm(kcQ[row * W4 + (d >> 2u)])[d & 3u] * kcS[row * NB + (d >> 5u)]; }\n red[d] = select(0.0, qsh[d] * kval, d < D);\n workgroupBarrier();\n for (var st = WGD / 2u; st > 0u; st = st >> 1u) {\n if (d < st) { red[d] = red[d] + red[d + st]; }\n workgroupBarrier();\n }\n let score = red[0] * p.scale;\n let mn = max(m, score);\n let corr = exp(m - mn);\n let pj = exp(score - mn);\n l = l * corr + pj;\n if (d < D) {\n let vval = unpack4x8snorm(vcQ[row * W4 + (d >> 2u)])[d & 3u] * vcS[row * NB + (d >> 5u)];\n acc = acc * corr + pj * vval;\n }\n m = mn;\n workgroupBarrier();\n }\n if (d < D) { outp[qi * D + d] = acc / l; }\n}\n",
|
|
6
9
|
"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
10
|
"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
11
|
"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",
|
|
@@ -15,11 +18,16 @@ const SHADERS = {
|
|
|
15
18
|
"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
19
|
"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
20
|
"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",
|
|
21
|
+
"conv1d_causal": "// Depthwise causal Conv1d (kernel width K) + SiLU, for the gated-DeltaNet q/k/v stream. x is\n// [S, C] (C = conv_dim channels), weight is [C, K] (per-channel taps, the GGUF ssm_conv1d layout).\n// Carries a persistent left-context so segmented prefill and token-by-token decode continue across\n// calls: state_in / state_out hold the last K-1 inputs ([K-1, C]); loadState!=0 uses them (else the\n// causal left pad is zero). Extended input ext = [state_in (K-1), x (S)]:\n// y[t,c] = silu( sum_{j<K} w[c,j] * ext[t+j, c] ), state_out[i,c] = ext[S+i, c] (i < K-1)\nstruct Params { S: u32, C: u32, K: u32, loadState: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, C]\n@group(0) @binding(2) var<storage, read> w: array<f32>; // [C, K]\n@group(0) @binding(3) var<storage, read> state_in: array<f32>; // [K-1, C]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, C]\n@group(0) @binding(5) var<storage, read_write> state_out: array<f32>; // [K-1, C]\n\nfn ext(m: u32, c: u32) -> f32 {\n if (m + 1u < p.K) { return select(0.0, state_in[m * p.C + c], p.loadState != 0u); }\n return x[(m - (p.K - 1u)) * p.C + c];\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 i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n let outN = p.S * p.C;\n if (i < outN) {\n let c = i % p.C;\n let t = i / p.C;\n var acc = 0.0;\n for (var j = 0u; j < p.K; j = j + 1u) { acc = acc + w[c * p.K + j] * ext(t + j, c); }\n y[i] = acc / (1.0 + exp(-acc)); // SiLU\n } else if (i < outN + (p.K - 1u) * p.C) {\n let si = i - outN;\n let sc = si % p.C;\n let sk = si / p.C; // 0 .. K-2\n state_out[sk * p.C + sc] = ext(p.S + sk, sc);\n }\n}\n",
|
|
18
22
|
"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",
|
|
19
23
|
"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",
|
|
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,
|
|
24
|
+
"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, 64>; // per-word abs max (D <= 256 -> at most 64 words)\nvar<workgroup> wblk: array<f32, 8>; // per-block scale (D/32 <= 8 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",
|
|
25
|
+
"deltanet_gbeta": "// DeltaNet gate/decay compute: from the a (decay input) and b (beta input) projections,\n// g[s,h] = a_neg[h] * softplus(a[s,h] + dt_bias[h]) (<= 0, log-space decay)\n// beta[s,h] = sigmoid(b[s,h])\n// per value head h. a_neg is -exp(A_log): the PrismML GGUF stores this pre-computed in the ssm_a\n// tensor (verified against the transformers A_log), so no exp() here. One invocation per (s,h);\n// output is [g (S*H) ; beta (S*H)] concatenated (engine binds two sub-ranges). Matches qwen35_numpy.\nstruct Params { S: u32, H: u32, _p0: u32, _p1: u32 }; // H = num_value_heads\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> a: array<f32>; // [S, H]\n@group(0) @binding(2) var<storage, read> b: array<f32>; // [S, H]\n@group(0) @binding(3) var<storage, read> a_neg: array<f32>; // [H] = -exp(A_log)\n@group(0) @binding(4) var<storage, read> dt_bias: array<f32>; // [H]\n@group(0) @binding(5) var<storage, read_write> out: array<f32>;// [2*S*H]: g then beta\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 let n = p.S * p.H;\n if (i >= n) { return; }\n let h = i % p.H;\n let x = a[i] + dt_bias[h];\n let sp = max(x, 0.0) + log(1.0 + exp(-abs(x))); // softplus (stable)\n out[i] = a_neg[h] * sp; // g (a_neg already = -exp(A_log))\n out[n + i] = 1.0 / (1.0 + exp(-b[i])); // beta\n}\n",
|
|
26
|
+
"deltanet_norm_gate": "// Gated RMSNorm for the DeltaNet output: y = gamma * rmsnorm(core) * silu(z), normalized over the\n// value head dim (one workgroup per head-vector row). Unlike the model's plain RMSNorm this uses\n// the weight directly (not 1+weight), matching tools/qwen35_numpy (Qwen3NextRMSNormGated).\noverride WG: u32 = 128u;\nstruct Params { rows: u32, DV: u32, eps: f32, _pad: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> core: array<f32>; // [rows, DV]\n@group(0) @binding(2) var<storage, read> z: array<f32>; // [rows, DV] gate\n@group(0) @binding(3) var<storage, read> gamma: array<f32>; // [DV]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>;// [rows, DV]\nvar<workgroup> sdata: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x;\n if (row >= p.rows) { return; }\n let tid = lid.x;\n let base = row * p.DV;\n var s = 0.0;\n for (var i = tid; i < p.DV; i = i + WG) { let c = core[base + i]; s = s + c * c; }\n sdata[tid] = s;\n workgroupBarrier();\n for (var st = WG / 2u; st > 0u; st = st >> 1u) {\n if (tid < st) { sdata[tid] = sdata[tid] + sdata[tid + st]; }\n workgroupBarrier();\n }\n let inv = inverseSqrt(sdata[0] / f32(p.DV) + p.eps);\n for (var i = tid; i < p.DV; i = i + WG) {\n let zz = z[base + i];\n y[base + i] = gamma[i] * (core[base + i] * inv) * (zz / (1.0 + exp(-zz))); // * silu(z)\n }\n}\n",
|
|
27
|
+
"deltanet_recur": "// Gated DeltaNet recurrent scan (the sequential O(1)/token gated delta rule; bitgpu's decode path\n// and a correctness reference for prefill). One workgroup per value head; thread `dv` owns value\n// column dv of the per-head state S[dk,dv], held in registers across the token loop. Per token:\n// S *= exp(g); kv = Kn·S; delta = (v - kv)·beta; S += Kn⊗delta; out = Qn·S\n// with Kn = l2norm(k), Qn = l2norm(q)/sqrt(dk) (matches tools/qwen35_numpy._delta_recurrent).\n// GQA: value head h reads q/k from key head h%HK. GGUF/bitgpu store value heads grouped\n// [rep, n_key_heads] (transposed from HF's [n_key_heads, rep]), so the shared key/query head is\n// h%HK (a \"tile\"), NOT h/(H/HK) (a \"repeat-interleave\"). loadState!=0 continues from state_in\n// (persistent decode/cross-segment state); state_out always carries the final state out.\noverride WGV: u32 = 128u; // threads per workgroup == head_v_dim (dv)\nstruct Params { S: u32, H: u32, DK: u32, DV: u32, HK: u32, betaOff: u32, loadState: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, HK, DK]\n@group(0) @binding(2) var<storage, read> k: array<f32>; // [S, HK, DK]\n@group(0) @binding(3) var<storage, read> v: array<f32>; // [S, H, DV]\n@group(0) @binding(4) var<storage, read> g: array<f32>; // [S, H]\n@group(0) @binding(5) var<storage, read> beta: array<f32>; // [S, H]\n@group(0) @binding(6) var<storage, read> state_in: array<f32>; // [H, DK, DV]\n@group(0) @binding(7) var<storage, read_write> core: array<f32>; // [S, H, DV]\n@group(0) @binding(8) var<storage, read_write> state_out: array<f32>; // [H, DK, DV]\nvar<workgroup> ksh: array<f32, 128>; // current token's raw k (>= DK)\nvar<workgroup> qsh: array<f32, 128>; // current token's raw q\n\n@compute @workgroup_size(WGV)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let h = wg.x; // value head\n let hk = h % p.HK; // GQA: shared key/query head (GGUF [rep,n_key] tile order)\n let dv = lid.x;\n let DK = p.DK;\n let sbase = h * DK * p.DV + dv; // state column S[:, dv] of head h, stride DV\n let scale = inverseSqrt(f32(DK));\n var s: array<f32, 128>; // state column S[:, dv], length DK\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = select(0.0, state_in[sbase + dk * p.DV], p.loadState != 0u); }\n\n for (var t = 0u; t < p.S; t = t + 1u) {\n let base = t * p.H + h; // value-head row (v, g, beta, out)\n let basek = t * p.HK + hk; // key-head row (q, k)\n for (var i = lid.x; i < DK; i = i + WGV) { ksh[i] = k[basek * DK + i]; qsh[i] = q[basek * DK + i]; }\n workgroupBarrier();\n var sk = 0.0;\n var sq = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { sk = sk + ksh[dk] * ksh[dk]; sq = sq + qsh[dk] * qsh[dk]; }\n let ik = inverseSqrt(sk + 1e-6); // l2norm(k)\n let iq = inverseSqrt(sq + 1e-6) * scale; // l2norm(q) / sqrt(dk)\n if (dv < p.DV) {\n let gt = exp(g[base]);\n let bt = beta[p.betaOff + base]; // beta may share g's buffer (engine: gbeta = [g; beta])\n for (var dk = 0u; dk < DK; dk = dk + 1u) { s[dk] = s[dk] * gt; } // decay\n var kv = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) { kv = kv + s[dk] * ksh[dk] * ik; }\n let delta = (v[base * p.DV + dv] - kv) * bt;\n var o = 0.0;\n for (var dk = 0u; dk < DK; dk = dk + 1u) {\n s[dk] = s[dk] + ksh[dk] * ik * delta; // S += Kn ⊗ delta\n o = o + s[dk] * qsh[dk] * iq; // out = Qn · S (updated)\n }\n core[base * p.DV + dv] = o;\n }\n workgroupBarrier();\n }\n if (dv < p.DV) { for (var dk = 0u; dk < DK; dk = dk + 1u) { state_out[sbase + dk * p.DV] = s[dk]; } }\n}\n",
|
|
21
28
|
"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",
|
|
22
29
|
"embed_gather_batch": "// Batched GPU embedding gather + 4-bit dequant for PROMPT tokens: one invocation per output\n// element writes out[s*H + k] for tokenIds[s]. A prefill segment uploads S u32 token ids\n// instead of S*H dequantized floats, so the CPU-side embedding tables are not needed at all\n// (~50-100 MB RAM per model). Same per-row stride math and dequant as embed_gather.wgsl\n// (H=2048 -> 256/16/8 strides); uint8 sources read as u32 and byte-extracted (little-endian).\nstruct Params { S: u32, H: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenIds: array<u32>; // [S]\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab * H/8] packed\n@group(0) @binding(3) var<storage, read> tgt4: array<u32>; // uint8 [256*4] packed (1 src byte -> 4)\n@group(0) @binding(4) var<storage, read> embScales: array<f32>; // [vocab * H/128]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab * ceil(H/256)] packed\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S * H]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let gi = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (gi >= p.S * p.H) { return; }\n let k = gi % p.H;\n let id = tokenIds[gi / p.H];\n let rowBytes = p.H >> 3u;\n let scaleRow = p.H >> 7u;\n let zpRow = (scaleRow + 1u) >> 1u;\n let i = k >> 3u;\n let qd = (k >> 1u) & 3u;\n let c = k & 1u;\n let wqIdx = id * rowBytes + i;\n let e = (embWq[wqIdx >> 2u] >> (8u * (wqIdx & 3u))) & 0xffu; // source byte 0..255\n let tIdx = 4u * e + qd;\n let t = (tgt4[tIdx >> 2u] >> (8u * (tIdx & 3u))) & 0xffu; // expanded byte (2 codes)\n let code = (t >> (4u * c)) & 0xfu;\n let blk = k >> 7u;\n let zpIdx = id * zpRow + (blk >> 1u);\n let zpByte = (embZp[zpIdx >> 2u] >> (8u * (zpIdx & 3u))) & 0xffu;\n let zp = (zpByte >> (4u * (blk & 1u))) & 0xfu;\n out[gi] = (f32(code) - f32(zp)) * embScales[id * scaleRow + blk];\n}\n",
|
|
30
|
+
"gate_sigmoid": "// Output gate for Qwen3.5 gated attention: y = x * sigmoid(gate), elementwise. Applied to the\n// attention output before o_proj (the gate is the second half of the doubled q_proj).\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>;\n@group(0) @binding(2) var<storage, read> gate: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n y[i] = x[i] / (1.0 + exp(-gate[i]));\n}\n",
|
|
23
31
|
"logsumexp": "// log-sum-exp over the (penalty-filtered) logits, the softmax normalizer that turns a raw logit\n// into a true logprob on the CPU: logprob(id) = logit[id] - lse. Runs AFTER sampler_penalty and\n// BEFORE the argmax_masked rounds (those mask their winners in place, which would corrupt the\n// sum). Two-phase single-workgroup reduction: strided max, then strided sum of exp(x - max);\n// entries at the -inf sentinel (banned ids) contribute nothing. Only one f32 is read back.\noverride WG: u32 = 256u;\nstruct Params { N: u32, _0: u32, _1: u32, _2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> outLse: array<f32>; // outLse[0] = max + log(sum)\n\nconst NEG_SENTINEL: f32 = -3.0e38; // below any real logit; banned entries sit at f32 -inf\n\nvar<workgroup> sval: array<f32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var m = -3.4e38;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL && v > m) { m = v; }\n }\n sval[tid] = m;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s && sval[tid + s] > sval[tid]) { sval[tid] = sval[tid + s]; }\n workgroupBarrier();\n }\n let gmax = sval[0];\n workgroupBarrier();\n var acc = 0.0;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > NEG_SENTINEL) { acc = acc + exp(v - gmax); }\n }\n sval[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sval[tid] = sval[tid] + sval[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) { outLse[0] = gmax + log(sval[0]); }\n}\n",
|
|
24
32
|
"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",
|
|
25
33
|
"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",
|
|
@@ -47,7 +55,10 @@ const SHADERS = {
|
|
|
47
55
|
"rmsnorm_sg_af16": "// RMSNorm (subgroup) that writes the normalized activation as f16 - the input side of the\n// f16-activation decode matmuls (activation: 'f16'). Reads the f32 residual stream; the\n// sum-of-squares reduction stays f32 (accuracy); only the stored output is rounded to f16.\n// Identical reduction to rmsnorm_sg, so it is bit-comparable up to the final f16 rounding.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>;\n@group(0) @binding(2) var<storage, read> gamma: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f16>;\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 total = subgroupAdd(s);\n let inv = inverseSqrt(total / f32(p.D) + p.eps);\n for (var i = lane; i < p.D; i = i + SG) { y[base + i] = f16(x[base + i] * inv * gamma[i]); }\n}\n",
|
|
48
56
|
"rmsnorm_wg": "// RMSNorm, no-subgroup fallback: one workgroup per row; threads split D and tree-reduce the\n// sum of squares via shared memory. Replaces the one-thread-per-row kernel on this path: at\n// decode (R=1) that kernel walked 2xD elements serially on a single thread, latency-bound,\n// and it ran twice per layer - the dominant cost of the whole fallback decode step.\n// Mirrors rmsnorm_sg exactly, with subgroupAdd swapped for the shared-memory reduction.\noverride WG: u32 = 64u;\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read_write> y: array<f32>; // [R, D]\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.R) { return; }\n let tid = lid.x;\n let base = row * p.D;\n var s = 0.0;\n for (var i = tid; i < p.D; i = i + WG) { let v = x[base + i]; s = s + v * v; }\n sdata[tid] = s;\n workgroupBarrier();\n for (var st = WG / 2u; st > 0u; st = st >> 1u) {\n if (tid < st) { sdata[tid] = sdata[tid] + sdata[tid + st]; }\n workgroupBarrier();\n }\n let inv = inverseSqrt(sdata[0] / f32(p.D) + p.eps);\n for (var i = tid; i < p.D; i = i + WG) { y[base + i] = x[base + i] * inv * gamma[i]; }\n}\n",
|
|
49
57
|
"rope": "// RoPE (rotate_half) with precomputed full cos/sin [S, D]. x is [S, H, D]. One invocation per element.\nstruct Params { S: u32, H: u32, D: u32, _pad: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> cos: array<f32>; // [S, D]\n@group(0) @binding(3) var<storage, read> sin: array<f32>; // [S, D]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.S * p.H * p.D) { return; }\n let d = idx % p.D;\n let sh = idx / p.D;\n let s = sh / p.H;\n let half = p.D / 2u;\n let row = sh * p.D; // s*H*D + h*D\n var rot: f32;\n if (d < half) {\n rot = -x[row + d + half];\n } else {\n rot = x[row + d - half];\n }\n y[idx] = x[idx] * cos[s * p.D + d] + rot * sin[s * p.D + d];\n}\n",
|
|
58
|
+
"rope_partial": "// Partial RoPE: rotate only the first ROT dims of each head (rotate_half within [0,ROT)); the\n// remaining head_dim-ROT dims pass through unrotated. cos/sin are [S, ROT]. x/y are [S, H, D].\n// Matches tools/qwen35_numpy._rope_partial (Qwen3.5 full-attention layers, partial_rotary_factor).\nstruct Params { S: u32, H: u32, D: u32, ROT: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> cosb: array<f32>; // [S, ROT]\n@group(0) @binding(3) var<storage, read> sinb: array<f32>; // [S, ROT]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.S * p.H * p.D) { return; }\n let d = idx % p.D;\n if (d >= p.ROT) { y[idx] = x[idx]; return; } // passthrough tail\n let sh = idx / p.D;\n let s = sh / p.H;\n let half = p.ROT / 2u;\n var rot: f32;\n if (d < half) { rot = -x[idx + half]; } else { rot = x[idx - half]; }\n y[idx] = x[idx] * cosb[s * p.ROT + d] + rot * sinb[s * p.ROT + d];\n}\n",
|
|
50
59
|
"sampler_penalty": "// GPU logits pre-filter for sampling: applies repetition_penalty then no_repeat_ngram bans in place\n// on the full vocab logit buffer, so only a tiny top-K candidate set has to be read back (not all\n// ~151k logits). Matches transformers.js exactly: rep_penalty over the DEDUPED prompt+generated id\n// set (logit<0 ? *penalty : /penalty), then ngram-banned next-tokens set to -Infinity. Both id lists\n// are computed on the CPU each step (exact, since at syncN=1 the full history is known) and uploaded.\n// Temperature is NOT applied here: top-k is invariant under the monotonic divide, so temperature is\n// applied on the CPU to just the K candidate values before softmax (bit-identical, one less pass).\n// Single workgroup, no subgroup ops -> all devices. The storageBarrier guarantees every penalty\n// write lands before any ban write, so a token that is both repeated and ngram-banned ends at -inf\n// (ban wins, matching the reference order rep_penalty -> ngram).\noverride WG: u32 = 256u;\n// negInf carries the -Infinity bit pattern (0xff800000) from the host: bitcasting it at RUNTIME yields\n// -inf, whereas bitcast<f32>(0xff800000u) is a const-expression evaluating to inf, which is a WGSL\n// shader-creation error. (Runtime inf is fine; only const/override inf/nan is rejected.)\nstruct Params { affectedLen: u32, banLen: u32, penalty: f32, negInf: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> affectedIds: array<u32>; // deduped prompt+generated ids\n@group(0) @binding(2) var<storage, read> banIds: array<u32>; // ngram-banned next-token ids\n@group(0) @binding(3) var<storage, read_write> logits: array<f32>; // [vocab], modified in place\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n for (var i = tid; i < p.affectedLen; i = i + WG) {\n let t = affectedIds[i];\n let v = logits[t];\n if (v < 0.0) { logits[t] = v * p.penalty; } else { logits[t] = v / p.penalty; }\n }\n storageBarrier(); // all penalty writes before any ban write\n for (var i = tid; i < p.banLen; i = i + WG) {\n logits[banIds[i]] = bitcast<f32>(p.negInf); // -Infinity (runtime bitcast)\n }\n}\n",
|
|
60
|
+
"slice_cols": "// Extract a contiguous column range [off, off+w) from each row of a [rows, stride] buffer into a\n// packed [rows, w] buffer. Splits the DeltaNet conv output (q|k|v concatenated per token) into the\n// separate q/k/v activation buffers the scan reads.\nstruct Params { rows: u32, w: u32, stride: u32, off: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, stride]\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;// [rows, w]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.rows * p.w) { return; }\n let r = i / p.w;\n let c = i % p.w;\n dst[i] = src[r * p.stride + p.off + c];\n}\n",
|
|
61
|
+
"split_head": "// De-interleave a per-head doubled projection [S, H, 2*Dh] into [S, H, Dh], taking the half at\n// `off` (0 = query, Dh = gate). The Qwen3.5 gated-attention q_proj packs query and output-gate\n// interleaved per head; this pulls one out into a packed buffer.\nstruct Params { S: u32, H: u32, Dh: u32, off: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [S, H, 2*Dh]\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;// [S, H, Dh]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.S * p.H * p.Dh) { return; }\n let d = i % p.Dh;\n let sh = i / p.Dh; // s*H + h\n dst[i] = src[sh * (2u * p.Dh) + p.off + d];\n}\n",
|
|
51
62
|
"swiglu": "// SwiGLU gate: y[i] = silu(gate[i]) * up[i], silu(g) = g * sigmoid(g). One invocation per element.\nstruct Params { n: u32, _p0: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> gate: array<f32>;\n@group(0) @binding(2) var<storage, read> up: array<f32>;\n@group(0) @binding(3) var<storage, read_write> y: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n let g = gate[i];\n y[i] = (g / (1.0 + exp(-g))) * up[i];\n}\n"
|
|
52
63
|
};
|
|
53
64
|
//#endregion
|
|
@@ -242,17 +253,17 @@ const eqBytes = (a, b) => {
|
|
|
242
253
|
* baked caches (v2/GGUF). Plain rope or YaRN (transformers formula: beta_fast 32, beta_slow 1,
|
|
243
254
|
* mscale = 0.1*ln(factor)+1). Angles accumulate in f64 and round once to f32 per entry -
|
|
244
255
|
* tools/reference.py implements the identical recipe for fixture generation. */
|
|
245
|
-
function synthRope(A, positions) {
|
|
246
|
-
const half =
|
|
256
|
+
function synthRope(A, positions, rotaryDim = A.head_dim) {
|
|
257
|
+
const half = rotaryDim / 2;
|
|
247
258
|
const rope = A.rope;
|
|
248
259
|
const base = rope.rope_theta;
|
|
249
260
|
const factor = rope.rope_type === "yarn" ? rope.factor ?? 1 : 1;
|
|
250
261
|
const inv = new Float64Array(half);
|
|
251
262
|
const orig = rope.original_max_position_embeddings ?? 0;
|
|
252
|
-
const lo = factor === 1 ? 0 : Math.max(0, Math.floor(
|
|
253
|
-
const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil(
|
|
263
|
+
const lo = factor === 1 ? 0 : Math.max(0, Math.floor(rotaryDim * Math.log(orig / (64 * Math.PI)) / (2 * Math.log(base))));
|
|
264
|
+
const hi = factor === 1 ? 0 : Math.min(half - 1, Math.ceil(rotaryDim * Math.log(orig / (2 * Math.PI)) / (2 * Math.log(base))));
|
|
254
265
|
for (let j = 0; j < half; j++) {
|
|
255
|
-
const pf = base ** (2 * j /
|
|
266
|
+
const pf = base ** (2 * j / rotaryDim);
|
|
256
267
|
if (factor === 1) {
|
|
257
268
|
inv[j] = 1 / pf;
|
|
258
269
|
continue;
|
|
@@ -331,7 +342,8 @@ async function createEngineInner(options, holder) {
|
|
|
331
342
|
const T = manifest.tensors;
|
|
332
343
|
const FINAL_NORM = `layers.${A.layers}.final_norm_layernorm`;
|
|
333
344
|
if (A.act !== "silu") throw new Error(`bitgpu: unsupported activation '${A.act}' (kernels implement silu/SwiGLU)`);
|
|
334
|
-
if (A.head_dim > 128) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim}
|
|
345
|
+
if (A.head_dim > (A.hybrid ? 256 : 128)) throw new Error(`bitgpu: unsupported head_dim ${A.head_dim}`);
|
|
346
|
+
const ROPE_D = A.hybrid?.rotary_dim ?? A.head_dim;
|
|
335
347
|
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)`);
|
|
336
348
|
if (!T[FINAL_NORM]) throw new Error(`bitgpu: manifest is missing the final norm tensor '${FINAL_NORM}'`);
|
|
337
349
|
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)`);
|
|
@@ -385,10 +397,11 @@ async function createEngineInner(options, holder) {
|
|
|
385
397
|
const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
|
|
386
398
|
const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
|
|
387
399
|
const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
|
|
388
|
-
const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
|
|
400
|
+
const kv16 = opts.kvCache === "f16" && !A.hybrid && adapter.features.has("shader-f16");
|
|
389
401
|
const kv8 = opts.kvCache === "q8";
|
|
390
402
|
const roll = opts.overflow === "sinks";
|
|
391
403
|
const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0;
|
|
404
|
+
if (roll && A.hybrid) throw new Error("bitgpu: overflow 'sinks' is not yet supported for the qwen3_5 hybrid backbone (the full-attention read path has no sink/roll K-rotation, and windowing only the full layers while the linear layers keep full-history state is unvalidated)");
|
|
392
405
|
if (roll && maxSeqLen < SINKS + 64) throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`);
|
|
393
406
|
const KVB = kv16 ? 2 : kv8 ? 1 : 4;
|
|
394
407
|
const actF16 = opts.activation === "f16" && useSG && adapter.features.has("shader-f16");
|
|
@@ -412,7 +425,25 @@ async function createEngineInner(options, holder) {
|
|
|
412
425
|
} else if (t.kind === "f32" && t.weight) track(t.weight.len);
|
|
413
426
|
const fusedLen = (names, f) => names.reduce((n, nm) => n + T[nm][f].len, 0);
|
|
414
427
|
for (let li = 0; li < A.layers; li++) {
|
|
415
|
-
|
|
428
|
+
let groups;
|
|
429
|
+
if (A.hybrid) groups = [
|
|
430
|
+
...A.hybrid.layer_types[li] === "full" ? [
|
|
431
|
+
"attn.q_proj",
|
|
432
|
+
"attn.k_proj",
|
|
433
|
+
"attn.v_proj",
|
|
434
|
+
"attn.o_proj"
|
|
435
|
+
] : [
|
|
436
|
+
"linear.in_qkv",
|
|
437
|
+
"linear.z",
|
|
438
|
+
"linear.a",
|
|
439
|
+
"linear.b",
|
|
440
|
+
"linear.out_proj"
|
|
441
|
+
],
|
|
442
|
+
"mlp.gate_proj",
|
|
443
|
+
"mlp.up_proj",
|
|
444
|
+
"mlp.down_proj"
|
|
445
|
+
].map((s) => [`layers.${li}.${s}`]);
|
|
446
|
+
else groups = [
|
|
416
447
|
[
|
|
417
448
|
`layers.${li}.attn.q_proj`,
|
|
418
449
|
`layers.${li}.attn.k_proj`,
|
|
@@ -547,6 +578,20 @@ async function createEngineInner(options, holder) {
|
|
|
547
578
|
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";
|
|
548
579
|
const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
|
|
549
580
|
const COPY_KV = kv16 ? "copy_kv16" : "copy";
|
|
581
|
+
if (A.hybrid) {
|
|
582
|
+
for (const n of [
|
|
583
|
+
"conv1d_causal",
|
|
584
|
+
"deltanet_gbeta",
|
|
585
|
+
"rope_partial",
|
|
586
|
+
"slice_cols",
|
|
587
|
+
"split_head",
|
|
588
|
+
"gate_sigmoid"
|
|
589
|
+
]) specs.push([n]);
|
|
590
|
+
specs.push(["deltanet_recur", { WGV: A.hybrid.linear_head_dim }]);
|
|
591
|
+
specs.push(["deltanet_norm_gate", { WG: 64 }]);
|
|
592
|
+
specs.push(["attention_online", { WGD: A.head_dim }]);
|
|
593
|
+
specs.push([kv8 ? "attention_online_cache_kv8" : "attention_online_cache", { WGD: A.head_dim }]);
|
|
594
|
+
}
|
|
550
595
|
await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
|
|
551
596
|
const S_ = GPUBufferUsage.STORAGE, CD = GPUBufferUsage.COPY_DST, CS = GPUBufferUsage.COPY_SRC, U = GPUBufferUsage.UNIFORM;
|
|
552
597
|
let transients = null;
|
|
@@ -632,6 +677,10 @@ async function createEngineInner(options, holder) {
|
|
|
632
677
|
size: 16,
|
|
633
678
|
usage: S_
|
|
634
679
|
});
|
|
680
|
+
const dummy2 = device.createBuffer({
|
|
681
|
+
size: 16,
|
|
682
|
+
usage: S_
|
|
683
|
+
});
|
|
635
684
|
let fullHistory = [];
|
|
636
685
|
let cacheLen = 0;
|
|
637
686
|
const resetCache = () => {
|
|
@@ -822,7 +871,40 @@ async function createEngineInner(options, holder) {
|
|
|
822
871
|
scales
|
|
823
872
|
};
|
|
824
873
|
};
|
|
825
|
-
|
|
874
|
+
if (manifest.arch.hybrid) {
|
|
875
|
+
const bin = (nm) => {
|
|
876
|
+
const r = T[nm];
|
|
877
|
+
W[nm] = {
|
|
878
|
+
N: r.N,
|
|
879
|
+
K: r.K,
|
|
880
|
+
nb: r.K / 128,
|
|
881
|
+
N0: r.N,
|
|
882
|
+
N1: 0,
|
|
883
|
+
N2: 0,
|
|
884
|
+
...fuse([r])
|
|
885
|
+
};
|
|
886
|
+
};
|
|
887
|
+
for (let li = 0; li < A.layers; li++) {
|
|
888
|
+
for (const s of [
|
|
889
|
+
"mlp.gate_proj",
|
|
890
|
+
"mlp.up_proj",
|
|
891
|
+
"mlp.down_proj"
|
|
892
|
+
]) bin(`layers.${li}.${s}`);
|
|
893
|
+
if (manifest.arch.hybrid.layer_types[li] === "full") for (const s of [
|
|
894
|
+
"attn.q_proj",
|
|
895
|
+
"attn.k_proj",
|
|
896
|
+
"attn.v_proj",
|
|
897
|
+
"attn.o_proj"
|
|
898
|
+
]) bin(`layers.${li}.${s}`);
|
|
899
|
+
else for (const s of [
|
|
900
|
+
"linear.in_qkv",
|
|
901
|
+
"linear.z",
|
|
902
|
+
"linear.a",
|
|
903
|
+
"linear.b",
|
|
904
|
+
"linear.out_proj"
|
|
905
|
+
]) bin(`layers.${li}.${s}`);
|
|
906
|
+
}
|
|
907
|
+
} else for (let li = 0; li < A.layers; li++) {
|
|
826
908
|
const q = T[`layers.${li}.attn.q_proj`], k = T[`layers.${li}.attn.k_proj`], v = T[`layers.${li}.attn.v_proj`];
|
|
827
909
|
W[`layers.${li}.attn.qkv`] = {
|
|
828
910
|
K: q.K,
|
|
@@ -884,12 +966,12 @@ async function createEngineInner(options, holder) {
|
|
|
884
966
|
const sinBytes = wireCpu(T.sin_cache);
|
|
885
967
|
cosCache = new Float32Array(cosBytes.buffer);
|
|
886
968
|
sinCache = new Float32Array(sinBytes.buffer);
|
|
887
|
-
const ropePositions = cosCache.length / (
|
|
969
|
+
const ropePositions = cosCache.length / (ROPE_D / 2);
|
|
888
970
|
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`);
|
|
889
971
|
} else {
|
|
890
972
|
const cap = A.max_positions ?? 40960;
|
|
891
973
|
if (maxSeqLen > cap) throw new Error(`bitgpu: maxSeqLen ${maxSeqLen} exceeds the model's max_positions (${cap})`);
|
|
892
|
-
[cosCache, sinCache] = synthRope(A, maxSeqLen);
|
|
974
|
+
[cosCache, sinCache] = synthRope(A, maxSeqLen, ROPE_D);
|
|
893
975
|
}
|
|
894
976
|
routes.sort((a, b) => a.off - b.off || a.len - b.len);
|
|
895
977
|
const merged = [];
|
|
@@ -972,7 +1054,7 @@ async function createEngineInner(options, holder) {
|
|
|
972
1054
|
return out;
|
|
973
1055
|
}
|
|
974
1056
|
function ropeBufs(posBase, S) {
|
|
975
|
-
const D =
|
|
1057
|
+
const D = ROPE_D, R = D / 2, cos = new Float32Array(S * D), sin = new Float32Array(S * D);
|
|
976
1058
|
for (let s = 0; s < S; s++) for (let d = 0; d < D; d++) {
|
|
977
1059
|
cos[s * D + d] = cosCache[(posBase + s) * R + d % R];
|
|
978
1060
|
sin[s * D + d] = sinCache[(posBase + s) * R + d % R];
|
|
@@ -986,30 +1068,55 @@ async function createEngineInner(options, holder) {
|
|
|
986
1068
|
};
|
|
987
1069
|
}
|
|
988
1070
|
const KV = A.kv_heads, Dh = A.head_dim, Hd = A.hidden, H = A.heads, F = A.intermediate;
|
|
1071
|
+
const NK = A.hybrid?.linear_key_heads ?? 0, NV = A.hybrid?.linear_value_heads ?? 0, DKV = A.hybrid?.linear_head_dim ?? 0, CONVK = A.hybrid?.conv_kernel ?? 0, KEYDIM = NK * DKV, VALDIM = NV * DKV, CONVDIM = KEYDIM * 2 + VALDIM;
|
|
989
1072
|
let kvCapacity = Math.min(maxSeqLen, 512);
|
|
990
1073
|
const Kc = [], Vc = [];
|
|
991
1074
|
const Ksc = [], Vsc = [];
|
|
992
1075
|
const kvScaleBytes = (cap) => cap * KV * (Dh / 32) * 4;
|
|
993
|
-
|
|
994
|
-
|
|
1076
|
+
const kvLayers = [];
|
|
1077
|
+
for (let li = 0; li < A.layers; li++) if (!A.hybrid || A.hybrid.layer_types[li] === "full") kvLayers.push(li);
|
|
1078
|
+
const linearLayers = [];
|
|
1079
|
+
for (let li = 0; li < A.layers; li++) if (A.hybrid && A.hybrid.layer_types[li] === "linear") linearLayers.push(li);
|
|
1080
|
+
const rsSz = A.hybrid ? NV * DKV * DKV * 4 : 0;
|
|
1081
|
+
const csSz = A.hybrid ? (CONVK - 1) * CONVDIM * 4 : 0;
|
|
1082
|
+
for (const li of kvLayers) {
|
|
1083
|
+
Kc[li] = device.createBuffer({
|
|
995
1084
|
size: kvCapacity * KV * Dh * KVB,
|
|
996
1085
|
usage: S_ | CS | CD
|
|
997
|
-
})
|
|
998
|
-
Vc
|
|
1086
|
+
});
|
|
1087
|
+
Vc[li] = device.createBuffer({
|
|
999
1088
|
size: kvCapacity * KV * Dh * KVB,
|
|
1000
1089
|
usage: S_ | CS | CD
|
|
1001
|
-
})
|
|
1090
|
+
});
|
|
1002
1091
|
if (kv8) {
|
|
1003
|
-
Ksc
|
|
1092
|
+
Ksc[li] = device.createBuffer({
|
|
1004
1093
|
size: kvScaleBytes(kvCapacity),
|
|
1005
1094
|
usage: S_ | CS | CD
|
|
1006
|
-
})
|
|
1007
|
-
Vsc
|
|
1095
|
+
});
|
|
1096
|
+
Vsc[li] = device.createBuffer({
|
|
1008
1097
|
size: kvScaleBytes(kvCapacity),
|
|
1009
1098
|
usage: S_ | CS | CD
|
|
1010
|
-
})
|
|
1099
|
+
});
|
|
1011
1100
|
}
|
|
1012
1101
|
}
|
|
1102
|
+
const hyRS = [], hyCS = [];
|
|
1103
|
+
let hyPar = 0;
|
|
1104
|
+
if (A.hybrid) for (const li of linearLayers) {
|
|
1105
|
+
hyRS[li] = [device.createBuffer({
|
|
1106
|
+
size: rsSz,
|
|
1107
|
+
usage: S_ | CS | CD
|
|
1108
|
+
}), device.createBuffer({
|
|
1109
|
+
size: rsSz,
|
|
1110
|
+
usage: S_ | CS | CD
|
|
1111
|
+
})];
|
|
1112
|
+
hyCS[li] = [device.createBuffer({
|
|
1113
|
+
size: csSz,
|
|
1114
|
+
usage: S_ | CS | CD
|
|
1115
|
+
}), device.createBuffer({
|
|
1116
|
+
size: csSz,
|
|
1117
|
+
usage: S_ | CS | CD
|
|
1118
|
+
})];
|
|
1119
|
+
}
|
|
1013
1120
|
let rollCosT = null, rollSinT = null, rollOnes = null, rollZeros = null;
|
|
1014
1121
|
if (roll) {
|
|
1015
1122
|
const R2 = Dh / 2;
|
|
@@ -1045,9 +1152,8 @@ async function createEngineInner(options, holder) {
|
|
|
1045
1152
|
const copyScales = kvScaleBytes(kvCapacity);
|
|
1046
1153
|
device.pushErrorScope("out-of-memory");
|
|
1047
1154
|
const enc = device.createCommandEncoder();
|
|
1048
|
-
const per = kv8 ? 4 : 2;
|
|
1049
1155
|
const olds = [];
|
|
1050
|
-
for (
|
|
1156
|
+
for (const li of kvLayers) {
|
|
1051
1157
|
const nk = device.createBuffer({
|
|
1052
1158
|
size: newCap * KV * Dh * KVB,
|
|
1053
1159
|
usage: S_ | CS | CD
|
|
@@ -1058,7 +1164,7 @@ async function createEngineInner(options, holder) {
|
|
|
1058
1164
|
});
|
|
1059
1165
|
enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes);
|
|
1060
1166
|
enc.copyBufferToBuffer(Vc[li], 0, nv, 0, copyBytes);
|
|
1061
|
-
|
|
1167
|
+
const grp = [Kc[li], Vc[li]];
|
|
1062
1168
|
Kc[li] = nk;
|
|
1063
1169
|
Vc[li] = nv;
|
|
1064
1170
|
if (kv8) {
|
|
@@ -1072,31 +1178,32 @@ async function createEngineInner(options, holder) {
|
|
|
1072
1178
|
});
|
|
1073
1179
|
enc.copyBufferToBuffer(Ksc[li], 0, nks, 0, copyScales);
|
|
1074
1180
|
enc.copyBufferToBuffer(Vsc[li], 0, nvs, 0, copyScales);
|
|
1075
|
-
|
|
1181
|
+
grp.push(Ksc[li], Vsc[li]);
|
|
1076
1182
|
Ksc[li] = nks;
|
|
1077
1183
|
Vsc[li] = nvs;
|
|
1078
1184
|
}
|
|
1185
|
+
olds[li] = grp;
|
|
1079
1186
|
}
|
|
1080
1187
|
device.queue.submit([enc.finish()]);
|
|
1081
1188
|
await device.queue.onSubmittedWorkDone();
|
|
1082
1189
|
const oom = await device.popErrorScope();
|
|
1083
1190
|
if (oom) {
|
|
1084
|
-
for (
|
|
1191
|
+
for (const li of kvLayers) {
|
|
1085
1192
|
Kc[li].destroy();
|
|
1086
1193
|
Vc[li].destroy();
|
|
1087
|
-
Kc[li] = olds[
|
|
1088
|
-
Vc[li] = olds[
|
|
1194
|
+
Kc[li] = olds[li][0];
|
|
1195
|
+
Vc[li] = olds[li][1];
|
|
1089
1196
|
if (kv8) {
|
|
1090
1197
|
Ksc[li].destroy();
|
|
1091
1198
|
Vsc[li].destroy();
|
|
1092
|
-
Ksc[li] = olds[
|
|
1093
|
-
Vsc[li] = olds[
|
|
1199
|
+
Ksc[li] = olds[li][2];
|
|
1200
|
+
Vsc[li] = olds[li][3];
|
|
1094
1201
|
}
|
|
1095
1202
|
}
|
|
1096
1203
|
poolInvalidate();
|
|
1097
1204
|
throw new GpuOutOfMemoryError(`KV cache growth to ${newCap} positions failed: ${oom.message}`);
|
|
1098
1205
|
}
|
|
1099
|
-
for (const b of olds) b.destroy();
|
|
1206
|
+
for (const li of kvLayers) for (const b of olds[li]) b.destroy();
|
|
1100
1207
|
kvCapacity = newCap;
|
|
1101
1208
|
poolInvalidate();
|
|
1102
1209
|
}
|
|
@@ -1117,7 +1224,7 @@ async function createEngineInner(options, holder) {
|
|
|
1117
1224
|
}
|
|
1118
1225
|
const enc = device.createCommandEncoder();
|
|
1119
1226
|
const groups = [];
|
|
1120
|
-
for (
|
|
1227
|
+
for (const li of kvLayers) {
|
|
1121
1228
|
groups.push([Kc[li], rowK], [Vc[li], rowK]);
|
|
1122
1229
|
if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS]);
|
|
1123
1230
|
}
|
|
@@ -1452,8 +1559,235 @@ async function createEngineInner(options, holder) {
|
|
|
1452
1559
|
if (roll) ins.push(rollCosT, rollSinT);
|
|
1453
1560
|
return ins;
|
|
1454
1561
|
};
|
|
1562
|
+
function hybridLayer(pass, li, h, S, posBase, cos, sin) {
|
|
1563
|
+
const hy = manifest.arch.hybrid;
|
|
1564
|
+
const w = (r) => W[`layers.${li}.${r}`];
|
|
1565
|
+
const ls = posBase > 0 ? 1 : 0;
|
|
1566
|
+
const par = hyPar;
|
|
1567
|
+
const n1 = actBuf(S * Hd);
|
|
1568
|
+
rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1);
|
|
1569
|
+
let h2;
|
|
1570
|
+
if (hy.layer_types[li] === "linear") {
|
|
1571
|
+
const mixed = actBuf(S * CONVDIM);
|
|
1572
|
+
fusedMM(pass, w("linear.in_qkv"), n1, S, [
|
|
1573
|
+
mixed,
|
|
1574
|
+
dummy,
|
|
1575
|
+
dummy2
|
|
1576
|
+
]);
|
|
1577
|
+
const convd = actBuf(S * CONVDIM);
|
|
1578
|
+
const cvSt = (CONVK - 1) * CONVDIM;
|
|
1579
|
+
setup(pass, "conv1d_causal", [
|
|
1580
|
+
["u", S],
|
|
1581
|
+
["u", CONVDIM],
|
|
1582
|
+
["u", CONVK],
|
|
1583
|
+
["u", ls]
|
|
1584
|
+
], [
|
|
1585
|
+
mixed,
|
|
1586
|
+
w("linear.conv1d").buf,
|
|
1587
|
+
hyCS[li][par]
|
|
1588
|
+
], [convd, hyCS[li][par ^ 1]]);
|
|
1589
|
+
{
|
|
1590
|
+
const [gx, gy] = grid2d(Math.ceil((S * CONVDIM + cvSt) / 64));
|
|
1591
|
+
pass.dispatchWorkgroups(gx, gy, 1);
|
|
1592
|
+
}
|
|
1593
|
+
const q = actBuf(S * KEYDIM), k = actBuf(S * KEYDIM), v = actBuf(S * VALDIM);
|
|
1594
|
+
run(pass, "slice_cols", [
|
|
1595
|
+
["u", S],
|
|
1596
|
+
["u", KEYDIM],
|
|
1597
|
+
["u", CONVDIM],
|
|
1598
|
+
["u", 0]
|
|
1599
|
+
], [convd], q, S * KEYDIM);
|
|
1600
|
+
run(pass, "slice_cols", [
|
|
1601
|
+
["u", S],
|
|
1602
|
+
["u", KEYDIM],
|
|
1603
|
+
["u", CONVDIM],
|
|
1604
|
+
["u", KEYDIM]
|
|
1605
|
+
], [convd], k, S * KEYDIM);
|
|
1606
|
+
run(pass, "slice_cols", [
|
|
1607
|
+
["u", S],
|
|
1608
|
+
["u", VALDIM],
|
|
1609
|
+
["u", CONVDIM],
|
|
1610
|
+
["u", 2 * KEYDIM]
|
|
1611
|
+
], [convd], v, S * VALDIM);
|
|
1612
|
+
const a = actBuf(S * NV), b = actBuf(S * NV);
|
|
1613
|
+
fusedMM(pass, w("linear.a"), n1, S, [
|
|
1614
|
+
a,
|
|
1615
|
+
dummy,
|
|
1616
|
+
dummy2
|
|
1617
|
+
]);
|
|
1618
|
+
fusedMM(pass, w("linear.b"), n1, S, [
|
|
1619
|
+
b,
|
|
1620
|
+
dummy,
|
|
1621
|
+
dummy2
|
|
1622
|
+
]);
|
|
1623
|
+
const gb = actBuf(2 * S * NV);
|
|
1624
|
+
run(pass, "deltanet_gbeta", [
|
|
1625
|
+
["u", S],
|
|
1626
|
+
["u", NV],
|
|
1627
|
+
["u", 0],
|
|
1628
|
+
["u", 0]
|
|
1629
|
+
], [
|
|
1630
|
+
a,
|
|
1631
|
+
b,
|
|
1632
|
+
w("linear.A_log").buf,
|
|
1633
|
+
w("linear.dt_bias").buf
|
|
1634
|
+
], gb, S * NV);
|
|
1635
|
+
const core = actBuf(S * VALDIM);
|
|
1636
|
+
setup(pass, "deltanet_recur", [
|
|
1637
|
+
["u", S],
|
|
1638
|
+
["u", NV],
|
|
1639
|
+
["u", DKV],
|
|
1640
|
+
["u", DKV],
|
|
1641
|
+
["u", NK],
|
|
1642
|
+
["u", S * NV],
|
|
1643
|
+
["u", ls],
|
|
1644
|
+
["u", 0]
|
|
1645
|
+
], [
|
|
1646
|
+
q,
|
|
1647
|
+
k,
|
|
1648
|
+
v,
|
|
1649
|
+
gb,
|
|
1650
|
+
gb,
|
|
1651
|
+
hyRS[li][par]
|
|
1652
|
+
], [core, hyRS[li][par ^ 1]]);
|
|
1653
|
+
pass.dispatchWorkgroups(NV);
|
|
1654
|
+
const z = actBuf(S * VALDIM);
|
|
1655
|
+
fusedMM(pass, w("linear.z"), n1, S, [
|
|
1656
|
+
z,
|
|
1657
|
+
dummy,
|
|
1658
|
+
dummy2
|
|
1659
|
+
]);
|
|
1660
|
+
const normed = actBuf(S * VALDIM);
|
|
1661
|
+
runN(pass, "deltanet_norm_gate", [
|
|
1662
|
+
["u", S * NV],
|
|
1663
|
+
["u", DKV],
|
|
1664
|
+
["f", A.rms_eps],
|
|
1665
|
+
["u", 0]
|
|
1666
|
+
], [
|
|
1667
|
+
core,
|
|
1668
|
+
z,
|
|
1669
|
+
w("linear.norm").buf
|
|
1670
|
+
], normed, S * NV);
|
|
1671
|
+
h2 = actBuf(S * Hd);
|
|
1672
|
+
residMM(pass, w("linear.out_proj"), normed, h, S, h2);
|
|
1673
|
+
} else {
|
|
1674
|
+
const qg = actBuf(S * H * Dh * 2);
|
|
1675
|
+
fusedMM(pass, w("attn.q_proj"), n1, S, [
|
|
1676
|
+
qg,
|
|
1677
|
+
dummy,
|
|
1678
|
+
dummy2
|
|
1679
|
+
]);
|
|
1680
|
+
const query = actBuf(S * H * Dh), gate = actBuf(S * H * Dh);
|
|
1681
|
+
run(pass, "split_head", [
|
|
1682
|
+
["u", S],
|
|
1683
|
+
["u", H],
|
|
1684
|
+
["u", Dh],
|
|
1685
|
+
["u", 0]
|
|
1686
|
+
], [qg], query, S * H * Dh);
|
|
1687
|
+
run(pass, "split_head", [
|
|
1688
|
+
["u", S],
|
|
1689
|
+
["u", H],
|
|
1690
|
+
["u", Dh],
|
|
1691
|
+
["u", Dh]
|
|
1692
|
+
], [qg], gate, S * H * Dh);
|
|
1693
|
+
const qn = actBuf(S * H * Dh), qr = actBuf(S * H * Dh);
|
|
1694
|
+
rms(pass, query, `layers.${li}.attn.q_norm`, S * H, Dh, qn);
|
|
1695
|
+
run(pass, "rope_partial", [
|
|
1696
|
+
["u", S],
|
|
1697
|
+
["u", H],
|
|
1698
|
+
["u", Dh],
|
|
1699
|
+
["u", ROPE_D]
|
|
1700
|
+
], [
|
|
1701
|
+
qn,
|
|
1702
|
+
cos,
|
|
1703
|
+
sin
|
|
1704
|
+
], qr, S * H * Dh);
|
|
1705
|
+
const kk = actBuf(S * KV * Dh);
|
|
1706
|
+
fusedMM(pass, w("attn.k_proj"), n1, S, [
|
|
1707
|
+
kk,
|
|
1708
|
+
dummy,
|
|
1709
|
+
dummy2
|
|
1710
|
+
]);
|
|
1711
|
+
const kn = actBuf(S * KV * Dh), kr = actBuf(S * KV * Dh);
|
|
1712
|
+
rms(pass, kk, `layers.${li}.attn.k_norm`, S * KV, Dh, kn);
|
|
1713
|
+
run(pass, "rope_partial", [
|
|
1714
|
+
["u", S],
|
|
1715
|
+
["u", KV],
|
|
1716
|
+
["u", Dh],
|
|
1717
|
+
["u", ROPE_D]
|
|
1718
|
+
], [
|
|
1719
|
+
kn,
|
|
1720
|
+
cos,
|
|
1721
|
+
sin
|
|
1722
|
+
], kr, S * KV * Dh);
|
|
1723
|
+
const vv = actBuf(S * KV * Dh);
|
|
1724
|
+
fusedMM(pass, w("attn.v_proj"), n1, S, [
|
|
1725
|
+
vv,
|
|
1726
|
+
dummy,
|
|
1727
|
+
dummy2
|
|
1728
|
+
]);
|
|
1729
|
+
appendKV(pass, kr, 0, li, S * KV, posBase * KV);
|
|
1730
|
+
appendKV(pass, vv, 1, li, S * KV, posBase * KV);
|
|
1731
|
+
const att = actBuf(S * H * Dh);
|
|
1732
|
+
const aP = [
|
|
1733
|
+
["u", S],
|
|
1734
|
+
["u", H],
|
|
1735
|
+
["u", KV],
|
|
1736
|
+
["u", Dh],
|
|
1737
|
+
["f", 1 / Math.sqrt(Dh)],
|
|
1738
|
+
["u", posBase],
|
|
1739
|
+
["u", 0],
|
|
1740
|
+
["u", 0]
|
|
1741
|
+
];
|
|
1742
|
+
if (kv8) runN(pass, "attention_online_cache_kv8", aP, [
|
|
1743
|
+
qr,
|
|
1744
|
+
Kc[li],
|
|
1745
|
+
Ksc[li],
|
|
1746
|
+
Vc[li],
|
|
1747
|
+
Vsc[li]
|
|
1748
|
+
], att, S * H);
|
|
1749
|
+
else runN(pass, "attention_online_cache", aP, [
|
|
1750
|
+
qr,
|
|
1751
|
+
Kc[li],
|
|
1752
|
+
Vc[li]
|
|
1753
|
+
], att, S * H);
|
|
1754
|
+
const gated = actBuf(S * H * Dh);
|
|
1755
|
+
run(pass, "gate_sigmoid", [
|
|
1756
|
+
["u", S * H * Dh],
|
|
1757
|
+
["u", 0],
|
|
1758
|
+
["u", 0],
|
|
1759
|
+
["u", 0]
|
|
1760
|
+
], [att, gate], gated, S * H * Dh);
|
|
1761
|
+
h2 = actBuf(S * Hd);
|
|
1762
|
+
residMM(pass, w("attn.o_proj"), gated, h, S, h2);
|
|
1763
|
+
}
|
|
1764
|
+
const n2 = actBuf(S * Hd);
|
|
1765
|
+
rms(pass, h2, `layers.${li}.post_attention_layernorm`, S, Hd, n2);
|
|
1766
|
+
const g = actBuf(S * F), u = actBuf(S * F);
|
|
1767
|
+
fusedMM(pass, w("mlp.gate_proj"), n2, S, [
|
|
1768
|
+
g,
|
|
1769
|
+
dummy,
|
|
1770
|
+
dummy2
|
|
1771
|
+
]);
|
|
1772
|
+
fusedMM(pass, w("mlp.up_proj"), n2, S, [
|
|
1773
|
+
u,
|
|
1774
|
+
dummy,
|
|
1775
|
+
dummy2
|
|
1776
|
+
]);
|
|
1777
|
+
const sw = actBuf(S * F);
|
|
1778
|
+
run(pass, "swiglu", [
|
|
1779
|
+
["u", S * F],
|
|
1780
|
+
["u", 0],
|
|
1781
|
+
["u", 0],
|
|
1782
|
+
["u", 0]
|
|
1783
|
+
], [g, u], sw, S * F);
|
|
1784
|
+
const hn = actBuf(S * Hd);
|
|
1785
|
+
residMM(pass, w("mlp.down_proj"), sw, h2, S, hn);
|
|
1786
|
+
return hn;
|
|
1787
|
+
}
|
|
1455
1788
|
function layer(pass, li, h, S, posBase, cos, sin) {
|
|
1456
1789
|
const Ltot = posBase + S;
|
|
1790
|
+
if (manifest.arch.hybrid) return hybridLayer(pass, li, h, S, posBase, cos, sin);
|
|
1457
1791
|
const af = actF16 && S === 1 && !FORCE_SLOW;
|
|
1458
1792
|
const n1 = af ? actBuf16(Hd) : actBuf(S * Hd);
|
|
1459
1793
|
rms(pass, h, `layers.${li}.input_layernorm`, S, Hd, n1, af);
|
|
@@ -1684,6 +2018,7 @@ async function createEngineInner(options, holder) {
|
|
|
1684
2018
|
cur = layer(pass, li, cur, S, posBase, cos, sin);
|
|
1685
2019
|
if (li === 0) layer0 = cur;
|
|
1686
2020
|
}
|
|
2021
|
+
if (A.hybrid) hyPar ^= 1;
|
|
1687
2022
|
const fn = actBuf(S * Hd);
|
|
1688
2023
|
rms(pass, cur, FINAL_NORM, S, Hd, fn);
|
|
1689
2024
|
pass.end();
|
|
@@ -2525,9 +2860,10 @@ async function createEngineInner(options, holder) {
|
|
|
2525
2860
|
const ck = {};
|
|
2526
2861
|
for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
|
|
2527
2862
|
const off = pos * KV * Dh;
|
|
2528
|
-
if (!kv16 && !kv8) {
|
|
2529
|
-
|
|
2530
|
-
ck.
|
|
2863
|
+
if (!kv16 && !kv8 && kvLayers.length) {
|
|
2864
|
+
const dl = kvLayers[0];
|
|
2865
|
+
ck.kc = (await readback(Kc[dl], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
|
|
2866
|
+
ck.vc = (await readback(Vc[dl], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
|
|
2531
2867
|
}
|
|
2532
2868
|
ck.fn = await readback(r.fn, Hd);
|
|
2533
2869
|
ck.logits = await readback(lg, W.lm_head.N);
|
|
@@ -2762,22 +3098,24 @@ async function createEngineInner(options, holder) {
|
|
|
2762
3098
|
}
|
|
2763
3099
|
const kvRowBytes = KV * Dh * KVB;
|
|
2764
3100
|
const scRowBytes = kv8 ? KV * (Dh / 32) * 4 : 0;
|
|
2765
|
-
const snapshotBytes = (len) => A.layers * 2 * len * (kvRowBytes + scRowBytes);
|
|
3101
|
+
const snapshotBytes = (len) => (A.hybrid ? kvLayers.length : A.layers) * 2 * len * (kvRowBytes + scRowBytes) + linearLayers.length * (rsSz + csSz);
|
|
2766
3102
|
async function saveCache(opts) {
|
|
2767
3103
|
if (fullHistory.length === 0) return null;
|
|
2768
3104
|
const len = roll ? cacheLen : fullHistory.length - 1;
|
|
2769
3105
|
const base = Math.max(0, Math.min(Math.floor(opts?.from ?? 0), len));
|
|
2770
3106
|
if (base > 0 && roll) throw new Error("saveCache: delta snapshots ({ from }) are not supported under overflow 'sinks'");
|
|
3107
|
+
if (base > 0 && A.hybrid) throw new Error("saveCache: delta snapshots ({ from }) are not supported for the qwen3_5 hybrid backbone");
|
|
2771
3108
|
const count = len - base;
|
|
2772
|
-
const
|
|
2773
|
-
|
|
3109
|
+
const bytes = snapshotBytes(count);
|
|
3110
|
+
const data = new ArrayBuffer(bytes);
|
|
3111
|
+
if (bytes > 0) {
|
|
2774
3112
|
const rb = device.createBuffer({
|
|
2775
|
-
size:
|
|
3113
|
+
size: bytes,
|
|
2776
3114
|
usage: GPUBufferUsage.MAP_READ | CD
|
|
2777
3115
|
});
|
|
2778
3116
|
const enc = device.createCommandEncoder();
|
|
2779
3117
|
let off = 0;
|
|
2780
|
-
|
|
3118
|
+
if (count > 0) for (const li of kvLayers) {
|
|
2781
3119
|
enc.copyBufferToBuffer(Kc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
|
|
2782
3120
|
off += count * kvRowBytes;
|
|
2783
3121
|
enc.copyBufferToBuffer(Vc[li], base * kvRowBytes, rb, off, count * kvRowBytes);
|
|
@@ -2789,6 +3127,12 @@ async function createEngineInner(options, holder) {
|
|
|
2789
3127
|
off += count * scRowBytes;
|
|
2790
3128
|
}
|
|
2791
3129
|
}
|
|
3130
|
+
for (const li of linearLayers) {
|
|
3131
|
+
enc.copyBufferToBuffer(hyRS[li][hyPar], 0, rb, off, rsSz);
|
|
3132
|
+
off += rsSz;
|
|
3133
|
+
enc.copyBufferToBuffer(hyCS[li][hyPar], 0, rb, off, csSz);
|
|
3134
|
+
off += csSz;
|
|
3135
|
+
}
|
|
2792
3136
|
device.queue.submit([enc.finish()]);
|
|
2793
3137
|
await rb.mapAsync(GPUMapMode.READ);
|
|
2794
3138
|
new Uint8Array(data).set(new Uint8Array(rb.getMappedRange()));
|
|
@@ -2824,6 +3168,7 @@ async function createEngineInner(options, holder) {
|
|
|
2824
3168
|
if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error("restoreCache: snapshot holds no tokens");
|
|
2825
3169
|
const len = snap.version === 2 ? snap.roll.cacheLen : snap.ids.length - 1;
|
|
2826
3170
|
const base = Math.max(0, Math.floor(snap.base ?? 0));
|
|
3171
|
+
if (base > 0 && A.hybrid) throw new Error("restoreCache: delta snapshots are not supported for the qwen3_5 hybrid backbone");
|
|
2827
3172
|
const count = len - base;
|
|
2828
3173
|
if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
|
|
2829
3174
|
if (snap.data.byteLength !== snapshotBytes(count)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(count)}`);
|
|
@@ -2833,7 +3178,7 @@ async function createEngineInner(options, holder) {
|
|
|
2833
3178
|
}
|
|
2834
3179
|
await ensureKvCapacity(len);
|
|
2835
3180
|
let off = 0;
|
|
2836
|
-
|
|
3181
|
+
if (count > 0) for (const li of kvLayers) {
|
|
2837
3182
|
device.queue.writeBuffer(Kc[li], base * kvRowBytes, snap.data, off, count * kvRowBytes);
|
|
2838
3183
|
off += count * kvRowBytes;
|
|
2839
3184
|
device.queue.writeBuffer(Vc[li], base * kvRowBytes, snap.data, off, count * kvRowBytes);
|
|
@@ -2845,6 +3190,13 @@ async function createEngineInner(options, holder) {
|
|
|
2845
3190
|
off += count * scRowBytes;
|
|
2846
3191
|
}
|
|
2847
3192
|
}
|
|
3193
|
+
for (const li of linearLayers) {
|
|
3194
|
+
device.queue.writeBuffer(hyRS[li][0], 0, snap.data, off, rsSz);
|
|
3195
|
+
off += rsSz;
|
|
3196
|
+
device.queue.writeBuffer(hyCS[li][0], 0, snap.data, off, csSz);
|
|
3197
|
+
off += csSz;
|
|
3198
|
+
}
|
|
3199
|
+
if (A.hybrid) hyPar = 0;
|
|
2848
3200
|
fullHistory = [...snap.ids];
|
|
2849
3201
|
cacheLen = len;
|
|
2850
3202
|
}
|