bitgpu 0.10.0 → 0.11.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 CHANGED
@@ -7,7 +7,8 @@ Reference targets are Bonsai **1.7B, 4B and 8B** (Qwen3 architecture, sign-packe
7
7
  weights + 2/4-bit embeddings, tied or untied lm_head) - every size is gated bit-exact against the
8
8
  reference forward on real hardware. GPU-resident decode (greedy or sampled), streaming, EOS stop,
9
9
  `AbortSignal`, cross-turn KV-cache reuse, optional f16/q8 KV-cache compression for long
10
- contexts in less VRAM, and conversation snapshots (save/restore across page reloads). Runs the
10
+ contexts in less VRAM, conversation snapshots (save/restore across page reloads), and an
11
+ optional rolling window with attention sinks for unbounded chats in fixed memory. Runs the
11
12
  fast subgroup path on Apple / NVIDIA /
12
13
  recent AMD and falls back to a workgroup-reduction path everywhere else WebGPU is available.
13
14
  Device limits are negotiated from the manifest, so the 8B's ~148 MiB lm_head binding is requested
@@ -33,7 +34,7 @@ weights stream straight from the Hugging Face Hub. This runs as-is:
33
34
  import { createEngine } from 'bitgpu'
34
35
  import { createChat } from 'bitgpu/chat'
35
36
 
36
- const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.10.0/models/bonsai-1.7b'
37
+ const REPO = 'https://cdn.jsdelivr.net/gh/stfurkan/bitgpu@v0.11.0/models/bonsai-1.7b'
37
38
  const HF = 'https://huggingface.co/onnx-community/Bonsai-1.7B-ONNX/resolve/main'
38
39
  const engine = await createEngine({
39
40
  manifestUrl: `${REPO}/manifest.json`,
@@ -49,7 +50,8 @@ await chat.send([{ role: 'user', content: 'Hi!' }], { onText: (t) => process.std
49
50
 
50
51
  The [demo](https://stfurkan.github.io/bitgpu/examples/chat.html) ([source](examples/chat.html))
51
52
  is this quickstart as a single HTML file: model picker, streaming chat, JSON mode with a schema
52
- editor, and cached downloads.
53
+ editor, tool calling, cached downloads, and sessions that survive reloads (the KV cache is
54
+ snapshot into IndexedDB and restored - the conversation continues with no re-prefill).
53
55
 
54
56
  ## Usage
55
57
 
@@ -115,6 +117,49 @@ Reach for `'q8'` to run a 4x longer window in the same VRAM (or the same window
115
117
  GPUs); keep the default `'f32'` when bit-exact reproducibility is the point.
116
118
  `engine.capabilities.kvCache` reports what is actually active.
117
119
 
120
+ ### Unbounded conversations (`overflow: 'sinks'`)
121
+
122
+ By default a conversation that outgrows `maxSeqLen` throws. `overflow: 'sinks'` switches to a
123
+ StreamingLLM-style rolling window instead: the first `sinkTokens` positions (default 4, the
124
+ "attention sinks" that anchor the model's attention) plus the most recent window are kept, the
125
+ middle is evicted in batches, and generation or multi-turn chat continues indefinitely in fixed
126
+ memory - `maxTokens` is no longer clamped to the window:
127
+
128
+ ```ts
129
+ const engine = await createEngine({ modelUrl, kvCache: 'q8', overflow: 'sinks', maxSeqLen: 4096 })
130
+ ```
131
+
132
+ Implementation detail that matters: keys are cached **unroped** and rotated at read time by
133
+ their cache-relative position (the StreamingLLM reference scheme), so eviction is a plain
134
+ byte-exact compaction - nothing is ever re-rotated or, under q8, requantized. This is the
135
+ combination llama.cpp cannot offer (its context shift rewrites roped K in place and is
136
+ disabled for quantized K caches); here `q8 + sinks` is the flagship pairing: unbounded chat in
137
+ a quarter of the memory. The guarantees follow the mode philosophy: within-mode decoding is
138
+ exact and deterministic (same seed -> same tokens, across evictions; gated on real hardware),
139
+ and **before the first eviction f32+sinks is bit-identical to default f32** (gated against the
140
+ known-good ids). After an eviction the model genuinely forgets the evicted middle - that is
141
+ the trade, by design: prefer it over hard failure for open-ended chat; prefer `'error'` plus
142
+ prompt-side trimming when every token of context must count. Prompts longer than the window
143
+ still throw (`bitgpu/chat`'s `onOverflow` handles that side). Snapshots keep working - sink
144
+ mode saves version-2 snapshots (restore requires sink mode with the same `sinkTokens`).
145
+
146
+ ### Speculative decoding: why only `promptLookup`
147
+
148
+ The engine speculates out of the box where it pays: `promptLookup` drafts from n-gram matches
149
+ in the prompt and verifies them in one batched pass, with auto-probation that measures the
150
+ break-even and bails when speculation does not help (output is bit-identical either way).
151
+
152
+ There is deliberately no draft-model / two-model mode, and the reason is measured, not
153
+ guessed: speculative decoding pays only when verifying k tokens in one batched pass costs
154
+ about one token's time - true for f16 models, whose decode is weight-bandwidth-bound, but not
155
+ for 1-bit models. The weight stream here is so small that batch-1 decode already saturates GPU
156
+ compute, so a k-row verify costs ~k single steps (measured: S=9 verify ~= 9.8x one step, and
157
+ even a perfect zero-cost drafter decoded slower than plain on the subgroup path). A full
158
+ in-engine two-model orchestration was built, gate-proven bit-exact, measured slower, and
159
+ removed - fast single-stream 1-bit decode and profitable speculation are the same budget,
160
+ already spent on the former. Where batching still wins (dispatch-latency-bound setups like the
161
+ no-subgroup fallback path) is exactly where `promptLookup`'s probation keeps it on.
162
+
118
163
  ## Chat (`bitgpu/chat`)
119
164
 
120
165
  The engine is deliberately ids-in/ids-out; `bitgpu/chat` is the batteries-included text layer on
@@ -368,9 +413,10 @@ npm run check:publish # publint + are-the-types-wrong
368
413
  `examples/verify.html` re-runs the full bit-exactness + throughput suite (forward cosines vs the
369
414
  committed reference fixtures in `test-fixtures/forward/`, known-good greedy ids, sampler kernel
370
415
  parity, determinism, KV reuse/growth, prompt-lookup identity, KV snapshot save/restore round
371
- trips - including into a fresh engine - and the f16/q8 KV-mode sections: within-mode exactness
372
- plus greedy agreement vs f32 out to a 1500-token prompt) against the **built package** and
373
- prints `PACKAGE OK` or `REGRESSION`.
416
+ trips - including into a fresh engine - the f16/q8 KV-mode sections: within-mode exactness
417
+ plus greedy agreement vs f32 out to a 1500-token prompt, the rolling-window section:
418
+ pre-eviction bit-exactness, 600 tokens through a 192-token window, determinism across
419
+ evictions) against the **built package** and prints `PACKAGE OK` or `REGRESSION`.
374
420
 
375
421
  It needs model weights, which are not committed. Point `examples/model` at a directory holding the
376
422
  model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~290 MB):
@@ -379,6 +425,7 @@ model's `manifest.json` + data/aux files (the reference target is Bonsai-1.7B, ~
379
425
  ln -s /path/to/bonsai-model examples/model # or copy the files in
380
426
  npm run build
381
427
  npm run verify:headless # serves the repo itself + drives system Chrome headlessly
428
+ FAST=1 npm run verify:headless # dev iteration: baseline model, core sections only (~3 min; NOT a release gate)
382
429
  ```
383
430
 
384
431
  Or serve the repo root (`python3 -m http.server 8000`) and open
package/dist/chat.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as KvSnapshot, n as Engine, o as GenerateOptions, u as TokenLogprobs } from "./types-CcgsXirU.js";
1
+ import { c as KvSnapshot, n as Engine, o as GenerateOptions, u as TokenLogprobs } from "./types-DJ61q1gX.js";
2
2
 
3
3
  //#region src/chat/tokenizer.d.ts
4
4
  interface ChatMessage {
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as ForwardResult, c as KvSnapshot, i as EngineOptions, l as LoadProgress, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as TokenLogprobs } from "./types-CcgsXirU.js";
1
+ import { a as ForwardResult, c as KvSnapshot, i as EngineOptions, l as LoadProgress, n as Engine, o as GenerateOptions, r as EngineCapabilities, s as GenerateResult, t as DeviceLostInfo, u as TokenLogprobs } from "./types-DJ61q1gX.js";
2
2
 
3
3
  //#region src/engine.d.ts
4
4
  /** Load a 1-bit model and return an {@link Engine}. Pass a model URL string for defaults. */
package/dist/index.js CHANGED
@@ -5,10 +5,16 @@ const SHADERS = {
5
5
  "argmax_masked": "// Masked argmax: like argmax.wgsl but skips any id already chosen in a prior round, and writes BOTH\n// the winning id and its logit value. Calling it K times (roundCount = 0..K-1, all in one compute\n// pass so each round sees the prior rounds' writes) yields the exact top-K (id, logit) pairs in\n// descending order = ONNX TopK over the (penalty-filtered) logits, which is what the transformers.js\n// sampler consumes. Then only K pairs are read back (not the full vocab), and the CPU does\n// temperature + softmax + multinomial. Single workgroup, no subgroup ops -> all devices. Tie-break =\n// lowest index (strict >), matching argmax.wgsl / ORT TopK in practice.\noverride WG: u32 = 256u;\nstruct Params { N: u32, roundCount: u32, _0: u32, _1: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> logits: array<f32>;\n@group(0) @binding(2) var<storage, read_write> candIds: array<u32>; // [K]; reads 0..roundCount-1, writes [roundCount]\n@group(0) @binding(3) var<storage, read_write> candVals: array<f32>; // [K]; writes [roundCount]\n\nvar<workgroup> sval: array<f32, 256>;\nvar<workgroup> sidx: array<u32, 256>;\n\n@compute @workgroup_size(WG)\nfn main(@builtin(local_invocation_id) lid: vec3<u32>) {\n let tid = lid.x;\n var bv = -3.4e38;\n var bi = 0u;\n for (var i = tid; i < p.N; i = i + WG) {\n let v = logits[i];\n if (v > bv) {\n var skip = false;\n for (var r = 0u; r < p.roundCount; r = r + 1u) { if (candIds[r] == i) { skip = true; break; } }\n if (!skip) { bv = v; bi = i; } // strict > keeps the lowest index within this thread's stride\n }\n }\n sval[tid] = bv; sidx[tid] = bi;\n workgroupBarrier();\n for (var s = WG / 2u; s > 0u; s = s >> 1u) {\n if (tid < s) {\n let ov = sval[tid + s]; let oi = sidx[tid + s];\n if (ov > sval[tid] || (ov == sval[tid] && oi < sidx[tid])) { sval[tid] = ov; sidx[tid] = oi; }\n }\n workgroupBarrier();\n }\n if (tid == 0u) { candIds[p.roundCount] = sidx[0]; candVals[p.roundCount] = sval[0]; }\n}\n",
6
6
  "attention_sg": "// Causal GQA attention, subgroup-parallel: one subgroup (= one workgroup) per (query, head).\n// Lanes split head_dim; flash-style online softmax over the cached positions; the per-position\n// score (q.k) is reduced with subgroupAdd. Fixes the decode bottleneck where attention ran only\n// H threads. SG = device subgroup size (16/32/64, so head_dim/SG <= 8). Reads K/V from the cache.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG; // <= 8 for SG>=16, D=128\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * Kc[kb + d]; }\n let score = subgroupAdd(part) * inv; // full q.k dot, broadcast to all lanes\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
7
7
  "attention_sg_kv16": "// attention_sg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_sg.wgsl: the ONLY difference is Kc/Vc are array<f16> and each cached value is\n// widened to f32 at the read. All arithmetic (dot, softmax, accumulation) stays f32, so the\n// precision loss is exactly one rounding of K/V at cache-write time, nothing compounding.\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG;\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; part = part + q[qb + d] * f32(Kc[kb + d]); }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
8
+ "attention_sg_kv16_roll": "// attention_sg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv16.wgsl: the ONLY\n// difference is the K rotation in the score loop; each cached f16 value is widened to f32 at\n// the read and rotated with the same `k*cos + rot*sin` operand order as rmsnorm_rope_sg.\n// The engine only selects this kernel when SG <= D/2 (partner dim stays in-lane).\nenable subgroups;\nenable f16;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG;\n let half = p.D / 2u;\n let hs = half / SG; // strides from a dim to its rotate partner\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var kd: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = f32(Kc[kb + lane + t * SG]); }\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) {\n let d = lane + t * SG;\n var rot: f32;\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
8
9
  "attention_sg_kv8": "// attention_sg with a q8 KV cache (kvCache: 'q8'). Keep in lockstep with attention_sg.wgsl: the\n// ONLY difference is Kc/Vc are packed snorm8 words dequantized at the read with their per-block\n// f32 scales (32-element blocks, q8_0-style; see copy_kv8.wgsl). All arithmetic (dot, softmax,\n// accumulation) stays f32. Each lane owns whole packed words, so q is read in matching groups\n// of 4.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let W4 = p.D / 4u;\n let B32 = p.D / 32u;\n\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = vec4<f32>(0.0); }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * B32;\n var part = 0.0;\n for (var w = lane; w < W4; w = w + SG) {\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\n part = part + dot(qv, kw);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\n acc[wi] = acc[wi] * corr + wgt * vw;\n wi = wi + 1u;\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let o = acc[wi] / l;\n out[ob + w * 4u] = o.x;\n out[ob + w * 4u + 1u] = o.y;\n out[ob + w * 4u + 2u] = o.z;\n out[ob + w * 4u + 3u] = o.w;\n wi = wi + 1u;\n }\n}\n",
10
+ "attention_sg_kv8_roll": "// attention_sg_kv8 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_sg_kv8.wgsl: the ONLY\n// difference is the K rotation in the score loop. The cache holds UNROPED quantized keys -\n// the whole point: the packed bytes are immutable, so eviction never requantizes (llama.cpp's\n// K-shift cannot do this on a quantized cache at all). A word's rotate partner is the word\n// D/8 away (all 4 dims of a word share one half), dequantized from global with its own scale.\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let W4 = p.D / 4u;\n let B32 = p.D / 32u;\n let half = p.D / 2u;\n let hw = half / 4u; // words from a word to its rotate partner\n\n var acc: array<vec4<f32>, 8>; // words per lane: W4/SG <= 8 for SG >= 4\n for (var t = 0u; t < 8u; t = t + 1u) { acc[t] = vec4<f32>(0.0); }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * B32;\n var part = 0.0;\n for (var w = lane; w < W4; w = w + SG) {\n let kw = unpack4x8snorm(Kq[rowQ + w]) * Ks[rowS + (w >> 3u)];\n let wp = select(w - hw, w + hw, w < hw);\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\n let rot = select(kp, -kp, w < hw);\n let cb = j * half + select(w - hw, w, w < hw) * 4u;\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\n let qv = vec4<f32>(q[qb + w * 4u], q[qb + w * 4u + 1u], q[qb + w * 4u + 2u], q[qb + w * 4u + 3u]);\n part = part + dot(qv, kw * cs + rot * sn);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let vw = unpack4x8snorm(Vq[rowQ + w]) * Vs[rowS + (w >> 3u)];\n acc[wi] = acc[wi] * corr + wgt * vw;\n wi = wi + 1u;\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n var wi = 0u;\n for (var w = lane; w < W4; w = w + SG) {\n let o = acc[wi] / l;\n out[ob + w * 4u] = o.x;\n out[ob + w * 4u + 1u] = o.y;\n out[ob + w * 4u + 2u] = o.z;\n out[ob + w * 4u + 3u] = o.w;\n wi = wi + 1u;\n }\n}\n",
11
+ "attention_sg_roll": "// attention_sg for the rolling-window / attention-sinks mode (overflow: 'sinks'): the cache\n// holds UNROPED keys, and each cached row j is rotated AT READ by its cache-relative position\n// (StreamingLLM-style; the cache bytes are immutable, so eviction compaction never re-rotates\n// or requantizes anything). Keep in lockstep with attention_sg.wgsl: the ONLY difference is\n// the K rotation in the score loop, written as `k*cos + rot*sin` with the same operand order\n// as rmsnorm_rope_sg so the f32 path stays bit-identical to the roped-at-write kernels until\n// the first eviction. cosT/sinT are the aux rope tables, [positions, D/2].\n// Lane math: d = lane + t*SG, partner d±D/2 is (D/2)/SG strides away IN THE SAME LANE (the\n// engine only selects this kernel when SG <= D/2).\nenable subgroups;\noverride SG: u32 = 32u;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\n\n@compute @workgroup_size(SG)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(subgroup_invocation_id) lane: u32) {\n let idx = wg.x;\n if (idx >= p.S * p.H) { return; }\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let dper = p.D / SG;\n let half = p.D / 2u;\n let hs = half / SG; // strides from a dim to its rotate partner\n\n var acc: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { acc[t] = 0.0; }\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var kd: array<f32, 8>;\n for (var t = 0u; t < dper; t = t + 1u) { kd[t] = Kc[kb + lane + t * SG]; }\n var part = 0.0;\n for (var t = 0u; t < dper; t = t + 1u) {\n let d = lane + t * SG;\n var rot: f32;\n if (d < half) { rot = -kd[t + hs]; } else { rot = kd[t - hs]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kd[t] * cosT[rb] + rot * sinT[rb]);\n }\n let score = subgroupAdd(part) * inv;\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < dper; t = t + 1u) { let d = lane + t * SG; out[ob + d] = acc[t] / l; }\n}\n",
9
12
  "attention_wg": "// Causal GQA attention, no-subgroup fallback: one workgroup per (query, head); threads split\n// head_dim; flash-style online softmax over the cached positions; the per-position q.k score\n// is tree-reduced via shared memory. Replaces attention_cache on this path: its single thread\n// per (query, head) walked the WHOLE context serially, so fallback decode degraded linearly\n// with conversation length and prefill attention was latency-bound. Mirrors attention_sg with\n// subgroupAdd swapped for the shared-memory reduction. Fixed workgroup of 64: the per-thread\n// accumulator covers head_dim <= 128 (enforced at manifest validation) in 2 strides.\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { part = part + q[qb + d] * Kc[kb + d]; }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv; // full q.k dot, visible to all threads\n workgroupBarrier(); // red[0] consumed before the next position overwrites it\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
10
13
  "attention_wg_kv16": "// attention_wg with an f16-STORAGE KV cache (kvCache: 'f16'). Keep in lockstep with\n// attention_wg.wgsl: the ONLY difference is Kc/Vc are array<f16>, widened to f32 at the read.\nenable f16;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { part = part + q[qb + d] * f32(Kc[kb + d]); }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
14
+ "attention_wg_kv16_roll": "// attention_wg_kv16 for the rolling-window / attention-sinks mode (see attention_sg_roll.wgsl\n// for the rope-at-read scheme). Keep in lockstep with attention_wg_kv16.wgsl: the ONLY\n// differences are the shared-memory K stage (kk, widened to f32) - the rotate partner d±D/2\n// may live in another thread's stride - and the rotation in the score loop, written as\n// `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\nenable f16;\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f16>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f16>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\nvar<workgroup> kk: array<f32, 128>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let half = p.D / 2u;\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { kk[d] = f32(Kc[kb + d]); }\n }\n workgroupBarrier();\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) {\n var rot: f32;\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\n }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * f32(Vc[kb + d]); }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
11
15
  "attention_wg_kv8": "// attention_wg with a q8 KV cache (kvCache: 'q8'): the no-subgroup fallback reader for the\n// packed-snorm8 cache (see copy_kv8.wgsl for the write side). Keep in lockstep with\n// attention_wg.wgsl: same online softmax, all arithmetic f32; each thread owns one packed word\n// (D <= 128 -> at most 32 words, so threads 32..63 only carry zeros through the reduction).\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D]\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let t = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let W4 = p.D / 4u;\n\n var qv = vec4<f32>(0.0);\n if (t < W4) {\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\n }\n var acc = vec4<f32>(0.0);\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\n var part = 0.0;\n if (t < W4) {\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\n part = dot(qv, kw);\n }\n red[t] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (t < s) { red[t] = red[t] + red[t + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n if (t < W4) {\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\n acc = acc * corr + wgt * vw;\n }\n m = mnew;\n }\n if (t < W4) {\n let ob = (qi * p.H + h) * p.D;\n let o = acc / l;\n out[ob + t * 4u] = o.x;\n out[ob + t * 4u + 1u] = o.y;\n out[ob + t * 4u + 2u] = o.z;\n out[ob + t * 4u + 3u] = o.w;\n }\n}\n",
16
+ "attention_wg_kv8_roll": "// attention_wg_kv8 for the rolling-window / attention-sinks mode: the no-subgroup fallback of\n// attention_sg_kv8_roll (see there and attention_sg_roll.wgsl for the rope-at-read scheme).\n// Keep in lockstep with attention_wg_kv8.wgsl: the ONLY difference is the K rotation in the\n// score loop; each thread's word rotates against its partner word D/8 away, dequantized from\n// global with its own scale.\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kq: array<u32>; // [Ltot, KV, D/4] packed snorm8, UNROPED\n@group(0) @binding(3) var<storage, read> Vq: array<u32>; // [Ltot, KV, D/4] packed snorm8\n@group(0) @binding(4) var<storage, read> Ks: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(5) var<storage, read> Vs: array<f32>; // [Ltot, KV, D/32] block scales\n@group(0) @binding(6) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(7) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(8) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let t = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let W4 = p.D / 4u;\n let half = p.D / 2u;\n let hw = half / 4u; // words from a word to its rotate partner\n\n var qv = vec4<f32>(0.0);\n if (t < W4) {\n qv = vec4<f32>(q[qb + t * 4u], q[qb + t * 4u + 1u], q[qb + t * 4u + 2u], q[qb + t * 4u + 3u]);\n }\n var acc = vec4<f32>(0.0);\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let rowQ = (j * p.KV + kvh) * W4;\n let rowS = (j * p.KV + kvh) * (p.D / 32u);\n var part = 0.0;\n if (t < W4) {\n let kw = unpack4x8snorm(Kq[rowQ + t]) * Ks[rowS + (t >> 3u)];\n let wp = select(t - hw, t + hw, t < hw);\n let kp = unpack4x8snorm(Kq[rowQ + wp]) * Ks[rowS + (wp >> 3u)];\n let rot = select(kp, -kp, t < hw);\n let cb = j * half + select(t - hw, t, t < hw) * 4u;\n let cs = vec4<f32>(cosT[cb], cosT[cb + 1u], cosT[cb + 2u], cosT[cb + 3u]);\n let sn = vec4<f32>(sinT[cb], sinT[cb + 1u], sinT[cb + 2u], sinT[cb + 3u]);\n part = dot(qv, kw * cs + rot * sn);\n }\n red[t] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (t < s) { red[t] = red[t] + red[t + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv;\n workgroupBarrier();\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let wgt = exp(score - mnew);\n l = l * corr + wgt;\n if (t < W4) {\n let vw = unpack4x8snorm(Vq[rowQ + t]) * Vs[rowS + (t >> 3u)];\n acc = acc * corr + wgt * vw;\n }\n m = mnew;\n }\n if (t < W4) {\n let ob = (qi * p.H + h) * p.D;\n let o = acc / l;\n out[ob + t * 4u] = o.x;\n out[ob + t * 4u + 1u] = o.y;\n out[ob + t * 4u + 2u] = o.z;\n out[ob + t * 4u + 3u] = o.w;\n }\n}\n",
17
+ "attention_wg_roll": "// attention_wg for the rolling-window / attention-sinks mode: no-subgroup fallback of\n// attention_sg_roll (see there for the rope-at-read scheme). Keep in lockstep with\n// attention_wg.wgsl: the ONLY differences are the shared-memory K stage (kk) - the rotate\n// partner d±D/2 may live in another thread's stride - and the rotation in the score loop,\n// written as `k*cos + rot*sin` with the same operand order as rmsnorm_rope_sg.\nstruct Params { S: u32, H: u32, KV: u32, D: u32, posBase: u32, Ltot: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> q: array<f32>; // [S, H, D] (roped, cache-relative)\n@group(0) @binding(2) var<storage, read> Kc: array<f32>; // [Ltot, KV, D] UNROPED\n@group(0) @binding(3) var<storage, read> Vc: array<f32>; // [Ltot, KV, D]\n@group(0) @binding(4) var<storage, read> cosT: array<f32>; // [positions, D/2]\n@group(0) @binding(5) var<storage, read> sinT: array<f32>; // [positions, D/2]\n@group(0) @binding(6) var<storage, read_write> out: array<f32>; // [S, H, D]\nvar<workgroup> red: array<f32, 64>;\nvar<workgroup> kk: array<f32, 128>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let idx = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (idx >= p.S * p.H) { return; }\n let tid = lid.x;\n let h = idx % p.H;\n let qi = idx / p.H;\n let pos = p.posBase + qi;\n let kvh = h / (p.H / p.KV);\n let qb = (qi * p.H + h) * p.D;\n let inv = 1.0 / sqrt(f32(p.D));\n let half = p.D / 2u;\n\n var acc: array<f32, 2>;\n acc[0] = 0.0;\n acc[1] = 0.0;\n var m = -1e30;\n var l = 0.0;\n for (var j = 0u; j <= pos; j = j + 1u) {\n let kb = (j * p.KV + kvh) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { kk[d] = Kc[kb + d]; }\n }\n workgroupBarrier();\n var part = 0.0;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) {\n var rot: f32;\n if (d < half) { rot = -kk[d + half]; } else { rot = kk[d - half]; }\n let rb = j * half + (d % half);\n part = part + q[qb + d] * (kk[d] * cosT[rb] + rot * sinT[rb]);\n }\n }\n red[tid] = part;\n workgroupBarrier();\n for (var s = 32u; s > 0u; s = s >> 1u) {\n if (tid < s) { red[tid] = red[tid] + red[tid + s]; }\n workgroupBarrier();\n }\n let score = red[0] * inv; // full q.k dot, visible to all threads\n workgroupBarrier(); // red[0] + kk consumed before the next position overwrites them\n let mnew = max(m, score);\n let corr = exp(m - mnew);\n let w = exp(score - mnew);\n l = l * corr + w;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { acc[t] = acc[t] * corr + w * Vc[kb + d]; }\n }\n m = mnew;\n }\n let ob = (qi * p.H + h) * p.D;\n for (var t = 0u; t < 2u; t = t + 1u) {\n let d = tid + t * 64u;\n if (d < p.D) { out[ob + d] = acc[t] / l; }\n }\n}\n",
12
18
  "copy": "// Copy src[0..n) into dst[dstOff..dstOff+n). Used to append K/V into the persistent cache.\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f32>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = src[i];\n}\n",
13
19
  "copy_kv16": "// copy with an f16-STORAGE destination (kvCache: 'f16'): appends f32 K/V rows into the f16\n// cache (one f32 -> f16 rounding per value). Keep in lockstep with copy.wgsl.\nenable f16;\nstruct Params { n: u32, dstOff: u32, _p1: u32, _p2: u32 };\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>;\n@group(0) @binding(2) var<storage, read_write> dst: array<f16>;\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wid: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>, @builtin(num_workgroups) nwg: vec3<u32>) {\n let i = (wid.y * nwg.x + wid.x) * 64u + lid.x;\n if (i >= p.n) { return; }\n dst[p.dstOff + i] = f16(src[i]);\n}\n",
14
20
  "copy_kv8": "// q8 cache append (kvCache: 'q8'): quantize f32 K/V rows into the packed-snorm8 cache, one f32\n// scale per 32-element block (llama.cpp q8_0-style). One 64-thread workgroup per row of D\n// elements: thread t owns packed word t (4 consecutive values), the workgroup reduces per-block\n// absolute maxima through shared memory, then packs with pack4x8snorm. Replaces copy/copy_kv16\n// at every cache-append site under q8. All attention arithmetic stays f32; the precision loss is\n// exactly one snorm8 rounding of K/V at write time, nothing compounding.\nstruct Params { rows: u32, D: u32, dstRow0: u32, _p: u32 };\n\n@group(0) @binding(0) var<uniform> p: Params;\n@group(0) @binding(1) var<storage, read> src: array<f32>; // [rows, D]\n@group(0) @binding(2) var<storage, read_write> dstQ: array<u32>; // packed 4 x snorm8 per word\n@group(0) @binding(3) var<storage, read_write> dstS: array<f32>; // [.., D/32] block scales\n\nvar<workgroup> wabs: array<f32, 32>; // per-word abs max (D <= 128 -> at most 32 words)\nvar<workgroup> wblk: array<f32, 4>; // per-block scale (D/32 <= 4 blocks)\n\n@compute @workgroup_size(64)\nfn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {\n let row = wg.x; // uniform across the workgroup -> early return is barrier-safe\n if (row >= p.rows) { return; }\n let t = lid.x;\n let W4 = p.D / 4u;\n let base = row * p.D;\n var v = vec4<f32>(0.0);\n if (t < W4) {\n v = vec4<f32>(src[base + t * 4u], src[base + t * 4u + 1u], src[base + t * 4u + 2u], src[base + t * 4u + 3u]);\n wabs[t] = max(max(abs(v.x), abs(v.y)), max(abs(v.z), abs(v.w)));\n }\n workgroupBarrier();\n if (t < p.D / 32u) {\n var m = 0.0;\n for (var i = 0u; i < 8u; i = i + 1u) { m = max(m, wabs[t * 8u + i]); }\n let s = max(m, 1e-30); // an all-zero block packs zeros, never NaN\n wblk[t] = s;\n dstS[(p.dstRow0 + row) * (p.D / 32u) + t] = s;\n }\n workgroupBarrier();\n if (t < W4) {\n dstQ[(p.dstRow0 + row) * W4 + t] = pack4x8snorm(v / wblk[t >> 3u]);\n }\n}\n",
@@ -317,6 +323,9 @@ async function createEngineInner(options, holder) {
317
323
  const useSG = hasSG && sgMin === sgMax && (sgMax === 16 || sgMax === 32 || sgMax === 64) && A.head_dim % sgMax === 0 && !forceNoSG;
318
324
  const kv16 = opts.kvCache === "f16" && adapter.features.has("shader-f16");
319
325
  const kv8 = opts.kvCache === "q8";
326
+ const roll = opts.overflow === "sinks";
327
+ const SINKS = roll ? Math.max(1, Math.floor(opts.sinkTokens ?? 4)) : 0;
328
+ if (roll && maxSeqLen < SINKS + 64) throw new Error(`bitgpu: overflow 'sinks' needs maxSeqLen >= sinkTokens + 64 (got ${maxSeqLen} with ${SINKS} sinks)`);
320
329
  const KVB = kv16 ? 2 : kv8 ? 1 : 4;
321
330
  const features = [];
322
331
  if (useSG) features.push("subgroups");
@@ -453,7 +462,14 @@ async function createEngineInner(options, holder) {
453
462
  if (useSG) for (const n of ["attention_sg_kv8", "rmsnorm_rope_sg_kv8"]) specs.push([n, { SG: sgMax }]);
454
463
  else specs.push(["attention_wg_kv8"]);
455
464
  }
456
- const ATT = kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : kv8 ? useSG ? "attention_sg_kv8" : "attention_wg_kv8" : useSG ? "attention_sg" : "attention_wg";
465
+ const rollSG = useSG && sgMax <= A.head_dim / 2;
466
+ if (roll) {
467
+ const rollAtt = kv16 ? "attention_sg_kv16_roll" : kv8 ? "attention_sg_kv8_roll" : "attention_sg_roll";
468
+ const rollAttWg = kv16 ? "attention_wg_kv16_roll" : kv8 ? "attention_wg_kv8_roll" : "attention_wg_roll";
469
+ if (rollSG) specs.push([rollAtt, { SG: sgMax }]);
470
+ else specs.push([rollAttWg]);
471
+ }
472
+ const ATT = roll ? kv16 ? rollSG ? "attention_sg_kv16_roll" : "attention_wg_kv16_roll" : kv8 ? rollSG ? "attention_sg_kv8_roll" : "attention_wg_kv8_roll" : rollSG ? "attention_sg_roll" : "attention_wg_roll" : kv16 ? useSG ? "attention_sg_kv16" : "attention_wg_kv16" : kv8 ? useSG ? "attention_sg_kv8" : "attention_wg_kv8" : useSG ? "attention_sg" : "attention_wg";
457
473
  const ROPE_K = kv16 ? "rmsnorm_rope_sg_kv16" : "rmsnorm_rope_sg";
458
474
  const COPY_KV = kv16 ? "copy_kv16" : "copy";
459
475
  await Promise.all(specs.map(([n, c]) => mkPipe(n, c)));
@@ -521,8 +537,10 @@ async function createEngineInner(options, holder) {
521
537
  usage: S_
522
538
  });
523
539
  let fullHistory = [];
540
+ let cacheLen = 0;
524
541
  const resetCache = () => {
525
542
  fullHistory = [];
543
+ cacheLen = 0;
526
544
  };
527
545
  if (manifest.luts.tgt2.src !== "aux") throw new Error("bitgpu: luts.tgt2 must live in the aux file (the streaming loader needs it before the weights arrive)");
528
546
  const tgt2 = readU8(manifest.luts.tgt2);
@@ -822,6 +840,30 @@ async function createEngineInner(options, holder) {
822
840
  }));
823
841
  }
824
842
  }
843
+ let rollCosT = null, rollSinT = null, rollOnes = null, rollZeros = null;
844
+ if (roll) {
845
+ const R2 = Dh / 2;
846
+ rollCosT = device.createBuffer({
847
+ size: maxSeqLen * R2 * 4,
848
+ usage: S_ | CD
849
+ });
850
+ rollSinT = device.createBuffer({
851
+ size: maxSeqLen * R2 * 4,
852
+ usage: S_ | CD
853
+ });
854
+ device.queue.writeBuffer(rollCosT, 0, cosCache.buffer, cosCache.byteOffset, maxSeqLen * R2 * 4);
855
+ device.queue.writeBuffer(rollSinT, 0, sinCache.buffer, sinCache.byteOffset, maxSeqLen * R2 * 4);
856
+ rollOnes = device.createBuffer({
857
+ size: Dh * 4,
858
+ usage: S_ | CD
859
+ });
860
+ rollZeros = device.createBuffer({
861
+ size: Dh * 4,
862
+ usage: S_ | CD
863
+ });
864
+ device.queue.writeBuffer(rollOnes, 0, new Float32Array(Dh).fill(1));
865
+ device.queue.writeBuffer(rollZeros, 0, new Float32Array(Dh));
866
+ }
825
867
  const loadOom = await device.popErrorScope();
826
868
  const loadVal = await device.popErrorScope();
827
869
  if (loadOom) throw new GpuOutOfMemoryError(`GPU allocation failed while loading weights (~${Math.round(weightBytes / 1048576)} MB VRAM needed): ${loadOom.message}`);
@@ -888,6 +930,35 @@ async function createEngineInner(options, holder) {
888
930
  kvCapacity = newCap;
889
931
  poolInvalidate();
890
932
  }
933
+ let evictScratch = null;
934
+ function evict(fill, need) {
935
+ const recent = fill - SINKS;
936
+ const batch = Math.min(recent, Math.max(need, Math.ceil((maxSeqLen - SINKS) / 4)));
937
+ const keep = recent - batch;
938
+ if (keep <= 0) return SINKS;
939
+ const rowK = KV * Dh * KVB;
940
+ const rowS = kv8 ? KV * (Dh / 32) * 4 : 0;
941
+ if (!evictScratch || evictScratch.size < keep * rowK) {
942
+ evictScratch?.destroy();
943
+ evictScratch = device.createBuffer({
944
+ size: keep * rowK,
945
+ usage: CS | CD
946
+ });
947
+ }
948
+ const enc = device.createCommandEncoder();
949
+ const groups = [];
950
+ for (let li = 0; li < A.layers; li++) {
951
+ groups.push([Kc[li], rowK], [Vc[li], rowK]);
952
+ if (kv8) groups.push([Ksc[li], rowS], [Vsc[li], rowS]);
953
+ }
954
+ for (const [buf, row] of groups) {
955
+ enc.copyBufferToBuffer(buf, (SINKS + batch) * row, evictScratch, 0, keep * row);
956
+ enc.copyBufferToBuffer(evictScratch, 0, buf, SINKS * row, keep * row);
957
+ }
958
+ device.queue.submit([enc.finish()]);
959
+ return SINKS + keep;
960
+ }
961
+ const evictFor = (fill, n) => roll && fill + n > maxSeqLen ? evict(fill, fill + n - maxSeqLen) : fill;
891
962
  async function readback(buf, n) {
892
963
  const rb = device.createBuffer({
893
964
  size: n * 4,
@@ -1175,17 +1246,21 @@ async function createEngineInner(options, holder) {
1175
1246
  ["u", 0]
1176
1247
  ], [src], data, rows * Dh);
1177
1248
  }
1178
- const attIns = (qr, li) => kv8 ? [
1179
- qr,
1180
- Kc[li],
1181
- Vc[li],
1182
- Ksc[li],
1183
- Vsc[li]
1184
- ] : [
1185
- qr,
1186
- Kc[li],
1187
- Vc[li]
1188
- ];
1249
+ const attIns = (qr, li) => {
1250
+ const ins = kv8 ? [
1251
+ qr,
1252
+ Kc[li],
1253
+ Vc[li],
1254
+ Ksc[li],
1255
+ Vsc[li]
1256
+ ] : [
1257
+ qr,
1258
+ Kc[li],
1259
+ Vc[li]
1260
+ ];
1261
+ if (roll) ins.push(rollCosT, rollSinT);
1262
+ return ins;
1263
+ };
1189
1264
  function layer(pass, li, h, S, posBase, cos, sin) {
1190
1265
  const Ltot = posBase + S;
1191
1266
  const n1 = actBuf(S * Hd);
@@ -1225,6 +1300,7 @@ async function createEngineInner(options, holder) {
1225
1300
  cos,
1226
1301
  sin
1227
1302
  ], qr, H);
1303
+ const kcos = roll ? rollOnes : cos, ksin = roll ? rollZeros : sin;
1228
1304
  if (kv8) {
1229
1305
  setup(pass, "rmsnorm_rope_sg_kv8", [
1230
1306
  ["u", KV],
@@ -1236,8 +1312,8 @@ async function createEngineInner(options, holder) {
1236
1312
  ], [
1237
1313
  k,
1238
1314
  W[`layers.${li}.attn.k_norm`].buf,
1239
- cos,
1240
- sin
1315
+ kcos,
1316
+ ksin
1241
1317
  ], [Kc[li], Ksc[li]]);
1242
1318
  pass.dispatchWorkgroups(isFull("rmsnorm_rope_sg_kv8") ? KV : 1);
1243
1319
  } else runN(pass, ROPE_K, [
@@ -1250,8 +1326,8 @@ async function createEngineInner(options, holder) {
1250
1326
  ], [
1251
1327
  k,
1252
1328
  W[`layers.${li}.attn.k_norm`].buf,
1253
- cos,
1254
- sin
1329
+ kcos,
1330
+ ksin
1255
1331
  ], Kc[li], KV);
1256
1332
  cap(li, "qr", qr);
1257
1333
  const att = actBuf(H * Dh);
@@ -1306,7 +1382,7 @@ async function createEngineInner(options, holder) {
1306
1382
  cos,
1307
1383
  sin
1308
1384
  ], qr, S * H * Dh);
1309
- run(pass, "rope", [
1385
+ if (!roll) run(pass, "rope", [
1310
1386
  ["u", S],
1311
1387
  ["u", KV],
1312
1388
  ["u", Dh],
@@ -1316,7 +1392,7 @@ async function createEngineInner(options, holder) {
1316
1392
  cos,
1317
1393
  sin
1318
1394
  ], kr, S * KV * Dh);
1319
- appendKV(pass, kr, 0, li, S * KV, posBase * KV);
1395
+ appendKV(pass, roll ? kn : kr, 0, li, S * KV, posBase * KV);
1320
1396
  appendKV(pass, v, 1, li, S * KV, posBase * KV);
1321
1397
  cap(li, "qr", qr);
1322
1398
  const att = actBuf(S * H * Dh);
@@ -1429,6 +1505,7 @@ async function createEngineInner(options, holder) {
1429
1505
  if (S === 0) throw new Error("forward: no tokens to process");
1430
1506
  if (S > maxSeqLen) throw new Error(`forward: sequence length ${S} exceeds maxSeqLen ${maxSeqLen}`);
1431
1507
  fullHistory = [];
1508
+ cacheLen = 0;
1432
1509
  await ensureKvCapacity(S);
1433
1510
  const vocab = W.lm_head.N;
1434
1511
  const embed = new Float32Array(S * Hd), layer0 = new Float32Array(S * Hd), finalnorm = new Float32Array(S * Hd), logits = new Float32Array(S * vocab);
@@ -1474,6 +1551,7 @@ async function createEngineInner(options, holder) {
1474
1551
  for (let off = 0; off < ids.length; off += PREFILL_SEG) {
1475
1552
  if (off > 0 && signal?.aborted) {
1476
1553
  fullHistory = [];
1554
+ cacheLen = 0;
1477
1555
  return null;
1478
1556
  }
1479
1557
  const seg = ids.slice(off, off + PREFILL_SEG);
@@ -1551,14 +1629,16 @@ async function createEngineInner(options, holder) {
1551
1629
  ctl?.onToken?.(firstTok);
1552
1630
  }
1553
1631
  poolInvalidate();
1632
+ let slot = posBase + ids.length;
1554
1633
  while (total < nTokens && !stopped) {
1555
1634
  if (ctl?.signal?.aborted) break;
1556
1635
  const batch = Math.min(syncN, nTokens - total);
1636
+ slot = evictFor(slot, batch);
1557
1637
  poolUse("decode");
1558
1638
  let t = performance.now();
1559
1639
  const enc = device.createCommandEncoder();
1560
1640
  for (let j = 0; j < batch; j++) {
1561
- const idxOut = total + j, pos = posBase + ids.length + idxOut - 1;
1641
+ const idxOut = total + j, pos = slot + j;
1562
1642
  let pass = enc.beginComputePass();
1563
1643
  runN(pass, "embed_gather", [
1564
1644
  ["u", Hd],
@@ -1594,17 +1674,21 @@ async function createEngineInner(options, holder) {
1594
1674
  t = performance.now();
1595
1675
  const toks = await readbackU32(tokBuf, total + batch);
1596
1676
  rbMs += performance.now() - t;
1677
+ let fed = batch;
1597
1678
  for (let j = 0; j < batch; j++) {
1598
1679
  const tk = toks[total + j];
1599
1680
  if (stopSet?.has(tk)) {
1600
1681
  stopped = true;
1682
+ fed = j;
1601
1683
  break;
1602
1684
  }
1603
1685
  gen.push(tk);
1604
1686
  ctl?.onToken?.(tk);
1605
1687
  }
1606
1688
  total += batch;
1689
+ slot += fed;
1607
1690
  }
1691
+ cacheLen = slot;
1608
1692
  const decodeMs = performance.now() - t1, nd = Math.max(1, gen.length - 1);
1609
1693
  return {
1610
1694
  prefillMs,
@@ -1832,10 +1916,12 @@ async function createEngineInner(options, holder) {
1832
1916
  const t1 = performance.now();
1833
1917
  let total = 1;
1834
1918
  poolInvalidate();
1919
+ let slot = posBase + ids.length;
1835
1920
  while (total < nTokens && !stopped) {
1836
1921
  if (signal?.aborted) break;
1837
1922
  poolUse("decode");
1838
- const idxOut = total, pos = posBase + ids.length + idxOut - 1;
1923
+ slot = evictFor(slot, 1);
1924
+ const idxOut = total, pos = slot;
1839
1925
  let t = performance.now();
1840
1926
  const { affLen, banLen } = writeAffBan(history);
1841
1927
  const enc = device.createCommandEncoder();
@@ -1879,7 +1965,9 @@ async function createEngineInner(options, holder) {
1879
1965
  recordLp(ci, cv, lse);
1880
1966
  onToken?.(tk);
1881
1967
  device.queue.writeBuffer(tokBuf, idxOut * 4, new Uint32Array([tk]));
1968
+ slot += 1;
1882
1969
  }
1970
+ cacheLen = slot;
1883
1971
  const decodeMs = performance.now() - t1;
1884
1972
  const nd = Math.max(1, gen.length - 1);
1885
1973
  return {
@@ -2061,6 +2149,7 @@ async function createEngineInner(options, holder) {
2061
2149
  const t1 = performance.now();
2062
2150
  while (total < nTokens && !stopped) {
2063
2151
  if (signal?.aborted) break;
2152
+ pos = evictFor(pos, maxDraft + 1);
2064
2153
  const kMax = Math.min(maxDraft, nTokens - total - 1, maxSeqLen - 1 - pos);
2065
2154
  const drafts = kMax > 0 ? draftNgram(history, ngramSize, kMax) : [];
2066
2155
  const S = drafts.length + 1;
@@ -2164,6 +2253,7 @@ async function createEngineInner(options, holder) {
2164
2253
  pos += emitted.length;
2165
2254
  tLast = emitted[emitted.length - 1];
2166
2255
  }
2256
+ cacheLen = pos;
2167
2257
  const decodeMs = performance.now() - t1;
2168
2258
  const nd = Math.max(1, gen.length - 1);
2169
2259
  return {
@@ -2306,6 +2396,7 @@ async function createEngineInner(options, holder) {
2306
2396
  useSubgroups: useSG,
2307
2397
  subgroupSize: sgMax,
2308
2398
  kvCache: kv16 ? "f16" : kv8 ? "q8" : "f32",
2399
+ overflow: roll ? "sinks" : "error",
2309
2400
  maxSeqLen,
2310
2401
  adapter: {
2311
2402
  vendor: info.vendor,
@@ -2333,12 +2424,18 @@ async function createEngineInner(options, holder) {
2333
2424
  readbackMs: 0
2334
2425
  }
2335
2426
  };
2336
- const posBase = reuse ? fullHistory.length - 1 : 0;
2427
+ let posBase = reuse ? roll ? cacheLen : fullHistory.length - 1 : 0;
2337
2428
  const prefillTokens = reuse ? [fullHistory[fullHistory.length - 1], ...promptTokenIds] : promptTokenIds;
2338
2429
  if (prefillTokens.length === 0) throw new Error("generate: no tokens to process");
2430
+ if (roll && posBase + prefillTokens.length + 1 > maxSeqLen) {
2431
+ if (SINKS + prefillTokens.length + 1 > maxSeqLen) throw new Error(`generate: prompt length ${prefillTokens.length} exceeds the rolling window (maxSeqLen ${maxSeqLen} minus ${SINKS} sinks); trim the prompt`);
2432
+ await ensureKvCapacity(Math.min(maxSeqLen, posBase + prefillTokens.length));
2433
+ posBase = evict(posBase, posBase + prefillTokens.length + 1 - maxSeqLen);
2434
+ cacheLen = posBase;
2435
+ }
2339
2436
  const room = maxSeqLen - posBase - prefillTokens.length;
2340
2437
  if (room < 1) throw new Error(`generate: prompt length ${posBase + prefillTokens.length} exceeds maxSeqLen ${maxSeqLen}; trim history or raise maxSeqLen`);
2341
- const maxTokens = Math.min(genOpts.maxTokens ?? 256, room);
2438
+ const maxTokens = roll ? genOpts.maxTokens ?? 256 : Math.min(genOpts.maxTokens ?? 256, room);
2342
2439
  if (reuse) fullHistory.push(...promptTokenIds);
2343
2440
  else fullHistory = [...promptTokenIds];
2344
2441
  if (maxTokens < 1) {
@@ -2348,6 +2445,7 @@ async function createEngineInner(options, holder) {
2348
2445
  const t0 = performance.now();
2349
2446
  await runPrefill(prefillTokens, posBase, genOpts.signal);
2350
2447
  await device.queue.onSubmittedWorkDone();
2448
+ cacheLen = posBase + prefillTokens.length - 1;
2351
2449
  return {
2352
2450
  tokens: [],
2353
2451
  prefillMs: performance.now() - t0,
@@ -2443,6 +2541,7 @@ async function createEngineInner(options, holder) {
2443
2541
  await runPrefill(ids, 0);
2444
2542
  await device.queue.onSubmittedWorkDone();
2445
2543
  fullHistory = [...ids];
2544
+ cacheLen = ids.length - 1;
2446
2545
  return { prefillMs: performance.now() - t0 };
2447
2546
  } finally {
2448
2547
  flushTransients();
@@ -2454,7 +2553,7 @@ async function createEngineInner(options, holder) {
2454
2553
  const snapshotBytes = (len) => A.layers * 2 * len * (kvRowBytes + scRowBytes);
2455
2554
  async function saveCache() {
2456
2555
  if (fullHistory.length === 0) return null;
2457
- const len = fullHistory.length - 1;
2556
+ const len = roll ? cacheLen : fullHistory.length - 1;
2458
2557
  const data = new ArrayBuffer(snapshotBytes(len));
2459
2558
  if (len > 0) {
2460
2559
  const rb = device.createBuffer({
@@ -2482,7 +2581,7 @@ async function createEngineInner(options, holder) {
2482
2581
  rb.destroy();
2483
2582
  }
2484
2583
  return {
2485
- version: 1,
2584
+ version: roll ? 2 : 1,
2486
2585
  kvCache: capabilities.kvCache,
2487
2586
  model: {
2488
2587
  layers: A.layers,
@@ -2492,17 +2591,23 @@ async function createEngineInner(options, holder) {
2492
2591
  vocab: A.vocab
2493
2592
  },
2494
2593
  ids: [...fullHistory],
2594
+ ...roll ? { roll: {
2595
+ sinkTokens: SINKS,
2596
+ cacheLen
2597
+ } } : {},
2495
2598
  data
2496
2599
  };
2497
2600
  }
2498
2601
  async function restoreCache(snap) {
2499
- if (!snap || snap.version !== 1) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`);
2602
+ if (!snap || snap.version !== 1 && snap.version !== 2) throw new Error(`restoreCache: unsupported snapshot version ${snap?.version}`);
2603
+ if (snap.version === 2 !== roll) throw new Error(snap.version === 2 ? "restoreCache: snapshot was saved under overflow 'sinks' (unroped keys); this engine runs overflow 'error'" : "restoreCache: snapshot was saved under overflow 'error' (roped keys); this engine runs overflow 'sinks'");
2604
+ if (snap.version === 2 && snap.roll?.sinkTokens !== SINKS) throw new Error(`restoreCache: snapshot uses ${snap.roll?.sinkTokens} sink tokens but this engine uses ${SINKS}`);
2500
2605
  if (snap.kvCache !== capabilities.kvCache) throw new Error(`restoreCache: snapshot was saved under kvCache '${snap.kvCache}' but this engine runs '${capabilities.kvCache}' - snapshots do not convert across modes`);
2501
2606
  const m = snap.model;
2502
2607
  if (!m || m.layers !== A.layers || m.kvHeads !== KV || m.headDim !== Dh || m.hidden !== Hd || m.vocab !== A.vocab) throw new Error("restoreCache: snapshot is from a different model (architecture mismatch)");
2503
2608
  if (!Array.isArray(snap.ids) || snap.ids.length === 0) throw new Error("restoreCache: snapshot holds no tokens");
2504
- if (snap.ids.length > maxSeqLen) throw new Error(`restoreCache: snapshot length ${snap.ids.length} exceeds maxSeqLen ${maxSeqLen}`);
2505
- const len = snap.ids.length - 1;
2609
+ const len = snap.version === 2 ? snap.roll.cacheLen : snap.ids.length - 1;
2610
+ if (len + 1 > maxSeqLen) throw new Error(`restoreCache: snapshot needs ${len + 1} cache slots but maxSeqLen is ${maxSeqLen}`);
2506
2611
  if (snap.data.byteLength !== snapshotBytes(len)) throw new Error(`restoreCache: snapshot data is ${snap.data.byteLength} bytes, expected ${snapshotBytes(len)}`);
2507
2612
  await ensureKvCapacity(len);
2508
2613
  let off = 0;
@@ -2519,6 +2624,7 @@ async function createEngineInner(options, holder) {
2519
2624
  }
2520
2625
  }
2521
2626
  fullHistory = [...snap.ids];
2627
+ cacheLen = len;
2522
2628
  }
2523
2629
  let opChain = Promise.resolve();
2524
2630
  const serialize = (fn) => {