bitgpu 0.1.0 → 0.3.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 +12 -0
- package/dist/index.d.ts +11 -1
- package/dist/index.js +55 -33
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -122,6 +122,18 @@ Or open `http://localhost:8000/examples/verify.html` in a WebGPU browser and cli
|
|
|
122
122
|
gate on real hardware before every release; CI covers only the CPU-checkable parts (types, sampler
|
|
123
123
|
math, drafter, packaging).
|
|
124
124
|
|
|
125
|
+
### Releasing
|
|
126
|
+
|
|
127
|
+
Publishing runs through GitHub Actions with npm trusted publishing (OIDC + provenance, no token).
|
|
128
|
+
After the GPU gate passes locally: bump `version` in package.json, commit, then
|
|
129
|
+
|
|
130
|
+
```sh
|
|
131
|
+
git tag v0.1.1 && git push origin main v0.1.1
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The release workflow re-runs the CPU checks, verifies the tag matches the package version, and
|
|
135
|
+
publishes.
|
|
136
|
+
|
|
125
137
|
The WGSL kernels live in `shaders/` and are inlined into the bundle at build time (no runtime
|
|
126
138
|
`fetch`). `scripts/gen-shaders.ts` does the inlining.
|
|
127
139
|
|
package/dist/index.d.ts
CHANGED
|
@@ -35,8 +35,16 @@ interface EngineOptions {
|
|
|
35
35
|
syncSteps?: number;
|
|
36
36
|
/** Prefill GEMM tiling: `'auto'` tiles once a prompt fills the 64-row tiles, `'always'`/`'never'` force it. Default `'auto'`. */
|
|
37
37
|
prefillTiling?: 'auto' | 'always' | 'never';
|
|
38
|
-
/** Max KV-cache length (prompt + generated positions). Caps VRAM (~`maxSeqLen` x 224 KB
|
|
38
|
+
/** Max KV-cache length (prompt + generated positions). Caps VRAM (~`maxSeqLen` x 224 KB at f32,
|
|
39
|
+
* half that with `kvCache: 'f16'`). Default `2048`. */
|
|
39
40
|
maxSeqLen?: number;
|
|
41
|
+
/** KV-cache STORAGE precision. `'f16'` halves KV memory (the industry-standard choice: all
|
|
42
|
+
* arithmetic stays f32; each cached K/V value is rounded once at cache-write). Outputs are no
|
|
43
|
+
* longer guaranteed bit-identical to f32 mode, though within f16 mode decoding stays exact and
|
|
44
|
+
* deterministic (same seed -> same tokens; cache reuse == full prefill). Falls back to `'f32'`
|
|
45
|
+
* silently when the adapter lacks `shader-f16` (see `capabilities.kvCache` for what's active).
|
|
46
|
+
* Default `'f32'`. */
|
|
47
|
+
kvCache?: 'f32' | 'f16';
|
|
40
48
|
/** Called as the model loads. */
|
|
41
49
|
onProgress?: (progress: LoadProgress) => void;
|
|
42
50
|
/** Called if the GPU device is lost after creation (driver reset, OS reclaim, tab backgrounding
|
|
@@ -129,6 +137,8 @@ interface EngineCapabilities {
|
|
|
129
137
|
useSubgroups: boolean;
|
|
130
138
|
/** Subgroup width when the subgroup path is active. */
|
|
131
139
|
subgroupSize: number;
|
|
140
|
+
/** Active KV-cache storage precision ('f16' only when requested AND the adapter has shader-f16). */
|
|
141
|
+
kvCache: 'f32' | 'f16';
|
|
132
142
|
/** Adapter identification, when the browser exposes it. */
|
|
133
143
|
adapter: {
|
|
134
144
|
vendor?: string;
|
package/dist/index.js
CHANGED
|
@@ -3,9 +3,12 @@ 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
|
-
"
|
|
7
|
-
"
|
|
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
|
+
"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_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",
|
|
9
|
+
"attention_wg_kv16": "// attention_wg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_wg.wgsl: the ONLY difference is Kc/Vc are array<f16>, widened to f32 at the read.\nenable f16;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { part = part + q[qb + d] * f32(Kc[kb + d]); }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
|
|
8
10
|
"copy": "// Copy src[0..n) into dst[dstOff..dstOff+n). Used to append K/V into the persistent cache.\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = src[i];\n}\n",
|
|
11
|
+
"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",
|
|
9
12
|
"embed_gather": "// GPU embedding gather + 4-bit dequant: reads a token id from a GPU buffer and writes that token's\n// embedding (H f32) directly into a GPU buffer, so the decode loop never round-trips the token id to\n// the CPU. Faithful port of the CPU embedDequant (4-bit codes via the tgt4 LUT, per-128 zero-point,\n// per-block scale). uint8 source arrays are read as u32 and byte-extracted (little-endian).\noverride WG: u32 = 256u;\nstruct Params { H: u32, srcIdx: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> tokenId: array<u32>; // tokenId[p.srcIdx] = the token to embed\n@group(0) @binding(2) var<storage, read> embWq: array<u32>; // uint8 [vocab*256] 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*16]\n@group(0) @binding(5) var<storage, read> embZp: array<u32>; // uint8 [vocab*8] 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 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 * 256u + 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 * 8u + (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 * 16u + blk];\n }\n}\n",
|
|
10
13
|
"matmul_binary_vec4": "// Binary matmul, vectorized: y[M,N] = x[M,K] @ W[N,K]^T, W = (+/-1) * per-block scale.\n// One thread per output; the K loop processes a 32-bit sign word at a time and the\n// activations as vec4 via dot() (4 weights per FMA instead of 1 scalar op). M-agnostic\n// (works for prefill M=S and decode M=1). x is bound as vec4 (K must be a multiple of 4).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, _pad: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xRow = m * (p.K / 4u);\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let wordsPerBlock = p.block / 32u; // 4 for block=128\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n for (var w = 0u; w < wordsPerBlock; w = w + 1u) {\n let word = signbits[wRow + b * wordsPerBlock + w];\n let xb = xRow + b * (p.block / 4u) + w * 8u; // vec4 base for this word (32 weights = 8 vec4)\n for (var g = 0u; g < 8u; g = g + 1u) {\n let bits4 = (word >> (g * 4u)) & 0xfu;\n let sv = vec4<f32>(\n select(-1.0, 1.0, (bits4 & 1u) != 0u),\n select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u),\n select(-1.0, 1.0, (bits4 & 8u) != 0u),\n );\n bsum = bsum + dot(x[xb + g], sv);\n }\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
|
|
11
14
|
"matmul_q2": "// 2-bit dequant matmul (lm_head): y[M,N] = x[M,K] @ W[N,K]^T, W[n,k] = (code - zp) * scale[n, k/block].\n// codes are 2-bit, 4 per byte, packed into u32 words. Correctness-first (one thread per output, fp32).\nstruct Params { M: u32, N: u32, K: u32, nb: u32, block: u32, zp: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [M, K]\n@group(0) @binding(2) var<storage, read> codes: array<u32>; // [N, K/4] bytes packed as u32\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [M, N]\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let idx = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (idx >= p.M * p.N) { return; }\n let m = idx / p.N;\n let n = idx % p.N;\n let xbase = m * p.K;\n let cbyteBase = n * (p.K / 4u); // byte offset of row n in the codes stream\n let sbase = n * p.nb;\n let zpf = f32(p.zp);\n\n var acc = 0.0;\n for (var b = 0u; b < p.nb; b = b + 1u) {\n var bsum = 0.0;\n let k0 = b * p.block;\n for (var j = 0u; j < p.block; j = j + 1u) {\n let k = k0 + j;\n let byteIdx = cbyteBase + (k >> 2u);\n let word = codes[byteIdx >> 2u];\n let byte = (word >> (8u * (byteIdx & 3u))) & 0xffu;\n let code = (byte >> (2u * (k & 3u))) & 3u;\n bsum = bsum + (f32(code) - zpf) * x[xbase + k];\n }\n acc = acc + bsum * scales[sbase + b];\n }\n y[idx] = acc;\n}\n",
|
|
@@ -23,9 +26,10 @@ const SHADERS = {
|
|
|
23
26
|
"matmul_split_tiled": "// Tiled register-blocked binary GEMM to 3 outputs (qkv or gate/up), PREFILL (M>1), vec4 K-accum.\n// Weights concatenated along N (N0|N1|N2); each 64-wide tile lies in one range (N0,N1 multiples of 64)\n// so a workgroup routes its whole tile to out0/out1/out2. Same vec4 design as matmul_resid_tiled.\nconst BM: u32 = 64u;\nconst BN: u32 = 64u;\nconst BKV: u32 = 4u; // BK / 4 (BK = 16)\nstruct Params { M: u32, K: u32, nb: u32, N0: u32, N1: u32, N2: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [M, K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\n\nvar<workgroup> xs: array<vec4<f32>, 256>;\nvar<workgroup> ws: array<vec4<f32>, 256>;\n\n@compute @workgroup_size(256)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let tid = lid.x;\n let tileM = wg.y * BM;\n let tileN = wg.x * BN;\n let tr = (tid / 16u) * 4u;\n let tc = (tid % 16u) * 4u;\n let Kv = p.K / 4u;\n var acc: array<f32, 16>;\n for (var i = 0u; i < 16u; i = i + 1u) { acc[i] = 0.0; }\n\n let Ksteps = Kv / BKV;\n for (var ks = 0u; ks < Ksteps; ks = ks + 1u) {\n let k0v = ks * BKV;\n for (var e = tid; e < BM * BKV; e = e + 256u) {\n let m = e / BKV; let kv = e % BKV; let gm = tileM + m;\n xs[e] = select(vec4<f32>(0.0), x[gm * Kv + (k0v + kv)], gm < p.M);\n }\n for (var e = tid; e < BN * BKV; e = e + 256u) {\n let n = e / BKV; let kv = e % BKV; let gn = tileN + n; let k = (k0v + kv) * 4u;\n var wv = vec4<f32>(0.0);\n if (gn < Ntot) {\n let bits4 = (signbits[gn * (p.K / 32u) + (k >> 5u)] >> (k & 31u)) & 0xfu;\n let s = scales[gn * p.nb + (k / 128u)];\n wv = vec4<f32>(select(-s, s, (bits4 & 1u) != 0u), select(-s, s, (bits4 & 2u) != 0u),\n select(-s, s, (bits4 & 4u) != 0u), select(-s, s, (bits4 & 8u) != 0u));\n }\n ws[e] = wv;\n }\n workgroupBarrier();\n for (var kv = 0u; kv < BKV; kv = kv + 1u) {\n var xr: array<vec4<f32>, 4>;\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { xr[tm] = xs[(tr + tm) * BKV + kv]; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let w = ws[(tc + tn) * BKV + kv];\n for (var tm = 0u; tm < 4u; tm = tm + 1u) { acc[tm * 4u + tn] = acc[tm * 4u + tn] + dot(xr[tm], w); }\n }\n }\n workgroupBarrier();\n }\n\n for (var tm = 0u; tm < 4u; tm = tm + 1u) {\n let gm = tileM + tr + tm;\n if (gm >= p.M) { continue; }\n for (var tn = 0u; tn < 4u; tn = tn + 1u) {\n let gn = tileN + tc + tn;\n if (gn >= Ntot) { continue; }\n let v = acc[tm * 4u + tn];\n if (gn < p.N0) { out0[gm * p.N0 + gn] = v; }\n else if (gn < p.N0 + p.N1) { out1[gm * p.N1 + (gn - p.N0)] = v; }\n else { out2[gm * p.N2 + (gn - p.N0 - p.N1)] = v; }\n }\n }\n}\n",
|
|
24
27
|
"matmul_split_wg": "// No-subgroup fallback: split-K GEMV for decode (M=1), workgroup-shared-memory reduction instead\n// of subgroupAdd. One workgroup per output column; WG threads split K and tree-reduce via shared\n// memory + barriers. ~WG-fold faster than one-thread-per-output (the v1 path). Routes qkv / gate-up.\noverride WG: u32 = 64u;\nstruct Params { K: u32, nb: u32, N0: u32, N1: u32, N2: u32, gridX: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [N0+N1+N2, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [N0+N1+N2, nb]\n@group(0) @binding(4) var<storage, read_write> out0: array<f32>;\n@group(0) @binding(5) var<storage, read_write> out1: array<f32>;\n@group(0) @binding(6) var<storage, read_write> out2: array<f32>;\nvar<workgroup> sdata: array<f32, 256>; // >= max WG\n\n@compute @workgroup_size(WG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let Ntot = p.N0 + p.N1 + p.N2;\n let n = wg.y * p.gridX + wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (n >= Ntot) { return; }\n let tid = lid.x;\n let wRow = n * (p.K / 32u);\n let sbase = n * p.nb;\n let Kvec = p.K / 4u;\n var acc = 0.0;\n for (var gi = tid; gi < Kvec; gi = gi + WG) {\n let k = gi * 4u;\n let word = signbits[wRow + (k >> 5u)];\n let bits4 = (word >> (k & 31u)) & 0xfu;\n let sv = vec4<f32>(select(-1.0, 1.0, (bits4 & 1u) != 0u), select(-1.0, 1.0, (bits4 & 2u) != 0u),\n select(-1.0, 1.0, (bits4 & 4u) != 0u), select(-1.0, 1.0, (bits4 & 8u) != 0u));\n acc = acc + dot(x[gi], sv) * scales[sbase + (k / 128u)];\n }\n sdata[tid] = acc;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) { sdata[tid] = sdata[tid] + sdata[tid + s]; }\n workgroupBarrier();\n }\n if (tid == 0u) {\n let total = sdata[0];\n if (n < p.N0) { out0[n] = total; }\n else if (n < p.N0 + p.N1) { out1[n - p.N0] = total; }\n else { out2[n - p.N0 - p.N1] = total; }\n }\n}\n",
|
|
25
28
|
"matmul_swiglu_mr_sg": "// Multi-row fused gate/up GEMV + SwiGLU for decode (M=1). Each workgroup computes ROWS\n// intermediate indices; per K-step it issues 2*ROWS independent weight loads (gate row n and up\n// row F+n for each of the ROWS) before the dots, giving the bandwidth-bound decode GEMV more\n// in-flight memory requests. One subgroup per workgroup; lanes split K; reduced with subgroupAdd.\nenable subgroups;\noverride SG: u32 = 32u;\noverride ROWS: u32 = 4u;\nstruct Params { K: u32, nb: u32, F: u32, gridX: u32, _p0: u32, _p1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<vec4<f32>>; // [K/4]\n@group(0) @binding(2) var<storage, read> signbits: array<u32>; // [2F, K/32]\n@group(0) @binding(3) var<storage, read> scales: array<f32>; // [2F, nb]\n@group(0) @binding(4) var<storage, read_write> y: array<f32>; // [F]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let nBase = (wg.y * p.gridX + wg.x) * ROWS;\n let Kvec = p.K / 4u;\n let wStride = p.K / 32u;\n\n var g: array<f32, 8>; // ROWS <= 8\n var u: array<f32, 8>;\n for (var r = 0u; r < ROWS; r = r + 1u) { g[r] = 0.0; u[r] = 0.0; }\n for (var gi = lane; gi < Kvec; gi = gi + SG) {\n let k = gi * 4u;\n let xv = x[gi];\n let widx = k >> 5u;\n let sh = k & 31u;\n let sc = k / 128u;\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n if (n < p.F) {\n let gw = (signbits[n * wStride + widx] >> sh) & 0xfu;\n let gv = vec4<f32>(select(-1.0, 1.0, (gw & 1u) != 0u), select(-1.0, 1.0, (gw & 2u) != 0u),\n select(-1.0, 1.0, (gw & 4u) != 0u), select(-1.0, 1.0, (gw & 8u) != 0u));\n g[r] = g[r] + dot(xv, gv) * scales[n * p.nb + sc];\n let uw = (signbits[(p.F + n) * wStride + widx] >> sh) & 0xfu;\n let uv = vec4<f32>(select(-1.0, 1.0, (uw & 1u) != 0u), select(-1.0, 1.0, (uw & 2u) != 0u),\n select(-1.0, 1.0, (uw & 4u) != 0u), select(-1.0, 1.0, (uw & 8u) != 0u));\n u[r] = u[r] + dot(xv, uv) * scales[(p.F + n) * p.nb + sc];\n }\n }\n }\n for (var r = 0u; r < ROWS; r = r + 1u) {\n let n = nBase + r;\n let gt = subgroupAdd(g[r]);\n let ut = subgroupAdd(u[r]);\n if (lane == 0u && n < p.F) { y[n] = (gt / (1.0 + exp(-gt))) * ut; }\n }\n}\n",
|
|
26
|
-
"rmsnorm": "// RMSNorm: y[r,d] = x[r,d] / sqrt(mean_d(x^2) + eps) * gamma[d]. One invocation per row.\nstruct Params { R: u32, D: u32, eps: f32, _pad: u32 };\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]\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 r = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (r >= p.R) { return; }\n let base = r * p.D;\n var ss = 0.0;\n for (var d = 0u; d < p.D; d = d + 1u) {\n let v = x[base + d];\n ss = ss + v * v;\n }\n let inv = inverseSqrt(ss / f32(p.D) + p.eps);\n for (var d = 0u; d < p.D; d = d + 1u) {\n y[base + d] = x[base + d] * inv * gamma[d];\n }\n}\n",
|
|
27
29
|
"rmsnorm_rope_sg": "// Fused per-head RMSNorm + RoPE for decode (S=1). One subgroup (= one workgroup) per head row;\n// lanes split head_dim, reduce sum-of-squares with subgroupAdd, then apply rope. rotate_half\n// pairs (d, d+-D/2): with SG>=32 and D=128 a lane owns d in {lane, lane+32, lane+64, lane+96},\n// so every (d, d+-64) pair is held by the same lane (no cross-lane reads for the rotate).\n// outOff/outStride let the K result write straight into the KV cache at its position.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outOff: u32, outStride: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> x: array<f32>; // [R, D]\n@group(0) @binding(2) var<storage, read> gamma: array<f32>; // [D]\n@group(0) @binding(3) var<storage, read> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> y: array<f32>; // [outOff + R*outStride]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let ob = p.outOff + row * p.outStride;\n for (var i = lane; i < p.D; i = i + SG) {\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n y[ob + i] = nd * cos[i] + rot * sin[i];\n }\n}\n",
|
|
30
|
+
"rmsnorm_rope_sg_kv16": "// rmsnorm_rope_sg writing into an f16-STORAGE KV cache (kvCache: 'f16'): used ONLY for the K\n// projection on the fused decode path, where the normed+roped K is written straight into the\n// cache. Keep in lockstep with rmsnorm_rope_sg.wgsl: the ONLY difference is y is array<f16>\n// (one f32 -> f16 rounding at the write). The q call keeps the f32 kernel.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { R: u32, D: u32, eps: f32, outOff: u32, outStride: u32, _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> cos: array<f32>; // [D]\n@group(0) @binding(4) var<storage, read> sin: array<f32>; // [D]\n@group(0) @binding(5) var<storage, read_write> y: array<f16>; // [outOff + R*outStride]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let row = wg.x;\n if (row >= p.R) { return; }\n let base = row * p.D;\n var s = 0.0;\n for (var i = lane; i < p.D; i = i + SG) { let v = x[base + i]; s = s + v * v; }\n let inv = inverseSqrt(subgroupAdd(s) / f32(p.D) + p.eps);\n let half = p.D / 2u;\n let ob = p.outOff + row * p.outStride;\n for (var i = lane; i < p.D; i = i + SG) {\n let nd = x[base + i] * inv * gamma[i];\n var pd: u32; var sgn: f32;\n if (i < half) { pd = i + half; sgn = -1.0; } else { pd = i - half; sgn = 1.0; }\n let rot = sgn * (x[base + pd] * inv * gamma[pd]);\n y[ob + i] = f16(nd * cos[i] + rot * sin[i]);\n }\n}\n",
|
|
28
31
|
"rmsnorm_sg": "// RMSNorm, subgroup-parallel: one subgroup (= one workgroup) per row; lanes split D and\n// reduce the sum-of-squares with subgroupAdd (register-only, no barriers/shared memory).\n// Fixes the decode bottleneck where R=1 ran on a single thread. SG is set from the device's\n// subgroup size at pipeline creation; requires workgroup_size == subgroup size.\nenable subgroups;\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<f32>;\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); // sum across the subgroup, broadcast to all lanes\n let inv = inverseSqrt(total / f32(p.D) + p.eps);\n for (var i = lane; i < p.D; i = i + SG) { y[base + i] = x[base + i] * inv * gamma[i]; }\n}\n",
|
|
32
|
+
"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",
|
|
29
33
|
"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",
|
|
30
34
|
"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",
|
|
31
35
|
"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"
|
|
@@ -187,10 +191,8 @@ const WGSLS = [
|
|
|
187
191
|
"matmul_split",
|
|
188
192
|
"matmul_resid",
|
|
189
193
|
"matmul_q2",
|
|
190
|
-
"rmsnorm",
|
|
191
194
|
"rope",
|
|
192
195
|
"swiglu",
|
|
193
|
-
"attention_cache",
|
|
194
196
|
"copy"
|
|
195
197
|
];
|
|
196
198
|
const DEFAULT_MAX_SEQ = 2048;
|
|
@@ -297,8 +299,13 @@ async function createEngine(options) {
|
|
|
297
299
|
const tiledPrefill = (S) => FORCETILE || !NOTILE && S >= 64;
|
|
298
300
|
const SYNC_N = Math.max(1, opts.syncSteps ?? 4);
|
|
299
301
|
const maxSeqLen = Math.max(1, opts.maxSeqLen ?? DEFAULT_MAX_SEQ);
|
|
300
|
-
const useSG = hasSG && sgMin === sgMax && (sgMax === 32 || sgMax === 64) && !forceNoSG;
|
|
301
|
-
const
|
|
302
|
+
const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && !forceNoSG;
|
|
303
|
+
const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
|
|
304
|
+
const KVB = kv16 ? 2 : 4;
|
|
305
|
+
const features = [];
|
|
306
|
+
if (useSG) features.push("subgroups");
|
|
307
|
+
if (kv16) features.push("shader-f16");
|
|
308
|
+
const device = await adapter.requestDevice({ requiredFeatures: features });
|
|
302
309
|
const lost = device.lost.then((info) => {
|
|
303
310
|
const li = {
|
|
304
311
|
reason: String(info.reason ?? "unknown"),
|
|
@@ -357,11 +364,23 @@ async function createEngine(options) {
|
|
|
357
364
|
SG: sgMax,
|
|
358
365
|
ROWS: ROWS_MR
|
|
359
366
|
}]);
|
|
360
|
-
} else
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
367
|
+
} else {
|
|
368
|
+
for (const n of [
|
|
369
|
+
"matmul_split_wg",
|
|
370
|
+
"matmul_resid_wg",
|
|
371
|
+
"matmul_q2_wg",
|
|
372
|
+
"rmsnorm_wg"
|
|
373
|
+
]) specs.push([n, { WG: WG_NS }]);
|
|
374
|
+
specs.push(["attention_wg"]);
|
|
375
|
+
}
|
|
376
|
+
if (kv16) {
|
|
377
|
+
specs.push(["copy_kv16"]);
|
|
378
|
+
if (useSG) for (const n of ["attention_sg_kv16", "rmsnorm_rope_sg_kv16"]) specs.push([n, { SG: sgMax }]);
|
|
379
|
+
else specs.push(["attention_wg_kv16"]);
|
|
380
|
+
}
|
|
381
|
+
const ATT = kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : useSG ? "attention_sg" : "attention_wg";
|
|
382
|
+
const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
|
|
383
|
+
const COPY_KV = kv16 ? "copy_kv16" : "copy";
|
|
365
384
|
await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
|
|
366
385
|
const S_ = GPUBufferUsage.STORAGE, CD = GPUBufferUsage.COPY_DST, CS = GPUBufferUsage.COPY_SRC, U = GPUBufferUsage.UNIFORM;
|
|
367
386
|
let transients = null;
|
|
@@ -552,25 +571,31 @@ async function createEngine(options) {
|
|
|
552
571
|
let kvCapacity = Math.min(maxSeqLen, 512);
|
|
553
572
|
const Kc = [], Vc = [];
|
|
554
573
|
for (let li = 0; li < A.layers; li++) {
|
|
555
|
-
Kc.push(
|
|
556
|
-
|
|
574
|
+
Kc.push(device.createBuffer({
|
|
575
|
+
size: kvCapacity * KV * Dh * KVB,
|
|
576
|
+
usage: S_ | CS | CD
|
|
577
|
+
}));
|
|
578
|
+
Vc.push(device.createBuffer({
|
|
579
|
+
size: kvCapacity * KV * Dh * KVB,
|
|
580
|
+
usage: S_ | CS | CD
|
|
581
|
+
}));
|
|
557
582
|
}
|
|
558
583
|
const loadOom = await device.popErrorScope();
|
|
559
584
|
if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~350 MB VRAM needed): ${loadOom.message}`);
|
|
560
585
|
async function ensureKvCapacity(needed) {
|
|
561
586
|
if (needed <= kvCapacity) return;
|
|
562
587
|
const newCap = Math.min(maxSeqLen, Math.max(needed, kvCapacity * 2));
|
|
563
|
-
const copyBytes = kvCapacity * KV * Dh *
|
|
588
|
+
const copyBytes = kvCapacity * KV * Dh * KVB;
|
|
564
589
|
device.pushErrorScope("out-of-memory");
|
|
565
590
|
const enc = device.createCommandEncoder();
|
|
566
591
|
const olds = [];
|
|
567
592
|
for (let li = 0; li < A.layers; li++) {
|
|
568
593
|
const nk = device.createBuffer({
|
|
569
|
-
size: newCap * KV * Dh *
|
|
594
|
+
size: newCap * KV * Dh * KVB,
|
|
570
595
|
usage: S_ | CS | CD
|
|
571
596
|
});
|
|
572
597
|
const nv = device.createBuffer({
|
|
573
|
-
size: newCap * KV * Dh *
|
|
598
|
+
size: newCap * KV * Dh * KVB,
|
|
574
599
|
usage: S_ | CS | CD
|
|
575
600
|
});
|
|
576
601
|
enc.copyBufferToBuffer(Kc[li], 0, nk, 0, copyBytes);
|
|
@@ -716,7 +741,7 @@ async function createEngine(options) {
|
|
|
716
741
|
["u", Dn],
|
|
717
742
|
["f", A.rms_eps],
|
|
718
743
|
["u", 0]
|
|
719
|
-
], [x, W[g].buf], out, R) :
|
|
744
|
+
], [x, W[g].buf], out, R) : runN(pass, "rmsnorm_wg", [
|
|
720
745
|
["u", R],
|
|
721
746
|
["u", Dn],
|
|
722
747
|
["f", A.rms_eps],
|
|
@@ -890,7 +915,7 @@ async function createEngine(options) {
|
|
|
890
915
|
k,
|
|
891
916
|
v
|
|
892
917
|
], gx, Math.ceil(Ntot / gx));
|
|
893
|
-
run(pass,
|
|
918
|
+
run(pass, COPY_KV, [
|
|
894
919
|
["u", KV * Dh],
|
|
895
920
|
["u", posBase * KV * Dh],
|
|
896
921
|
["u", 0],
|
|
@@ -910,7 +935,7 @@ async function createEngine(options) {
|
|
|
910
935
|
cos,
|
|
911
936
|
sin
|
|
912
937
|
], qr, H);
|
|
913
|
-
runN(pass,
|
|
938
|
+
runN(pass, ROPE_K, [
|
|
914
939
|
["u", KV],
|
|
915
940
|
["u", Dh],
|
|
916
941
|
["f", A.rms_eps],
|
|
@@ -925,7 +950,7 @@ async function createEngine(options) {
|
|
|
925
950
|
], Kc[li], KV);
|
|
926
951
|
cap(li, "qr", qr);
|
|
927
952
|
const att = actBuf(H * Dh);
|
|
928
|
-
runN(pass,
|
|
953
|
+
runN(pass, ATT, [
|
|
929
954
|
["u", 1],
|
|
930
955
|
["u", H],
|
|
931
956
|
["u", KV],
|
|
@@ -990,13 +1015,13 @@ async function createEngine(options) {
|
|
|
990
1015
|
cos,
|
|
991
1016
|
sin
|
|
992
1017
|
], kr, S * KV * Dh);
|
|
993
|
-
run(pass,
|
|
1018
|
+
run(pass, COPY_KV, [
|
|
994
1019
|
["u", S * KV * Dh],
|
|
995
1020
|
["u", posBase * KV * Dh],
|
|
996
1021
|
["u", 0],
|
|
997
1022
|
["u", 0]
|
|
998
1023
|
], [kr], Kc[li], S * KV * Dh);
|
|
999
|
-
run(pass,
|
|
1024
|
+
run(pass, COPY_KV, [
|
|
1000
1025
|
["u", S * KV * Dh],
|
|
1001
1026
|
["u", posBase * KV * Dh],
|
|
1002
1027
|
["u", 0],
|
|
@@ -1004,20 +1029,14 @@ async function createEngine(options) {
|
|
|
1004
1029
|
], [v], Vc[li], S * KV * Dh);
|
|
1005
1030
|
cap(li, "qr", qr);
|
|
1006
1031
|
const att = actBuf(S * H * Dh);
|
|
1007
|
-
|
|
1032
|
+
runN(pass, ATT, [
|
|
1008
1033
|
["u", S],
|
|
1009
1034
|
["u", H],
|
|
1010
1035
|
["u", KV],
|
|
1011
1036
|
["u", Dh],
|
|
1012
1037
|
["u", posBase],
|
|
1013
1038
|
["u", Ltot]
|
|
1014
|
-
]
|
|
1015
|
-
if (useSG) runN(pass, "attention_sg", attF, [
|
|
1016
|
-
qr,
|
|
1017
|
-
Kc[li],
|
|
1018
|
-
Vc[li]
|
|
1019
|
-
], att, S * H);
|
|
1020
|
-
else run(pass, "attention_cache", attF, [
|
|
1039
|
+
], [
|
|
1021
1040
|
qr,
|
|
1022
1041
|
Kc[li],
|
|
1023
1042
|
Vc[li]
|
|
@@ -1801,8 +1820,10 @@ async function createEngine(options) {
|
|
|
1801
1820
|
const ck = {};
|
|
1802
1821
|
for (const [name, b] of Object.entries(DBG0)) ck[name] = await readback(b, b.size / 4);
|
|
1803
1822
|
const off = pos * KV * Dh;
|
|
1804
|
-
|
|
1805
|
-
|
|
1823
|
+
if (!kv16) {
|
|
1824
|
+
ck.kc = (await readback(Kc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
|
|
1825
|
+
ck.vc = (await readback(Vc[0], kvCapacity * KV * Dh)).slice(off, off + KV * Dh);
|
|
1826
|
+
}
|
|
1806
1827
|
ck.fn = await readback(r.fn, Hd);
|
|
1807
1828
|
ck.logits = await readback(lg, W.lm_head.N);
|
|
1808
1829
|
FORCE_SLOW = false;
|
|
@@ -1879,6 +1900,7 @@ async function createEngine(options) {
|
|
|
1879
1900
|
const capabilities = {
|
|
1880
1901
|
useSubgroups: useSG,
|
|
1881
1902
|
subgroupSize: sgMax,
|
|
1903
|
+
kvCache: kv16 ? "f16" : "f32",
|
|
1882
1904
|
adapter: {
|
|
1883
1905
|
vendor: info.vendor,
|
|
1884
1906
|
architecture: info.architecture,
|