bots-garden/razorbillpublic Fork
⑂ b5ef2e8
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#47 spike, tasks 1-2: KV-cache prefix reuse measured (samples/02-kv-cache-reuse)

A standalone sample plays a ~4k-token conversation as a stateless client would,
cold (fresh cache per request) and warm (one cache rewound to the longest common
token prefix). On Qwen3-4B-4bit the time to first token falls from 25-30 s to
under 1 s per turn, with identical greedy answers when thinking is off. Report
and proposal are in the ticket's first comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-25T22:28:34+01:00 Browse files
b5ef2e8 parent: f2a20f5
modified .memory/handoffs/2026-11-25-v0-2-server-foundation.md +10 -0
@@ -98,3 +98,13 @@ Docs EN+FR rewritten (see summary). Remaining in the v0.2 milestone: #47 (KV-cac
9898 priority high). Release not started: version string is still 0.1.0, milestone not closed — use the
9999 release skill only when the user asks. Mac run of `scripts/compat.sh` (now 14 doc curl examples) not
100100 done since #44.
101+
102+## Update — #47 spike, tasks 1–2 done
103+Report = comment 1 on #47 (findings + proposal). Waiting on the user's decision: implement the
104+per-model prefix cache now (v0.2) or later; tasks 3–6 still open. `samples/02-kv-cache-reuse`
105+reproduces the numbers (`host.sh build|run samples/02-kv-cache-reuse kv-cache-reuse [--think
106+--max-tokens 400] [--kv-bits 8] [--prefill-step 256]`; first build ~10 min, a run ~4 min — run it in
107+the background, the host.sh client must not be killed by a timeout). Trap: with thinking on, greedy
108+answers differ between cold and warm; that is prefill chunking noise (control with --prefill-step),
109+not a bug. Open question: prefill only ~140–190 tok/s on Qwen3-4B-4bit — check the chip / compare
110+with `rzb serve` logs before quoting absolute numbers.
@@ -98,3 +98,13 @@ Docs EN+FR rewritten (see summary). Remaining in the v0.2 milestone: #47 (KV-cac
98 priority high). Release not started: version string is still 0.1.0, milestone not closed — use the98 priority high). Release not started: version string is still 0.1.0, milestone not closed — use the
99 release skill only when the user asks. Mac run of `scripts/compat.sh` (now 14 doc curl examples) not99 release skill only when the user asks. Mac run of `scripts/compat.sh` (now 14 doc curl examples) not
100 done since #44.100 done since #44.
101+
102+## Update — #47 spike, tasks 1–2 done
103+Report = comment 1 on #47 (findings + proposal). Waiting on the user's decision: implement the
104+per-model prefix cache now (v0.2) or later; tasks 3–6 still open. `samples/02-kv-cache-reuse`
105+reproduces the numbers (`host.sh build|run samples/02-kv-cache-reuse kv-cache-reuse [--think
106+--max-tokens 400] [--kv-bits 8] [--prefill-step 256]`; first build ~10 min, a run ~4 min — run it in
107+the background, the host.sh client must not be killed by a timeout). Trap: with thinking on, greedy
108+answers differ between cold and warm; that is prefill chunking noise (control with --prefill-step),
109+not a bug. Open question: prefill only ~140–190 tok/s on Qwen3-4B-4bit — check the chip / compare
110+with `rzb serve` logs before quoting absolute numbers.
modified .memory/history.md +15 -0
@@ -263,3 +263,18 @@ Hummingbird box. test_docs_curl.py maps doc model ids to the suite's ids: 14 cur
263263 (Linux/fake). Link/anchor check script: 0 broken. Gate PASS (run #21). Closed #45 and #31 (its last
264264 task was the architecture doc). Not done: Mac run of the doc curl examples (needs the user), version
265265 bump to 0.2.0 (release step), milestone still has #47 open.
266+
267+## 2026-11-25 — #47 KV-cache spike, short version (tasks 1–2)
268+
269+User asked what #47 was worth, then chose the short version: read the mlx-swift-lm cache code and
270+measure prefix reuse. Added `samples/02-kv-cache-reuse` (standalone, xcodebuild on the Mac via the
271+host-runner): plays a ~4k-token conversation cold (fresh cache per request) and warm (one cache,
272+`trimPromptCache` to the longest common prefix with the previous prompt, prefill the rest), greedy,
273+compares answers. Results (Qwen3-4B-4bit): TTFT 25–30 s → 0.3–0.8 s (34–56×); 4/4 identical answers
274+thinking off (bf16 and 8-bit KV); thinking on differs from turn 2 — a control run with prefill step
275+256 vs 512 and no reuse also changes the turn-1 answer, so it is chunking noise. 144 KiB/token bf16,
276+76.5 KiB 8-bit. Report written as comment 1 on #47 with a proposal (prefix cache per model in
277+MLXEngine, cached_tokens in usage); tasks 1–2 closed, 3–6 open, ticket open. No server code changed.
278+Gate measures samples too: first FAIL (run #22, swiftlint identifier_name ×4 and opening_brace in the
279+sample), fixed by renaming, PASS (run #23); sample rebuilt on the Mac after the fix. Observed prefill speed
280+~140–190 tok/s for a 4B model looked low; not investigated.
@@ -263,3 +263,18 @@ Hummingbird box. test_docs_curl.py maps doc model ids to the suite's ids: 14 cur
263 (Linux/fake). Link/anchor check script: 0 broken. Gate PASS (run #21). Closed #45 and #31 (its last263 (Linux/fake). Link/anchor check script: 0 broken. Gate PASS (run #21). Closed #45 and #31 (its last
264 task was the architecture doc). Not done: Mac run of the doc curl examples (needs the user), version264 task was the architecture doc). Not done: Mac run of the doc curl examples (needs the user), version
265 bump to 0.2.0 (release step), milestone still has #47 open.265 bump to 0.2.0 (release step), milestone still has #47 open.
266+
267+## 2026-11-25 — #47 KV-cache spike, short version (tasks 1–2)
268+
269+User asked what #47 was worth, then chose the short version: read the mlx-swift-lm cache code and
270+measure prefix reuse. Added `samples/02-kv-cache-reuse` (standalone, xcodebuild on the Mac via the
271+host-runner): plays a ~4k-token conversation cold (fresh cache per request) and warm (one cache,
272+`trimPromptCache` to the longest common prefix with the previous prompt, prefill the rest), greedy,
273+compares answers. Results (Qwen3-4B-4bit): TTFT 25–30 s → 0.3–0.8 s (34–56×); 4/4 identical answers
274+thinking off (bf16 and 8-bit KV); thinking on differs from turn 2 — a control run with prefill step
275+256 vs 512 and no reuse also changes the turn-1 answer, so it is chunking noise. 144 KiB/token bf16,
276+76.5 KiB 8-bit. Report written as comment 1 on #47 with a proposal (prefix cache per model in
277+MLXEngine, cached_tokens in usage); tasks 1–2 closed, 3–6 open, ticket open. No server code changed.
278+Gate measures samples too: first FAIL (run #22, swiftlint identifier_name ×4 and opening_brace in the
279+sample), fixed by renaming, PASS (run #23); sample rebuilt on the Mac after the fix. Observed prefill speed
280+~140–190 tok/s for a 4B model looked low; not investigated.
modified .memory/summary.md +9 -0
@@ -92,6 +92,15 @@ server (tutorial, 10 how-to, 4 reference incl. `http-api.md` / `api-http.md`, 5
9292 only successful calls in ```bash blocks. v0.2 tickets #31–#45 closed; #47 (KV-cache spike) still
9393 open in the milestone; version string still `0.1.0` (bump at release).
9494
95+KV cache (#47, tasks 1–2 done, report = comment 1 on the ticket): `rzb serve` reuses no KV cache
96+today (one new `ChatSession` per request). Measured with `samples/02-kv-cache-reuse` (Qwen3-4B-4bit,
97+4k-token history): rewinding a kept cache to the common token prefix cuts time to first token from
98+25–30 s to <1 s per turn; greedy answers identical with thinking off; with thinking on they differ,
99+but changing only the prefill step size already changes them (numeric, not a reuse bug). Qwen3-4B
100+KV = 144 KiB/token (bf16), 76.5 KiB (8-bit). mlx-swift-lm's own reuse policy is internal to
101+`ChatSession`; hybrid (ArraysCache/Mamba) caches cannot be trimmed, rotating ones only before
102+wrapping. Implementation not decided yet (proposal in the report).
103+
95104 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
96105
97106 Swift 6.2 tools / Swift 6 language mode. Modules: `RazorbillCore` (YAML config via Yams, agent
@@ -92,6 +92,15 @@ server (tutorial, 10 how-to, 4 reference incl. `http-api.md` / `api-http.md`, 5
92 only successful calls in ```bash blocks. v0.2 tickets #31–#45 closed; #47 (KV-cache spike) still92 only successful calls in ```bash blocks. v0.2 tickets #31–#45 closed; #47 (KV-cache spike) still
93 open in the milestone; version string still `0.1.0` (bump at release).93 open in the milestone; version string still `0.1.0` (bump at release).
94 94
95+KV cache (#47, tasks 1–2 done, report = comment 1 on the ticket): `rzb serve` reuses no KV cache
96+today (one new `ChatSession` per request). Measured with `samples/02-kv-cache-reuse` (Qwen3-4B-4bit,
97+4k-token history): rewinding a kept cache to the common token prefix cuts time to first token from
98+25–30 s to <1 s per turn; greedy answers identical with thinking off; with thinking on they differ,
99+but changing only the prefill step size already changes them (numeric, not a reuse bug). Qwen3-4B
100+KV = 144 KiB/token (bf16), 76.5 KiB (8-bit). mlx-swift-lm's own reuse policy is internal to
101+`ChatSession`; hybrid (ArraysCache/Mamba) caches cannot be trimmed, rotating ones only before
102+wrapping. Implementation not decided yet (proposal in the report).
103+
95 ## Architecture of v0.1 (agent, removed on the v0.2 branch)104 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
96 105
97 Swift 6.2 tools / Swift 6 language mode. Modules: `RazorbillCore` (YAML config via Yams, agent106 Swift 6.2 tools / Swift 6 language mode. Modules: `RazorbillCore` (YAML config via Yams, agent
modified .quality/history.jsonl +2 -0
@@ -19,3 +19,5 @@
1919 {"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"}
2020 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"}
2121 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "c1a7231", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 21, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T19:12:45Z"}
22+{"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 4 (max 0)", "warning-level issues: 1 (max 0)"], "commit": "f2a20f5", "counts": {"error": 4, "warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 227, "complex": 538, "cyclo": 590, "fields": 1144, "funcs": 558, "lcom": 110, "lines": 10186, "loc": 8113}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 22, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:27:49Z"}
23+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "f2a20f5", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 227, "complex": 538, "cyclo": 590, "fields": 1144, "funcs": 558, "lcom": 110, "lines": 10189, "loc": 8116}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 23, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:28:10Z"}
@@ -19,3 +19,5 @@
19 {"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"}19 {"branch": "feature/v0.2-openai-server", "breaches": ["code smells: 2 (max 0)"], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 223, "complex": 513, "cyclo": 570, "fields": 1087, "funcs": 542, "lcom": 106, "lines": 9809, "loc": 7811}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 19, "smells": 2, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:20Z"}
20 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"}20 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "9be357d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 20, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T18:44:58Z"}
21 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "c1a7231", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 21, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T19:12:45Z"}21 {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "c1a7231", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 221, "complex": 512, "cyclo": 569, "fields": 1086, "funcs": 541, "lcom": 106, "lines": 9798, "loc": 7798}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 21, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T19:12:45Z"}
22+{"branch": "feature/v0.2-openai-server", "breaches": ["error-level issues: 4 (max 0)", "warning-level issues: 1 (max 0)"], "commit": "f2a20f5", "counts": {"error": 4, "warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 227, "complex": 538, "cyclo": 590, "fields": 1144, "funcs": 558, "lcom": 110, "lines": 10186, "loc": 8113}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 22, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:27:49Z"}
23+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "f2a20f5", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 227, "complex": 538, "cyclo": 590, "fields": 1144, "funcs": 558, "lcom": 110, "lines": 10189, "loc": 8116}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 23, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:28:10Z"}
added .quality/report-20261125T212749Z.md +86 -0
new file mode 100644
@@ -0,0 +1,86 @@
1+# Quality report — 2026-11-25T21:27:49Z
2+
3+- **Gate**: ❌ **FAIL**
4+- **Commit**: `f2a20f5` on `feature/v0.2-openai-server`
5+- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6+- **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7+- **Run**: #22 (previous: 2026-11-25T19:12:45Z)
8+
9+## Gate violations
10+
11+- error-level issues: 4 (max 0)
12+- warning-level issues: 1 (max 0)
13+
14+## Lint issues (`qlty check`)
15+
16+| level | count | vs previous |
17+|---|---|---|
18+| error | 4 | — |
19+| warning | 1 | — |
20+
21+### Top rules
22+
23+| rule | count |
24+|---|---|
25+| swiftlint:identifier_name | 4 |
26+| swiftlint:opening_brace | 1 |
27+
28+### Most affected files
29+
30+| file | issues |
31+|---|---|
32+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 5 |
33+
34+## Code smells (`qlty smells`)
35+
36+Total: **0** (vs previous: ±0)
37+
38+_none_
39+
40+## Metrics (`qlty metrics`)
41+
42+| metric | total | vs previous |
43+|---|---|---|
44+| funcs | 558 | +17 |
45+| classes | 227 | +6 |
46+| fields | 1144 | +58 |
47+| cyclo | 590 | +21 |
48+| complex | 538 | +26 |
49+| lcom | 110 | +4 |
50+| lines | 10186 | +388 |
51+| loc | 8113 | +315 |
52+
53+### Most complex files
54+
55+| file | complex | cyclo | loc |
56+|---|---|---|---|
57+| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
58+| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
59+| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
60+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 282 |
61+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
62+| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
63+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
64+| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 |
65+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 |
66+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 |
67+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
68+| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 |
69+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
70+| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
71+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
72+
73+## Trend
74+
75+| run | timestamp | error | warning | smells | complex | gate |
76+|---|---|---|---|---|---|---|
77+| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
78+| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
79+| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
80+| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
81+| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL |
82+| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
83+| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
84+| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
85+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
86+| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL |
new file mode 100644
@@ -0,0 +1,86 @@
1+# Quality report — 2026-11-25T21:27:49Z
2+
3+- **Gate**: ❌ **FAIL**
4+- **Commit**: `f2a20f5` on `feature/v0.2-openai-server`
5+- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6+- **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7+- **Run**: #22 (previous: 2026-11-25T19:12:45Z)
8+
9+## Gate violations
10+
11+- error-level issues: 4 (max 0)
12+- warning-level issues: 1 (max 0)
13+
14+## Lint issues (`qlty check`)
15+
16+| level | count | vs previous |
17+|---|---|---|
18+| error | 4 | — |
19+| warning | 1 | — |
20+
21+### Top rules
22+
23+| rule | count |
24+|---|---|
25+| swiftlint:identifier_name | 4 |
26+| swiftlint:opening_brace | 1 |
27+
28+### Most affected files
29+
30+| file | issues |
31+|---|---|
32+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 5 |
33+
34+## Code smells (`qlty smells`)
35+
36+Total: **0** (vs previous: ±0)
37+
38+_none_
39+
40+## Metrics (`qlty metrics`)
41+
42+| metric | total | vs previous |
43+|---|---|---|
44+| funcs | 558 | +17 |
45+| classes | 227 | +6 |
46+| fields | 1144 | +58 |
47+| cyclo | 590 | +21 |
48+| complex | 538 | +26 |
49+| lcom | 110 | +4 |
50+| lines | 10186 | +388 |
51+| loc | 8113 | +315 |
52+
53+### Most complex files
54+
55+| file | complex | cyclo | loc |
56+|---|---|---|---|
57+| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
58+| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
59+| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
60+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 282 |
61+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
62+| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
63+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
64+| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 |
65+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 |
66+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 |
67+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
68+| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 |
69+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
70+| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
71+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
72+
73+## Trend
74+
75+| run | timestamp | error | warning | smells | complex | gate |
76+|---|---|---|---|---|---|---|
77+| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
78+| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
79+| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
80+| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
81+| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL |
82+| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
83+| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
84+| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
85+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
86+| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL |
added .quality/report-20261125T212810Z.md +76 -0
new file mode 100644
@@ -0,0 +1,76 @@
1+# Quality report — 2026-11-25T21:28:10Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `f2a20f5` on `feature/v0.2-openai-server`
5+- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6+- **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7+- **Run**: #23 (previous: 2026-11-25T21:27:49Z)
8+
9+## Lint issues (`qlty check`)
10+
11+| level | count | vs previous |
12+|---|---|---|
13+| error | 0 | -4 |
14+| warning | 0 | -1 |
15+
16+### Top rules
17+
18+_none_
19+
20+### Most affected files
21+
22+_none_
23+
24+## Code smells (`qlty smells`)
25+
26+Total: **0** (vs previous: ±0)
27+
28+_none_
29+
30+## Metrics (`qlty metrics`)
31+
32+| metric | total | vs previous |
33+|---|---|---|
34+| funcs | 558 | ±0 |
35+| classes | 227 | ±0 |
36+| fields | 1144 | ±0 |
37+| cyclo | 590 | ±0 |
38+| complex | 538 | ±0 |
39+| lcom | 110 | ±0 |
40+| lines | 10189 | +3 |
41+| loc | 8116 | +3 |
42+
43+### Most complex files
44+
45+| file | complex | cyclo | loc |
46+|---|---|---|---|
47+| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
48+| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
49+| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
50+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 |
51+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
52+| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
53+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
54+| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 |
55+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 |
56+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 |
57+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
58+| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 |
59+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
60+| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
61+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
62+
63+## Trend
64+
65+| run | timestamp | error | warning | smells | complex | gate |
66+|---|---|---|---|---|---|---|
67+| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
68+| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
69+| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
70+| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL |
71+| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
72+| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
73+| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
74+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
75+| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL |
76+| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS |
new file mode 100644
@@ -0,0 +1,76 @@
1+# Quality report — 2026-11-25T21:28:10Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `f2a20f5` on `feature/v0.2-openai-server`
5+- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6+- **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7+- **Run**: #23 (previous: 2026-11-25T21:27:49Z)
8+
9+## Lint issues (`qlty check`)
10+
11+| level | count | vs previous |
12+|---|---|---|
13+| error | 0 | -4 |
14+| warning | 0 | -1 |
15+
16+### Top rules
17+
18+_none_
19+
20+### Most affected files
21+
22+_none_
23+
24+## Code smells (`qlty smells`)
25+
26+Total: **0** (vs previous: ±0)
27+
28+_none_
29+
30+## Metrics (`qlty metrics`)
31+
32+| metric | total | vs previous |
33+|---|---|---|
34+| funcs | 558 | ±0 |
35+| classes | 227 | ±0 |
36+| fields | 1144 | ±0 |
37+| cyclo | 590 | ±0 |
38+| complex | 538 | ±0 |
39+| lcom | 110 | ±0 |
40+| lines | 10189 | +3 |
41+| loc | 8116 | +3 |
42+
43+### Most complex files
44+
45+| file | complex | cyclo | loc |
46+|---|---|---|---|
47+| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
48+| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
49+| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
50+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 |
51+| tools/host-runner/host_runner.py | 22 | 22 | 141 |
52+| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
53+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
54+| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 |
55+| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 |
56+| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 |
57+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 |
58+| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 |
59+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
60+| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
61+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
62+
63+## Trend
64+
65+| run | timestamp | error | warning | smells | complex | gate |
66+|---|---|---|---|---|---|---|
67+| 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
68+| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
69+| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
70+| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL |
71+| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS |
72+| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
73+| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
74+| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
75+| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL |
76+| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS |
modified .quality/report-latest.md +18 -15
@@ -1,14 +1,17 @@
1-# Quality report — 2026-11-25T19:12:45Z
1+# Quality report — 2026-11-25T21:28:10Z
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `c1a7231` on `feature/v0.2-openai-server`
4+- **Commit**: `f2a20f5` on `feature/v0.2-openai-server`
55 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
66 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #21 (previous: 2026-11-25T18:44:58Z)
7+- **Run**: #23 (previous: 2026-11-25T21:27:49Z)
88
99 ## Lint issues (`qlty check`)
1010
11-_none_
11+| level | count | vs previous |
12+|---|---|---|
13+| error | 0 | -4 |
14+| warning | 0 | -1 |
1215
1316 ### Top rules
1417
@@ -28,14 +31,14 @@ _none_
2831
2932 | metric | total | vs previous |
3033 |---|---|---|
31-| funcs | 541 | ±0 |
32-| classes | 221 | ±0 |
33-| fields | 1086 | ±0 |
34-| cyclo | 569 | ±0 |
35-| complex | 512 | ±0 |
36-| lcom | 106 | ±0 |
37-| lines | 9798 | ±0 |
38-| loc | 7798 | ±0 |
34+| funcs | 558 | ±0 |
35+| classes | 227 | ±0 |
36+| fields | 1144 | ±0 |
37+| cyclo | 590 | ±0 |
38+| complex | 538 | ±0 |
39+| lcom | 110 | ±0 |
40+| lines | 10189 | +3 |
41+| loc | 8116 | +3 |
3942
4043 ### Most complex files
4144
@@ -44,6 +47,7 @@ _none_
4447 | Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
4548 | Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
4649 | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
50+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 |
4751 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
4852 | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
4953 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
@@ -55,14 +59,11 @@ _none_
5559 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
5660 | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
5761 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
58-| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 |
5962
6063 ## Trend
6164
6265 | run | timestamp | error | warning | smells | complex | gate |
6366 |---|---|---|---|---|---|---|
64-| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
65-| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
6667 | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
6768 | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
6869 | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
@@ -71,3 +72,5 @@ _none_
7172 | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
7273 | 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
7374 | 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
75+| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL |
76+| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS |
@@ -1,14 +1,17 @@
1-# Quality report — 2026-11-25T19:12:45Z1+# Quality report — 2026-11-25T21:28:10Z
2 2
3 - **Gate**: ✅ **PASS**3 - **Gate**: ✅ **PASS**
4-- **Commit**: `c1a7231` on `feature/v0.2-openai-server`4+- **Commit**: `f2a20f5` on `feature/v0.2-openai-server`
5 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)5 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
6 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)6 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #21 (previous: 2026-11-25T18:44:58Z)7+- **Run**: #23 (previous: 2026-11-25T21:27:49Z)
8 8
9 ## Lint issues (`qlty check`)9 ## Lint issues (`qlty check`)
10 10
11-_none_11+| level | count | vs previous |
12+|---|---|---|
13+| error | 0 | -4 |
14+| warning | 0 | -1 |
12 15
13 ### Top rules16 ### Top rules
14 17
@@ -28,14 +31,14 @@ _none_
28 31
29 | metric | total | vs previous |32 | metric | total | vs previous |
30 |---|---|---|33 |---|---|---|
31-| funcs | 541 | ±0 |34+| funcs | 558 | ±0 |
32-| classes | 221 | ±0 |35+| classes | 227 | ±0 |
33-| fields | 1086 | ±0 |36+| fields | 1144 | ±0 |
34-| cyclo | 569 | ±0 |37+| cyclo | 590 | ±0 |
35-| complex | 512 | ±0 |38+| complex | 538 | ±0 |
36-| lcom | 106 | ±0 |39+| lcom | 110 | ±0 |
37-| lines | 9798 | ±0 |40+| lines | 10189 | +3 |
38-| loc | 7798 | ±0 |41+| loc | 8116 | +3 |
39 42
40 ### Most complex files43 ### Most complex files
41 44
@@ -44,6 +47,7 @@ _none_
44 | Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |47 | Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 |
45 | Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |48 | Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 |
46 | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |49 | Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 |
50+| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 |
47 | tools/host-runner/host_runner.py | 22 | 22 | 141 |51 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
48 | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |52 | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 |
49 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |53 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 |
@@ -55,14 +59,11 @@ _none_
55 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |59 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
56 | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |60 | Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 |
57 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |61 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 |
58-| Tests/RazorbillServerTests/ModelManagerTests.swift | 12 | 10 | 263 |
59 62
60 ## Trend63 ## Trend
61 64
62 | run | timestamp | error | warning | smells | complex | gate |65 | run | timestamp | error | warning | smells | complex | gate |
63 |---|---|---|---|---|---|---|66 |---|---|---|---|---|---|---|
64-| 12 | 2026-11-25T12:48:22Z | 0 | 0 | 0 | 329 | PASS |
65-| 13 | 2026-11-25T12:55:33Z | 0 | 0 | 0 | 338 | PASS |
66 | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |67 | 14 | 2026-11-25T13:25:34Z | 1 | 3 | 2 | 406 | FAIL |
67 | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |68 | 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS |
68 | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |69 | 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS |
@@ -71,3 +72,5 @@ _none_
71 | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |72 | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL |
72 | 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |73 | 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS |
73 | 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |74 | 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS |
75+| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL |
76+| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS |
modified .tickets/issues/0047-spike-kv-cache-how-it-works-and-what-a-server-ca.yaml +80 -4
@@ -6,7 +6,7 @@ author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-25T04:56:08.000Z
9-updatedAt: 2026-11-25T04:56:08.000Z
9+updatedAt: 2026-11-25T21:00:00.000Z
1010 labels:
1111 - "spike"
1212 - "area::engine"
@@ -43,20 +43,24 @@ body: |
4343 tasks:
4444 - id: 1
4545 title: "Read the mlx-swift-lm cache code and write how it works (types, sizes, hybrid models)"
46- state: open
46+ state: closed
4747 priority: high
4848 author:
4949 name: k33g
5050 email: ph.charriere@gmail.com
5151 createdAt: 2026-11-25T04:56:08.000Z
52+ updatedAt: 2026-11-25T21:00:00.000Z
53+ closedAt: 2026-11-25T21:00:00.000Z
5254 - id: 2
5355 title: "Prototype prefix reuse between two stateless requests and measure prefill time"
54- state: open
56+ state: closed
5557 priority: high
5658 author:
5759 name: k33g
5860 email: ph.charriere@gmail.com
5961 createdAt: 2026-11-25T04:56:08.000Z
62+ updatedAt: 2026-11-25T21:00:00.000Z
63+ closedAt: 2026-11-25T21:00:00.000Z
6064 - id: 3
6165 title: "Check trimming on rotating, quantized and hybrid (GatedDelta) caches"
6266 state: open
@@ -89,4 +93,76 @@ tasks:
8993 name: k33g
9094 email: ph.charriere@gmail.com
9195 createdAt: 2026-11-25T04:56:08.000Z
92-comments: []
96+comments:
97+ - id: 1
98+ author:
99+ name: k33g
100+ email: ph.charriere@gmail.com
101+ createdAt: 2026-11-25T21:00:00.000Z
102+ body: |
103+ ## Report, part 1: how the cache works and measured prefix reuse (tasks 1 and 2)
104+
105+ ### How the KV cache works (mlx-swift-lm 3.32.3)
106+ - For each attention layer, the cache holds the key and value vectors of every token processed so far. Size per token = 2 (K and V) × layers × KV heads × head dim × bytes per value.
107+ - Qwen3-4B: 2 × 36 × 8 × 128 × 2 bytes = **144 KiB per token**, which matches the measured 144.0 KiB. That is about 580 MiB for 4k tokens and 4.5 GiB for 32k tokens.
108+ - An 8-bit quantized cache measures **76.5 KiB per token**, including scales and biases. A 4-bit cache would be about 40 KiB (computed, not measured).
109+ - GQA already reduces the size: 8 KV heads instead of 32 query heads.
110+ - Cache types and rewinding (`trim`):
111+ - `KVCacheSimple` (default) and `QuantizedKVCache` can be trimmed exactly. The simple cache grows by blocks of 256 tokens.
112+ - `RotatingKVCache` (sliding-window models: Gemma 3/3n/4, Mistral 3, GPT-OSS, Olmo 3, Exaone 4…, or `maxKVSize`) can be trimmed exactly only until the window wraps. A long conversation then has to be rebuilt.
113+ - `ArraysCache` / `MambaCache` (hybrid models: Qwen3.5, Qwen3-Next, LFM2, Jamba, FalconH1, NemotronH, GraniteMoeHybrid, Mamba2) **cannot be trimmed**. `canTrimPromptCache` returns false for them, so the cache is rebuilt. Reusing it would need a snapshot of the recurrent state taken at the end of the prompt prefill. That is not done.
114+ - The library already reuses prefixes, but only **inside one `ChatSession`**. That logic is `PromptCacheReusePolicy`: longest-common-prefix rewind, rebuild fallback, and rules per response protocol. It also fills `GenerateCompletionInfo.cachedPromptTokenCount`. razorbill creates a new `ChatSession` per request (`MLXEngine.makeSession`), so **nothing is reused today**.
115+ - The policy is `internal` and `KVCacheStorage` is `package`, so the server has to do the reconciliation itself. It can do so with public building blocks:
116+ - `model.newCache(parameters:)`;
117+ - `processor.prepare` to get the prompt tokens;
118+ - `canTrimPromptCache` / `trimPromptCache`;
119+ - the free function `generate(input:cache:parameters:context:components:tools:)`, which still parses tool calls and accepts our logit processors.
120+
121+ ### Prototype: `samples/02-kv-cache-reuse`
122+ The prototype plays the same conversation twice, the way a stateless OpenAI client does:
123+ - a system prompt plus about 4k tokens of notes and acknowledgements, then N questions;
124+ - each answer is sent back without its reasoning.
125+
126+ The two runs:
127+ - **cold**: an empty cache for every request, which is what `rzb serve` does today;
128+ - **warm**: one cache kept between requests, rewound to the longest common token prefix with the previous prompt, then only the rest is prefilled.
129+
130+ Decoding is greedy, so the answers can be compared. Measured on the Mac with mlx-community/Qwen3-4B-4bit, through the host-runner.
131+
132+ | Run | Prompt | Reused (turns 2+) | First token, cold | First token, warm | Same answers |
133+ | --- | --- | --- | --- | --- | --- |
134+ | thinking off, bf16 KV | 4012–4108 | 4008–4078 | 28.6–30.2 s | 0.33–0.76 s (**48×**) | 4/4 |
135+ | thinking off, 8-bit KV | 4012–4108 | 4008–4078 | 25.9–26.8 s | 0.31–0.57 s (**56×**) | 4/4 |
136+ | thinking on, 400 tokens | 4128–4247 | 4128–4213 | 24.3–25.2 s | 0.51–0.84 s (**34×**) | 1/4 (see below) |
137+
138+ Findings:
139+ 1. On a 4k-token history, the **time to first token falls from 25–30 s to under 1 s** for every turn after the first. The tokens that are prefilled again are the new question plus the previous answer as the client rendered it: 30–45 tokens.
140+ 2. **Thinking does not break the prefix.** Qwen3's template drops the reasoning of earlier turns, but the previous prompt ends before the answer, so it is reused whole. Only the generated tokens, including the reasoning, are trimmed away, and the answer is prefilled again.
141+ 3. **Correctness.**
142+ - With thinking off, warm and cold answers are identical (4/4, with bf16 and with the 8-bit cache).
143+ - With thinking on, they differ from turn 2 onwards. Turns 3 and 4 differ necessarily, because each run then sends back its own answers.
144+ - A control run with no reuse at all, changing only the prefill step (512 → 256), already changes the turn-1 answer.
145+ - So a different chunking of the same prompt is enough to flip a greedy choice somewhere in a 400-token reasoning chain (4-bit weights, bf16 activations). It is not a reuse bug. The turn-2 answers say the same thing ("Part 3 mentions the cache budget first…").
146+ 4. **8-bit KV** halves the cache memory (144 → 76.5 KiB/token). It gave the same answers on this test and was not slower. 4-bit KV and TurboQuant are not measured yet (task 4).
147+ 5. Prefill throughput is about 140–190 tokens/s for a 4B 4-bit model. That seems low and is worth comparing with `rzb serve` logs and the Mac's chip. It does not change the ratio.
148+
149+ ### Not covered yet
150+ - Trimming rotating and hybrid caches on real models (task 3).
151+ - 4-bit and TurboQuant KV (task 4).
152+ - Persisted prompt caches (task 5).
153+ - How a kept cache fits the 75 % memory budget (#26).
154+ - Interaction with constrained decoding (#38) and cancellation. After a cancelled generation, the cache offset is read from the cache itself, so a rewind stays correct.
155+
156+ ### Proposal (decision pending)
157+ **One implementation ticket**: a prefix cache per loaded model in `MLXEngine`.
158+ - Keep one `[KVCache]` and the token ledger of the last prompt.
159+ - On each request: render the tokens, rewind to the common prefix, and rebuild when the cache cannot be trimmed (hybrid models, a wrapped window, or a different tool/system setup, which simply gives a short common prefix).
160+ - Report `usage.prompt_tokens_details.cached_tokens`.
161+ - Count the cache in the memory budget, and drop it on unload and `keep_alive`.
162+ - Requests are already serialized per model (#34), so one entry per model is enough.
163+
164+ **Later tickets**:
165+ - a `kv_bits` setting;
166+ - a hybrid-state snapshot;
167+ - a multi-entry LRU, for several conversations alternating on one model.
168+
@@ -6,7 +6,7 @@ author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-25T04:56:08.000Z8 createdAt: 2026-11-25T04:56:08.000Z
9-updatedAt: 2026-11-25T04:56:08.000Z9+updatedAt: 2026-11-25T21:00:00.000Z
10 labels:10 labels:
11 - "spike"11 - "spike"
12 - "area::engine"12 - "area::engine"
@@ -43,20 +43,24 @@ body: |
43 tasks:43 tasks:
44 - id: 144 - id: 1
45 title: "Read the mlx-swift-lm cache code and write how it works (types, sizes, hybrid models)"45 title: "Read the mlx-swift-lm cache code and write how it works (types, sizes, hybrid models)"
46- state: open46+ state: closed
47 priority: high47 priority: high
48 author:48 author:
49 name: k33g49 name: k33g
50 email: ph.charriere@gmail.com50 email: ph.charriere@gmail.com
51 createdAt: 2026-11-25T04:56:08.000Z51 createdAt: 2026-11-25T04:56:08.000Z
52+ updatedAt: 2026-11-25T21:00:00.000Z
53+ closedAt: 2026-11-25T21:00:00.000Z
52 - id: 254 - id: 2
53 title: "Prototype prefix reuse between two stateless requests and measure prefill time"55 title: "Prototype prefix reuse between two stateless requests and measure prefill time"
54- state: open56+ state: closed
55 priority: high57 priority: high
56 author:58 author:
57 name: k33g59 name: k33g
58 email: ph.charriere@gmail.com60 email: ph.charriere@gmail.com
59 createdAt: 2026-11-25T04:56:08.000Z61 createdAt: 2026-11-25T04:56:08.000Z
62+ updatedAt: 2026-11-25T21:00:00.000Z
63+ closedAt: 2026-11-25T21:00:00.000Z
60 - id: 364 - id: 3
61 title: "Check trimming on rotating, quantized and hybrid (GatedDelta) caches"65 title: "Check trimming on rotating, quantized and hybrid (GatedDelta) caches"
62 state: open66 state: open
@@ -89,4 +93,76 @@ tasks:
89 name: k33g93 name: k33g
90 email: ph.charriere@gmail.com94 email: ph.charriere@gmail.com
91 createdAt: 2026-11-25T04:56:08.000Z95 createdAt: 2026-11-25T04:56:08.000Z
92-comments: []96+comments:
97+ - id: 1
98+ author:
99+ name: k33g
100+ email: ph.charriere@gmail.com
101+ createdAt: 2026-11-25T21:00:00.000Z
102+ body: |
103+ ## Report, part 1: how the cache works and measured prefix reuse (tasks 1 and 2)
104+
105+ ### How the KV cache works (mlx-swift-lm 3.32.3)
106+ - For each attention layer, the cache holds the key and value vectors of every token processed so far. Size per token = 2 (K and V) × layers × KV heads × head dim × bytes per value.
107+ - Qwen3-4B: 2 × 36 × 8 × 128 × 2 bytes = **144 KiB per token**, which matches the measured 144.0 KiB. That is about 580 MiB for 4k tokens and 4.5 GiB for 32k tokens.
108+ - An 8-bit quantized cache measures **76.5 KiB per token**, including scales and biases. A 4-bit cache would be about 40 KiB (computed, not measured).
109+ - GQA already reduces the size: 8 KV heads instead of 32 query heads.
110+ - Cache types and rewinding (`trim`):
111+ - `KVCacheSimple` (default) and `QuantizedKVCache` can be trimmed exactly. The simple cache grows by blocks of 256 tokens.
112+ - `RotatingKVCache` (sliding-window models: Gemma 3/3n/4, Mistral 3, GPT-OSS, Olmo 3, Exaone 4…, or `maxKVSize`) can be trimmed exactly only until the window wraps. A long conversation then has to be rebuilt.
113+ - `ArraysCache` / `MambaCache` (hybrid models: Qwen3.5, Qwen3-Next, LFM2, Jamba, FalconH1, NemotronH, GraniteMoeHybrid, Mamba2) **cannot be trimmed**. `canTrimPromptCache` returns false for them, so the cache is rebuilt. Reusing it would need a snapshot of the recurrent state taken at the end of the prompt prefill. That is not done.
114+ - The library already reuses prefixes, but only **inside one `ChatSession`**. That logic is `PromptCacheReusePolicy`: longest-common-prefix rewind, rebuild fallback, and rules per response protocol. It also fills `GenerateCompletionInfo.cachedPromptTokenCount`. razorbill creates a new `ChatSession` per request (`MLXEngine.makeSession`), so **nothing is reused today**.
115+ - The policy is `internal` and `KVCacheStorage` is `package`, so the server has to do the reconciliation itself. It can do so with public building blocks:
116+ - `model.newCache(parameters:)`;
117+ - `processor.prepare` to get the prompt tokens;
118+ - `canTrimPromptCache` / `trimPromptCache`;
119+ - the free function `generate(input:cache:parameters:context:components:tools:)`, which still parses tool calls and accepts our logit processors.
120+
121+ ### Prototype: `samples/02-kv-cache-reuse`
122+ The prototype plays the same conversation twice, the way a stateless OpenAI client does:
123+ - a system prompt plus about 4k tokens of notes and acknowledgements, then N questions;
124+ - each answer is sent back without its reasoning.
125+
126+ The two runs:
127+ - **cold**: an empty cache for every request, which is what `rzb serve` does today;
128+ - **warm**: one cache kept between requests, rewound to the longest common token prefix with the previous prompt, then only the rest is prefilled.
129+
130+ Decoding is greedy, so the answers can be compared. Measured on the Mac with mlx-community/Qwen3-4B-4bit, through the host-runner.
131+
132+ | Run | Prompt | Reused (turns 2+) | First token, cold | First token, warm | Same answers |
133+ | --- | --- | --- | --- | --- | --- |
134+ | thinking off, bf16 KV | 4012–4108 | 4008–4078 | 28.6–30.2 s | 0.33–0.76 s (**48×**) | 4/4 |
135+ | thinking off, 8-bit KV | 4012–4108 | 4008–4078 | 25.9–26.8 s | 0.31–0.57 s (**56×**) | 4/4 |
136+ | thinking on, 400 tokens | 4128–4247 | 4128–4213 | 24.3–25.2 s | 0.51–0.84 s (**34×**) | 1/4 (see below) |
137+
138+ Findings:
139+ 1. On a 4k-token history, the **time to first token falls from 25–30 s to under 1 s** for every turn after the first. The tokens that are prefilled again are the new question plus the previous answer as the client rendered it: 30–45 tokens.
140+ 2. **Thinking does not break the prefix.** Qwen3's template drops the reasoning of earlier turns, but the previous prompt ends before the answer, so it is reused whole. Only the generated tokens, including the reasoning, are trimmed away, and the answer is prefilled again.
141+ 3. **Correctness.**
142+ - With thinking off, warm and cold answers are identical (4/4, with bf16 and with the 8-bit cache).
143+ - With thinking on, they differ from turn 2 onwards. Turns 3 and 4 differ necessarily, because each run then sends back its own answers.
144+ - A control run with no reuse at all, changing only the prefill step (512 → 256), already changes the turn-1 answer.
145+ - So a different chunking of the same prompt is enough to flip a greedy choice somewhere in a 400-token reasoning chain (4-bit weights, bf16 activations). It is not a reuse bug. The turn-2 answers say the same thing ("Part 3 mentions the cache budget first…").
146+ 4. **8-bit KV** halves the cache memory (144 → 76.5 KiB/token). It gave the same answers on this test and was not slower. 4-bit KV and TurboQuant are not measured yet (task 4).
147+ 5. Prefill throughput is about 140–190 tokens/s for a 4B 4-bit model. That seems low and is worth comparing with `rzb serve` logs and the Mac's chip. It does not change the ratio.
148+
149+ ### Not covered yet
150+ - Trimming rotating and hybrid caches on real models (task 3).
151+ - 4-bit and TurboQuant KV (task 4).
152+ - Persisted prompt caches (task 5).
153+ - How a kept cache fits the 75 % memory budget (#26).
154+ - Interaction with constrained decoding (#38) and cancellation. After a cancelled generation, the cache offset is read from the cache itself, so a rewind stays correct.
155+
156+ ### Proposal (decision pending)
157+ **One implementation ticket**: a prefix cache per loaded model in `MLXEngine`.
158+ - Keep one `[KVCache]` and the token ledger of the last prompt.
159+ - On each request: render the tokens, rewind to the common prefix, and rebuild when the cache cannot be trimmed (hybrid models, a wrapped window, or a different tool/system setup, which simply gives a short common prefix).
160+ - Report `usage.prompt_tokens_details.cached_tokens`.
161+ - Count the cache in the memory budget, and drop it on unload and `keep_alive`.
162+ - Requests are already serialized per model (#34), so one entry per model is enough.
163+
164+ **Later tickets**:
165+ - a `kv_bits` setting;
166+ - a hybrid-state snapshot;
167+ - a multi-entry LRU, for several conversations alternating on one model.
168+
added samples/02-kv-cache-reuse/.gitignore +3 -0
new file mode 100644
@@ -0,0 +1,3 @@
1+.build/
2+.swiftpm/
3+DerivedData/
new file mode 100644
@@ -0,0 +1,3 @@
1+.build/
2+.swiftpm/
3+DerivedData/
added samples/02-kv-cache-reuse/Package.resolved +123 -0
new file mode 100644
@@ -0,0 +1,123 @@
1+{
2+ "originHash" : "69a96eca9100b268a1b80a7bbcca4c3ccb56ae373ddbe2588937e9159d063552",
3+ "pins" : [
4+ {
5+ "identity" : "eventsource",
6+ "kind" : "remoteSourceControl",
7+ "location" : "https://github.com/mattt/EventSource.git",
8+ "state" : {
9+ "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1",
10+ "version" : "1.6.0"
11+ }
12+ },
13+ {
14+ "identity" : "mlx-swift",
15+ "kind" : "remoteSourceControl",
16+ "location" : "https://github.com/ml-explore/mlx-swift",
17+ "state" : {
18+ "revision" : "19601207e9a0de51e03ee6ec0c3c5f3784275075",
19+ "version" : "0.32.3"
20+ }
21+ },
22+ {
23+ "identity" : "mlx-swift-lm",
24+ "kind" : "remoteSourceControl",
25+ "location" : "https://github.com/ml-explore/mlx-swift-lm",
26+ "state" : {
27+ "revision" : "3b339ad6e3b3f44c8121ecff5131c7fd55e075e6",
28+ "version" : "3.32.3"
29+ }
30+ },
31+ {
32+ "identity" : "swift-argument-parser",
33+ "kind" : "remoteSourceControl",
34+ "location" : "https://github.com/apple/swift-argument-parser",
35+ "state" : {
36+ "revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
37+ "version" : "1.8.2"
38+ }
39+ },
40+ {
41+ "identity" : "swift-asn1",
42+ "kind" : "remoteSourceControl",
43+ "location" : "https://github.com/apple/swift-asn1.git",
44+ "state" : {
45+ "revision" : "97fd57437fc94cfa6b62f2b8f84c50f433534e17",
46+ "version" : "1.7.5"
47+ }
48+ },
49+ {
50+ "identity" : "swift-collections",
51+ "kind" : "remoteSourceControl",
52+ "location" : "https://github.com/apple/swift-collections.git",
53+ "state" : {
54+ "revision" : "88754449ab766a739610b660e117762115fabc9c",
55+ "version" : "1.7.6"
56+ }
57+ },
58+ {
59+ "identity" : "swift-crypto",
60+ "kind" : "remoteSourceControl",
61+ "location" : "https://github.com/apple/swift-crypto.git",
62+ "state" : {
63+ "revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f",
64+ "version" : "4.5.2"
65+ }
66+ },
67+ {
68+ "identity" : "swift-huggingface",
69+ "kind" : "remoteSourceControl",
70+ "location" : "https://github.com/huggingface/swift-huggingface",
71+ "state" : {
72+ "revision" : "f0a0cb43cb1b402d2bbf6fb10d8981328c449c48",
73+ "version" : "0.13.0"
74+ }
75+ },
76+ {
77+ "identity" : "swift-jinja",
78+ "kind" : "remoteSourceControl",
79+ "location" : "https://github.com/huggingface/swift-jinja.git",
80+ "state" : {
81+ "revision" : "3104efda56131c37dda52e9142f02cc2425c02e6",
82+ "version" : "3.2.1"
83+ }
84+ },
85+ {
86+ "identity" : "swift-numerics",
87+ "kind" : "remoteSourceControl",
88+ "location" : "https://github.com/apple/swift-numerics",
89+ "state" : {
90+ "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2",
91+ "version" : "1.1.1"
92+ }
93+ },
94+ {
95+ "identity" : "swift-syntax",
96+ "kind" : "remoteSourceControl",
97+ "location" : "https://github.com/swiftlang/swift-syntax.git",
98+ "state" : {
99+ "revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1",
100+ "version" : "603.0.2"
101+ }
102+ },
103+ {
104+ "identity" : "swift-transformers",
105+ "kind" : "remoteSourceControl",
106+ "location" : "https://github.com/huggingface/swift-transformers",
107+ "state" : {
108+ "revision" : "402a8a1105f52038b0949d9596981fc9e32bed17",
109+ "version" : "1.4.0"
110+ }
111+ },
112+ {
113+ "identity" : "yyjson",
114+ "kind" : "remoteSourceControl",
115+ "location" : "https://github.com/ibireme/yyjson.git",
116+ "state" : {
117+ "revision" : "6447536015f3d600f3d65323b10976103b337ca7",
118+ "version" : "0.13.0"
119+ }
120+ }
121+ ],
122+ "version" : 3
123+}
new file mode 100644
@@ -0,0 +1,123 @@
1+{
2+ "originHash" : "69a96eca9100b268a1b80a7bbcca4c3ccb56ae373ddbe2588937e9159d063552",
3+ "pins" : [
4+ {
5+ "identity" : "eventsource",
6+ "kind" : "remoteSourceControl",
7+ "location" : "https://github.com/mattt/EventSource.git",
8+ "state" : {
9+ "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1",
10+ "version" : "1.6.0"
11+ }
12+ },
13+ {
14+ "identity" : "mlx-swift",
15+ "kind" : "remoteSourceControl",
16+ "location" : "https://github.com/ml-explore/mlx-swift",
17+ "state" : {
18+ "revision" : "19601207e9a0de51e03ee6ec0c3c5f3784275075",
19+ "version" : "0.32.3"
20+ }
21+ },
22+ {
23+ "identity" : "mlx-swift-lm",
24+ "kind" : "remoteSourceControl",
25+ "location" : "https://github.com/ml-explore/mlx-swift-lm",
26+ "state" : {
27+ "revision" : "3b339ad6e3b3f44c8121ecff5131c7fd55e075e6",
28+ "version" : "3.32.3"
29+ }
30+ },
31+ {
32+ "identity" : "swift-argument-parser",
33+ "kind" : "remoteSourceControl",
34+ "location" : "https://github.com/apple/swift-argument-parser",
35+ "state" : {
36+ "revision" : "6a52f3251125d74daf04fcbd5e6f08a75d074382",
37+ "version" : "1.8.2"
38+ }
39+ },
40+ {
41+ "identity" : "swift-asn1",
42+ "kind" : "remoteSourceControl",
43+ "location" : "https://github.com/apple/swift-asn1.git",
44+ "state" : {
45+ "revision" : "97fd57437fc94cfa6b62f2b8f84c50f433534e17",
46+ "version" : "1.7.5"
47+ }
48+ },
49+ {
50+ "identity" : "swift-collections",
51+ "kind" : "remoteSourceControl",
52+ "location" : "https://github.com/apple/swift-collections.git",
53+ "state" : {
54+ "revision" : "88754449ab766a739610b660e117762115fabc9c",
55+ "version" : "1.7.6"
56+ }
57+ },
58+ {
59+ "identity" : "swift-crypto",
60+ "kind" : "remoteSourceControl",
61+ "location" : "https://github.com/apple/swift-crypto.git",
62+ "state" : {
63+ "revision" : "da9d28d69ebe3894b18376c8f2395c2f37b8448f",
64+ "version" : "4.5.2"
65+ }
66+ },
67+ {
68+ "identity" : "swift-huggingface",
69+ "kind" : "remoteSourceControl",
70+ "location" : "https://github.com/huggingface/swift-huggingface",
71+ "state" : {
72+ "revision" : "f0a0cb43cb1b402d2bbf6fb10d8981328c449c48",
73+ "version" : "0.13.0"
74+ }
75+ },
76+ {
77+ "identity" : "swift-jinja",
78+ "kind" : "remoteSourceControl",
79+ "location" : "https://github.com/huggingface/swift-jinja.git",
80+ "state" : {
81+ "revision" : "3104efda56131c37dda52e9142f02cc2425c02e6",
82+ "version" : "3.2.1"
83+ }
84+ },
85+ {
86+ "identity" : "swift-numerics",
87+ "kind" : "remoteSourceControl",
88+ "location" : "https://github.com/apple/swift-numerics",
89+ "state" : {
90+ "revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2",
91+ "version" : "1.1.1"
92+ }
93+ },
94+ {
95+ "identity" : "swift-syntax",
96+ "kind" : "remoteSourceControl",
97+ "location" : "https://github.com/swiftlang/swift-syntax.git",
98+ "state" : {
99+ "revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1",
100+ "version" : "603.0.2"
101+ }
102+ },
103+ {
104+ "identity" : "swift-transformers",
105+ "kind" : "remoteSourceControl",
106+ "location" : "https://github.com/huggingface/swift-transformers",
107+ "state" : {
108+ "revision" : "402a8a1105f52038b0949d9596981fc9e32bed17",
109+ "version" : "1.4.0"
110+ }
111+ },
112+ {
113+ "identity" : "yyjson",
114+ "kind" : "remoteSourceControl",
115+ "location" : "https://github.com/ibireme/yyjson.git",
116+ "state" : {
117+ "revision" : "6447536015f3d600f3d65323b10976103b337ca7",
118+ "version" : "0.13.0"
119+ }
120+ }
121+ ],
122+ "version" : 3
123+}
added samples/02-kv-cache-reuse/Package.swift +42 -0
new file mode 100644
@@ -0,0 +1,42 @@
1+// swift-tools-version: 6.2
2+// Sample 02 — measure KV-cache prefix reuse between stateless chat requests (spike #47).
3+// macOS + Apple Silicon only: MLX runs on Metal. Build with `xcodebuild` (see README.md),
4+// because the SwiftPM command line cannot compile MLX's Metal shaders.
5+
6+import PackageDescription
7+
8+let package = Package(
9+ name: "kv-cache-reuse",
10+ platforms: [.macOS(.v14)],
11+ products: [
12+ // Explicit product so the scheme and the binary are both named `kv-cache-reuse`.
13+ .executable(name: "kv-cache-reuse", targets: ["KVCacheReuse"])
14+ ],
15+ dependencies: [
16+ // Disable the default FoundationModelsIntegration trait: this sample does not use
17+ // Apple's FoundationModels bridge, and the trait needs the macOS 27 SDK.
18+ .package(
19+ url: "https://github.com/ml-explore/mlx-swift-lm",
20+ .upToNextMinor(from: "3.32.3"),
21+ traits: []
22+ ),
23+ .package(url: "https://github.com/ml-explore/mlx-swift", from: "0.32.0"),
24+ .package(url: "https://github.com/huggingface/swift-huggingface", from: "0.9.0"),
25+ .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),
26+ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
27+ ],
28+ targets: [
29+ .executableTarget(
30+ name: "KVCacheReuse",
31+ dependencies: [
32+ .product(name: "MLX", package: "mlx-swift"),
33+ .product(name: "MLXLLM", package: "mlx-swift-lm"),
34+ .product(name: "MLXLMCommon", package: "mlx-swift-lm"),
35+ .product(name: "MLXHuggingFace", package: "mlx-swift-lm"),
36+ .product(name: "HuggingFace", package: "swift-huggingface"),
37+ .product(name: "Tokenizers", package: "swift-transformers"),
38+ .product(name: "ArgumentParser", package: "swift-argument-parser"),
39+ ]
40+ ),
41+ ]
42+)
new file mode 100644
@@ -0,0 +1,42 @@
1+// swift-tools-version: 6.2
2+// Sample 02 — measure KV-cache prefix reuse between stateless chat requests (spike #47).
3+// macOS + Apple Silicon only: MLX runs on Metal. Build with `xcodebuild` (see README.md),
4+// because the SwiftPM command line cannot compile MLX's Metal shaders.
5+
6+import PackageDescription
7+
8+let package = Package(
9+ name: "kv-cache-reuse",
10+ platforms: [.macOS(.v14)],
11+ products: [
12+ // Explicit product so the scheme and the binary are both named `kv-cache-reuse`.
13+ .executable(name: "kv-cache-reuse", targets: ["KVCacheReuse"])
14+ ],
15+ dependencies: [
16+ // Disable the default FoundationModelsIntegration trait: this sample does not use
17+ // Apple's FoundationModels bridge, and the trait needs the macOS 27 SDK.
18+ .package(
19+ url: "https://github.com/ml-explore/mlx-swift-lm",
20+ .upToNextMinor(from: "3.32.3"),
21+ traits: []
22+ ),
23+ .package(url: "https://github.com/ml-explore/mlx-swift", from: "0.32.0"),
24+ .package(url: "https://github.com/huggingface/swift-huggingface", from: "0.9.0"),
25+ .package(url: "https://github.com/huggingface/swift-transformers", from: "1.3.0"),
26+ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
27+ ],
28+ targets: [
29+ .executableTarget(
30+ name: "KVCacheReuse",
31+ dependencies: [
32+ .product(name: "MLX", package: "mlx-swift"),
33+ .product(name: "MLXLLM", package: "mlx-swift-lm"),
34+ .product(name: "MLXLMCommon", package: "mlx-swift-lm"),
35+ .product(name: "MLXHuggingFace", package: "mlx-swift-lm"),
36+ .product(name: "HuggingFace", package: "swift-huggingface"),
37+ .product(name: "Tokenizers", package: "swift-transformers"),
38+ .product(name: "ArgumentParser", package: "swift-argument-parser"),
39+ ]
40+ ),
41+ ]
42+)
added samples/02-kv-cache-reuse/README.md +51 -0
new file mode 100644
@@ -0,0 +1,51 @@
1+# Sample 02 — KV-cache prefix reuse between stateless requests
2+
3+A measurement program for spike #47. An OpenAI client resends the whole conversation with every request, so a server that starts each request from an empty KV cache prefills the full history every time. This program plays the same conversation twice and compares:
4+
5+- **cold** — each request starts from an empty cache (what `rzb serve` does today);
6+- **warm** — one cache is kept between requests; each request rewinds it (`trimPromptCache`) to the longest token prefix it shares with the previous prompt, then prefills only the rest.
7+
8+Generation is greedy (temperature 0), so both runs should give the same answers. The report compares them: a reused cache must be correct, not only fast.
9+
10+The conversation is a system prompt followed by notes and acknowledgements until it reaches `--history-tokens`, then `--turns` questions. After each answer, the program sends the answer back without its reasoning, as an OpenAI client does.
11+
12+## Build
13+
14+macOS and Apple Silicon only, built like [sample 01](../01-query-model/README.md):
15+
16+```bash
17+cd samples/02-kv-cache-reuse
18+xcodebuild build -scheme kv-cache-reuse -destination 'platform=macOS' -configuration Release \
19+ -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
20+```
21+
22+From the Linux sandbox: `tools/host-runner/host.sh build samples/02-kv-cache-reuse kv-cache-reuse`.
23+
24+## Run
25+
26+```bash
27+BIN=.build/xcode/Build/Products/Release/kv-cache-reuse
28+$BIN # Qwen3-4B-4bit, 4000-token history, 4 turns
29+$BIN --think --max-tokens 400 # thinking on: the reasoning is dropped from the history
30+$BIN --kv-bits 8 # 8-bit quantized KV cache
31+$BIN --model mlx-community/Llama-3.2-1B-Instruct-4bit --history-tokens 8000
32+```
33+
34+The report (Markdown) goes to stdout, progress to stderr.
35+
36+| Option | Default | Meaning |
37+| --- | --- | --- |
38+| `-m`, `--model` | `mlx-community/Qwen3-4B-4bit` | Hugging Face id of an MLX model |
39+| `--history-tokens` | 4000 | Approximate size of the history before the measured turns |
40+| `--turns` | 4 | Questions sent after the history, one stateless request each |
41+| `--max-tokens` | 64 | Maximum generated tokens per answer |
42+| `--kv-bits` | none | Quantize the KV cache to 4 or 8 bits |
43+| `--prefill-step` | 512 | Prompt tokens prefilled per step (to check how chunking alone changes greedy output) |
44+| `--think` | off | Enable thinking for reasoning models |
45+
46+## Reading the report
47+
48+- **Prefill** is mlx-swift-lm's `promptTime`: the time spent on the prompt tokens that were fed. **First token** is the wall-clock time until the first text chunk, which is what a client waits for.
49+- The first turn has nothing to reuse; compare turns 2 and later.
50+- **Same answer: no** on a turn means the warm cache produced different tokens from a cold prefill. Small numeric differences (prefill in one chunk or several) can do this with quantized weights. Check whether the answers still say the same thing.
51+- **KV cache** gives the bytes held after the last turn, per token, and what is allocated (the simple cache grows by blocks of 256 tokens).
new file mode 100644
@@ -0,0 +1,51 @@
1+# Sample 02 — KV-cache prefix reuse between stateless requests
2+
3+A measurement program for spike #47. An OpenAI client resends the whole conversation with every request, so a server that starts each request from an empty KV cache prefills the full history every time. This program plays the same conversation twice and compares:
4+
5+- **cold** — each request starts from an empty cache (what `rzb serve` does today);
6+- **warm** — one cache is kept between requests; each request rewinds it (`trimPromptCache`) to the longest token prefix it shares with the previous prompt, then prefills only the rest.
7+
8+Generation is greedy (temperature 0), so both runs should give the same answers. The report compares them: a reused cache must be correct, not only fast.
9+
10+The conversation is a system prompt followed by notes and acknowledgements until it reaches `--history-tokens`, then `--turns` questions. After each answer, the program sends the answer back without its reasoning, as an OpenAI client does.
11+
12+## Build
13+
14+macOS and Apple Silicon only, built like [sample 01](../01-query-model/README.md):
15+
16+```bash
17+cd samples/02-kv-cache-reuse
18+xcodebuild build -scheme kv-cache-reuse -destination 'platform=macOS' -configuration Release \
19+ -derivedDataPath .build/xcode -skipPackagePluginValidation -skipMacroValidation
20+```
21+
22+From the Linux sandbox: `tools/host-runner/host.sh build samples/02-kv-cache-reuse kv-cache-reuse`.
23+
24+## Run
25+
26+```bash
27+BIN=.build/xcode/Build/Products/Release/kv-cache-reuse
28+$BIN # Qwen3-4B-4bit, 4000-token history, 4 turns
29+$BIN --think --max-tokens 400 # thinking on: the reasoning is dropped from the history
30+$BIN --kv-bits 8 # 8-bit quantized KV cache
31+$BIN --model mlx-community/Llama-3.2-1B-Instruct-4bit --history-tokens 8000
32+```
33+
34+The report (Markdown) goes to stdout, progress to stderr.
35+
36+| Option | Default | Meaning |
37+| --- | --- | --- |
38+| `-m`, `--model` | `mlx-community/Qwen3-4B-4bit` | Hugging Face id of an MLX model |
39+| `--history-tokens` | 4000 | Approximate size of the history before the measured turns |
40+| `--turns` | 4 | Questions sent after the history, one stateless request each |
41+| `--max-tokens` | 64 | Maximum generated tokens per answer |
42+| `--kv-bits` | none | Quantize the KV cache to 4 or 8 bits |
43+| `--prefill-step` | 512 | Prompt tokens prefilled per step (to check how chunking alone changes greedy output) |
44+| `--think` | off | Enable thinking for reasoning models |
45+
46+## Reading the report
47+
48+- **Prefill** is mlx-swift-lm's `promptTime`: the time spent on the prompt tokens that were fed. **First token** is the wall-clock time until the first text chunk, which is what a client waits for.
49+- The first turn has nothing to reuse; compare turns 2 and later.
50+- **Same answer: no** on a turn means the warm cache produced different tokens from a cold prefill. Small numeric differences (prefill in one chunk or several) can do this with quantized weights. Check whether the answers still say the same thing.
51+- **KV cache** gives the bytes held after the last turn, per token, and what is allocated (the simple cache grows by blocks of 256 tokens).
added samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift +349 -0
new file mode 100644
@@ -0,0 +1,349 @@
1+// Sample 02 — measure KV-cache prefix reuse between stateless chat requests (spike #47).
2+//
3+// An OpenAI client resends the whole conversation with every request. This program plays the
4+// same conversation twice, the way such a client would:
5+//
6+// - cold: every request starts from an empty KV cache and prefills the whole prompt (what
7+// razorbill does today);
8+// - warm: one KV cache is kept between requests; each request rewinds it to the longest token
9+// prefix it shares with the previous prompt and prefills only the rest.
10+//
11+// Generation is greedy (temperature 0), so both runs should give the same answers; the report
12+// compares them, which checks that the reused cache is correct, not just fast.
13+
14+import ArgumentParser
15+import Foundation
16+import HuggingFace
17+import MLX
18+import MLXHuggingFace
19+import MLXLLM
20+import MLXLMCommon
21+import Tokenizers
22+
23+@main
24+struct KVCacheReuse: AsyncParsableCommand {
25+ static let configuration = CommandConfiguration(
26+ commandName: "kv-cache-reuse",
27+ abstract: "Compare prefill time with and without KV-cache prefix reuse."
28+ )
29+
30+ @Option(name: .shortAndLong, help: "Hugging Face model id (an MLX model).")
31+ var model = "mlx-community/Qwen3-4B-4bit"
32+
33+ @Option(help: "Approximate size of the conversation history, in tokens.")
34+ var historyTokens = 4000
35+
36+ @Option(help: "New turns sent after the history, each as a stateless request.")
37+ var turns = 4
38+
39+ @Option(help: "Maximum number of generated tokens per answer.")
40+ var maxTokens = 64
41+
42+ @Option(help: "Quantize the KV cache to this many bits (4 or 8). Default: not quantized.")
43+ var kvBits: Int?
44+
45+ @Option(help: "Prompt tokens prefilled per step. Default: mlx-swift-lm's (512).")
46+ var prefillStep: Int?
47+
48+ @Flag(help: "Let reasoning models (Qwen3...) think; the client sends answers back without it.")
49+ var think = false
50+
51+ func run() async throws {
52+ let settings = Settings(
53+ historyTokens: historyTokens, turns: turns, maxTokens: maxTokens, kvBits: kvBits,
54+ prefillStep: prefillStep, think: think)
55+ log("Loading \(model)...")
56+ let container = try await #huggingFaceLoadModelContainer(
57+ configuration: LLMRegistry.shared.configuration(id: model),
58+ progressHandler: { _ in })
59+ let modelName = model
60+ let report = try await container.perform { context in
61+ try await Benchmark(context: context, settings: settings).run(model: modelName)
62+ }
63+ print(report)
64+ }
65+}
66+
67+struct Settings: Sendable {
68+ let historyTokens: Int
69+ let turns: Int
70+ let maxTokens: Int
71+ let kvBits: Int?
72+ let prefillStep: Int?
73+ let think: Bool
74+}
75+
76+/// What one request cost.
77+struct Measure {
78+ let promptTokens: Int
79+ let reusedTokens: Int
80+ let prefillSeconds: Double
81+ let firstTokenSeconds: Double
82+ let generatedTokens: Int
83+ let answer: String
84+}
85+
86+/// One run of the conversation, cold or warm.
87+struct Run {
88+ var measures: [Measure] = []
89+ var usedBytes = 0
90+ var allocatedBytes = 0
91+ var cachedTokens = 0
92+}
93+
94+final class Benchmark {
95+ private let context: ModelContext
96+ private let settings: Settings
97+ private let parameters: GenerateParameters
98+
99+ init(context: ModelContext, settings: Settings) {
100+ self.context = context
101+ self.settings = settings
102+ var parameters = GenerateParameters(maxTokens: settings.maxTokens, temperature: 0)
103+ if let step = settings.prefillStep { parameters.prefill = .init(stepSize: step) }
104+ self.parameters = parameters
105+ }
106+
107+ func run(model: String) async throws -> String {
108+ let history = try await buildHistory()
109+ let historySize = try await render(history).count
110+ log("History: \(historySize) tokens. Cold run...")
111+ let cold = try await play(history, reuse: false)
112+ log("Warm run...")
113+ let warm = try await play(history, reuse: true)
114+ return Report(
115+ model: model, settings: settings, historyTokens: historySize, cold: cold, warm: warm
116+ ).text
117+ }
118+
119+ // MARK: - Playing the conversation
120+
121+ private func play(_ history: [Chat.Message], reuse: Bool) async throws -> Run {
122+ var messages = history
123+ var cache = try newCache()
124+ var previousPrompt: [Int] = []
125+ var run = Run()
126+ for index in 0 ..< settings.turns {
127+ messages.append(.user(Self.questions[index % Self.questions.count]))
128+ let prompt = try await render(messages)
129+ var start = 0
130+ if reuse && !previousPrompt.isEmpty {
131+ start = rewind(cache, to: prompt, previousPrompt: previousPrompt)
132+ if start == 0 { cache = try newCache() }
133+ } else {
134+ cache = try newCache()
135+ }
136+ let measure = try await generate(prompt, from: start, cache: cache)
137+ run.measures.append(measure)
138+ messages.append(.assistant(measure.answer))
139+ previousPrompt = prompt
140+ }
141+ let used = cache.flatMap(\.state).reduce(0) { $0 + $1.nbytes }
142+ let allocated = cache.compactMap { $0 as? BaseKVCache }
143+ .flatMap { $0.innerState() }.reduce(0) { $0 + $1.nbytes }
144+ run.usedBytes = used
145+ run.allocatedBytes = allocated
146+ run.cachedTokens = offset(of: cache)
147+ return run
148+ }
149+
150+ /// Rewinds `cache` to the longest prefix `prompt` shares with the previous prompt and returns
151+ /// where prefill must start, or 0 when the cache cannot be reused.
152+ private func rewind(_ cache: [KVCache], to prompt: [Int], previousPrompt: [Int]) -> Int {
153+ // At least one token must be fed to get the next token's logits.
154+ let common = min(
155+ zip(prompt, previousPrompt).prefix { $0 == $1 }.count, prompt.count - 1)
156+ // The cache also holds the previous answer, which the new prompt renders its own way.
157+ let extra = offset(of: cache) - common
158+ guard common > 0, extra >= 0 else { return 0 }
159+ if extra == 0 { return common }
160+ guard canTrimPromptCache(cache), trimPromptCache(cache, numTokens: extra) == extra
161+ else {
162+ log(" cache cannot be trimmed: rebuilding")
163+ return 0
164+ }
165+ return common
166+ }
167+
168+ private func generate(
169+ _ prompt: [Int], from start: Int, cache: [KVCache]
170+ ) async throws -> Measure {
171+ let input = LMInput(tokens: MLXArray(Array(prompt[start...])))
172+ let clock = ContinuousClock()
173+ let began = clock.now
174+ let stream = try MLXLMCommon.generate(
175+ input: input, cache: cache, parameters: parameters, context: context)
176+ var text = ""
177+ var firstToken: Duration?
178+ var info: GenerateCompletionInfo?
179+ for await event in stream {
180+ switch event {
181+ case .chunk(let chunk):
182+ if firstToken == nil { firstToken = clock.now - began }
183+ text += chunk
184+ case .info(let completion):
185+ info = completion
186+ default:
187+ break
188+ }
189+ }
190+ eval(cache.flatMap(\.state))
191+ return Measure(
192+ promptTokens: prompt.count, reusedTokens: start,
193+ prefillSeconds: info?.promptTime ?? 0,
194+ firstTokenSeconds: firstToken.map(Self.seconds) ?? 0,
195+ generatedTokens: info?.generationTokenCount ?? 0,
196+ answer: Self.visibleAnswer(text))
197+ }
198+
199+ // MARK: - Helpers
200+
201+ private func newCache() throws -> [KVCache] {
202+ let cache = try context.model.newCache(parameters: parameters)
203+ guard let bits = settings.kvBits else { return cache }
204+ return cache.map { entry in
205+ type(of: entry) == KVCacheSimple.self
206+ ? QuantizedKVCache(groupSize: 64, bits: bits) : entry
207+ }
208+ }
209+
210+ private func offset(of cache: [KVCache]) -> Int {
211+ cache.map(\.offset).max() ?? 0
212+ }
213+
214+ private func render(_ messages: [Chat.Message]) async throws -> [Int] {
215+ let input = try await context.processor.prepare(
216+ input: UserInput(chat: messages, additionalContext: ["enable_thinking": settings.think]))
217+ return input.text.tokens.asArray(Int.self)
218+ }
219+
220+ /// What a client shows and sends back: the answer without its reasoning.
221+ static func visibleAnswer(_ text: String) -> String {
222+ guard let end = text.range(of: "</think>") else {
223+ return text.trimmingCharacters(in: .whitespacesAndNewlines)
224+ }
225+ return text[end.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines)
226+ }
227+
228+ static func seconds(_ duration: Duration) -> Double {
229+ Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18
230+ }
231+
232+ // MARK: - The conversation
233+
234+ /// A system prompt, then pairs of notes and acknowledgements until the history is long enough.
235+ private func buildHistory() async throws -> [Chat.Message] {
236+ var messages: [Chat.Message] = [.system(Self.system)]
237+ var part = 1
238+ while try await render(messages).count < settings.historyTokens {
239+ messages.append(.user("Here are my notes for part \(part). \(Self.notes(part))"))
240+ messages.append(
241+ .assistant("Noted part \(part). \(Self.sentence(part * 7)) \(Self.sentence(part * 11))"))
242+ part += 1
243+ }
244+ return messages
245+ }
246+
247+ static let system = """
248+ You are the assistant of a small engineering team. You keep track of the notes they \
249+ send you, part by part, and answer questions about them. Answer briefly, in one or two \
250+ sentences, and quote the part number your answer comes from.
251+ """
252+
253+ static let questions = [
254+ "In one sentence, what is part 2 about?",
255+ "Which part mentions the cache budget first?",
256+ "Summarise part 5 in ten words.",
257+ "Which team is mentioned most often?",
258+ "What did part 1 say about deployments?",
259+ "List two risks mentioned in the notes.",
260+ ]
261+
262+ static func notes(_ part: Int) -> String {
263+ (0 ..< 6).map { sentence(part * 6 + $0) }.joined(separator: " ")
264+ }
265+
266+ static func sentence(_ seed: Int) -> String {
267+ let teams = ["The platform team", "The data team", "The mobile team", "The search team"]
268+ let verbs = ["reviewed", "postponed", "measured", "rewrote", "documented", "tested"]
269+ let things = [
270+ "the deployment pipeline", "the cache budget", "the login flow", "the billing export",
271+ "the nightly backups", "the API rate limits", "the onboarding guide",
272+ ]
273+ let endings = [
274+ "and found two regressions", "before the release", "with the new metrics",
275+ "after the incident review", "to reduce latency", "for the audit",
276+ ]
277+ return "\(teams[seed % teams.count]) \(verbs[(seed / 4) % verbs.count]) "
278+ + "\(things[(seed / 3) % things.count]) \(endings[(seed / 5) % endings.count])."
279+ }
280+}
281+
282+/// The results, as Markdown.
283+struct Report {
284+ let model: String
285+ let settings: Settings
286+ let historyTokens: Int
287+ let cold: Run
288+ let warm: Run
289+
290+ var text: String {
291+ var lines = [
292+ "## KV-cache reuse — \(model)",
293+ "",
294+ "History \(historyTokens) tokens, \(settings.turns) turns, max \(settings.maxTokens) "
295+ + "tokens per answer, thinking \(settings.think ? "on" : "off"), KV cache "
296+ + (settings.kvBits.map { "\($0)-bit" } ?? "not quantized") + ", prefill step "
297+ + (settings.prefillStep.map(String.init) ?? "default") + ".",
298+ "",
299+ "| Turn | Prompt tokens | Reused (warm) | Prefill cold (s) | Prefill warm (s) "
300+ + "| First token cold (s) | First token warm (s) | Same answer |",
301+ "| --- | --- | --- | --- | --- | --- | --- | --- |",
302+ ]
303+ for (index, (coldTurn, warmTurn)) in zip(cold.measures, warm.measures).enumerated() {
304+ let same = coldTurn.answer == warmTurn.answer ? "yes" : "**no**"
305+ lines.append(
306+ "| \(index + 1) | \(coldTurn.promptTokens) | \(warmTurn.reusedTokens) "
307+ + "| \(format(coldTurn.prefillSeconds)) | \(format(warmTurn.prefillSeconds)) "
308+ + "| \(format(coldTurn.firstTokenSeconds)) "
309+ + "| \(format(warmTurn.firstTokenSeconds)) | \(same) |")
310+ }
311+ // The first warm request has nothing to reuse; the gain is on the following ones.
312+ let coldNext = cold.measures.dropFirst().map(\.firstTokenSeconds).reduce(0, +)
313+ let warmNext = warm.measures.dropFirst().map(\.firstTokenSeconds).reduce(0, +)
314+ let same = zip(cold.measures, warm.measures).filter { $0.answer == $1.answer }.count
315+ lines += [
316+ "",
317+ "- Time to first token, turns 2 and later: cold \(format(coldNext)) s, "
318+ + "warm \(format(warmNext)) s"
319+ + (warmNext > 0 ? String(format: " (%.1f× faster)", coldNext / warmNext) : "")
320+ + ".",
321+ "- Same answers: \(same)/\(warm.measures.count).",
322+ "- KV cache after the last turn: \(warm.cachedTokens) tokens, "
323+ + "\(kib(warm.usedBytes)) used (\(perToken(warm.usedBytes, warm.cachedTokens)) "
324+ + "per token), \(kib(warm.allocatedBytes)) allocated.",
325+ ]
326+ for (index, (coldTurn, warmTurn)) in zip(cold.measures, warm.measures).enumerated() {
327+ lines.append("- Answer \(index + 1): \(warmTurn.answer.prefix(160))")
328+ if coldTurn.answer != warmTurn.answer {
329+ lines.append(" - cold: \(coldTurn.answer.prefix(160))")
330+ }
331+ }
332+ return lines.joined(separator: "\n")
333+ }
334+
335+ private func format(_ value: Double) -> String { String(format: "%.3f", value) }
336+
337+ private func kib(_ bytes: Int) -> String {
338+ String(format: "%.1f MiB", Double(bytes) / 1_048_576)
339+ }
340+
341+ private func perToken(_ bytes: Int, _ tokens: Int) -> String {
342+ tokens > 0 ? String(format: "%.1f KiB", Double(bytes) / Double(tokens) / 1024) : "—"
343+ }
344+}
345+
346+/// Status messages go to stderr so stdout carries only the report.
347+func log(_ message: String) {
348+ FileHandle.standardError.write(Data((message + "\n").utf8))
349+}
new file mode 100644
@@ -0,0 +1,349 @@
1+// Sample 02 — measure KV-cache prefix reuse between stateless chat requests (spike #47).
2+//
3+// An OpenAI client resends the whole conversation with every request. This program plays the
4+// same conversation twice, the way such a client would:
5+//
6+// - cold: every request starts from an empty KV cache and prefills the whole prompt (what
7+// razorbill does today);
8+// - warm: one KV cache is kept between requests; each request rewinds it to the longest token
9+// prefix it shares with the previous prompt and prefills only the rest.
10+//
11+// Generation is greedy (temperature 0), so both runs should give the same answers; the report
12+// compares them, which checks that the reused cache is correct, not just fast.
13+
14+import ArgumentParser
15+import Foundation
16+import HuggingFace
17+import MLX
18+import MLXHuggingFace
19+import MLXLLM
20+import MLXLMCommon
21+import Tokenizers
22+
23+@main
24+struct KVCacheReuse: AsyncParsableCommand {
25+ static let configuration = CommandConfiguration(
26+ commandName: "kv-cache-reuse",
27+ abstract: "Compare prefill time with and without KV-cache prefix reuse."
28+ )
29+
30+ @Option(name: .shortAndLong, help: "Hugging Face model id (an MLX model).")
31+ var model = "mlx-community/Qwen3-4B-4bit"
32+
33+ @Option(help: "Approximate size of the conversation history, in tokens.")
34+ var historyTokens = 4000
35+
36+ @Option(help: "New turns sent after the history, each as a stateless request.")
37+ var turns = 4
38+
39+ @Option(help: "Maximum number of generated tokens per answer.")
40+ var maxTokens = 64
41+
42+ @Option(help: "Quantize the KV cache to this many bits (4 or 8). Default: not quantized.")
43+ var kvBits: Int?
44+
45+ @Option(help: "Prompt tokens prefilled per step. Default: mlx-swift-lm's (512).")
46+ var prefillStep: Int?
47+
48+ @Flag(help: "Let reasoning models (Qwen3...) think; the client sends answers back without it.")
49+ var think = false
50+
51+ func run() async throws {
52+ let settings = Settings(
53+ historyTokens: historyTokens, turns: turns, maxTokens: maxTokens, kvBits: kvBits,
54+ prefillStep: prefillStep, think: think)
55+ log("Loading \(model)...")
56+ let container = try await #huggingFaceLoadModelContainer(
57+ configuration: LLMRegistry.shared.configuration(id: model),
58+ progressHandler: { _ in })
59+ let modelName = model
60+ let report = try await container.perform { context in
61+ try await Benchmark(context: context, settings: settings).run(model: modelName)
62+ }
63+ print(report)
64+ }
65+}
66+
67+struct Settings: Sendable {
68+ let historyTokens: Int
69+ let turns: Int
70+ let maxTokens: Int
71+ let kvBits: Int?
72+ let prefillStep: Int?
73+ let think: Bool
74+}
75+
76+/// What one request cost.
77+struct Measure {
78+ let promptTokens: Int
79+ let reusedTokens: Int
80+ let prefillSeconds: Double
81+ let firstTokenSeconds: Double
82+ let generatedTokens: Int
83+ let answer: String
84+}
85+
86+/// One run of the conversation, cold or warm.
87+struct Run {
88+ var measures: [Measure] = []
89+ var usedBytes = 0
90+ var allocatedBytes = 0
91+ var cachedTokens = 0
92+}
93+
94+final class Benchmark {
95+ private let context: ModelContext
96+ private let settings: Settings
97+ private let parameters: GenerateParameters
98+
99+ init(context: ModelContext, settings: Settings) {
100+ self.context = context
101+ self.settings = settings
102+ var parameters = GenerateParameters(maxTokens: settings.maxTokens, temperature: 0)
103+ if let step = settings.prefillStep { parameters.prefill = .init(stepSize: step) }
104+ self.parameters = parameters
105+ }
106+
107+ func run(model: String) async throws -> String {
108+ let history = try await buildHistory()
109+ let historySize = try await render(history).count
110+ log("History: \(historySize) tokens. Cold run...")
111+ let cold = try await play(history, reuse: false)
112+ log("Warm run...")
113+ let warm = try await play(history, reuse: true)
114+ return Report(
115+ model: model, settings: settings, historyTokens: historySize, cold: cold, warm: warm
116+ ).text
117+ }
118+
119+ // MARK: - Playing the conversation
120+
121+ private func play(_ history: [Chat.Message], reuse: Bool) async throws -> Run {
122+ var messages = history
123+ var cache = try newCache()
124+ var previousPrompt: [Int] = []
125+ var run = Run()
126+ for index in 0 ..< settings.turns {
127+ messages.append(.user(Self.questions[index % Self.questions.count]))
128+ let prompt = try await render(messages)
129+ var start = 0
130+ if reuse && !previousPrompt.isEmpty {
131+ start = rewind(cache, to: prompt, previousPrompt: previousPrompt)
132+ if start == 0 { cache = try newCache() }
133+ } else {
134+ cache = try newCache()
135+ }
136+ let measure = try await generate(prompt, from: start, cache: cache)
137+ run.measures.append(measure)
138+ messages.append(.assistant(measure.answer))
139+ previousPrompt = prompt
140+ }
141+ let used = cache.flatMap(\.state).reduce(0) { $0 + $1.nbytes }
142+ let allocated = cache.compactMap { $0 as? BaseKVCache }
143+ .flatMap { $0.innerState() }.reduce(0) { $0 + $1.nbytes }
144+ run.usedBytes = used
145+ run.allocatedBytes = allocated
146+ run.cachedTokens = offset(of: cache)
147+ return run
148+ }
149+
150+ /// Rewinds `cache` to the longest prefix `prompt` shares with the previous prompt and returns
151+ /// where prefill must start, or 0 when the cache cannot be reused.
152+ private func rewind(_ cache: [KVCache], to prompt: [Int], previousPrompt: [Int]) -> Int {
153+ // At least one token must be fed to get the next token's logits.
154+ let common = min(
155+ zip(prompt, previousPrompt).prefix { $0 == $1 }.count, prompt.count - 1)
156+ // The cache also holds the previous answer, which the new prompt renders its own way.
157+ let extra = offset(of: cache) - common
158+ guard common > 0, extra >= 0 else { return 0 }
159+ if extra == 0 { return common }
160+ guard canTrimPromptCache(cache), trimPromptCache(cache, numTokens: extra) == extra
161+ else {
162+ log(" cache cannot be trimmed: rebuilding")
163+ return 0
164+ }
165+ return common
166+ }
167+
168+ private func generate(
169+ _ prompt: [Int], from start: Int, cache: [KVCache]
170+ ) async throws -> Measure {
171+ let input = LMInput(tokens: MLXArray(Array(prompt[start...])))
172+ let clock = ContinuousClock()
173+ let began = clock.now
174+ let stream = try MLXLMCommon.generate(
175+ input: input, cache: cache, parameters: parameters, context: context)
176+ var text = ""
177+ var firstToken: Duration?
178+ var info: GenerateCompletionInfo?
179+ for await event in stream {
180+ switch event {
181+ case .chunk(let chunk):
182+ if firstToken == nil { firstToken = clock.now - began }
183+ text += chunk
184+ case .info(let completion):
185+ info = completion
186+ default:
187+ break
188+ }
189+ }
190+ eval(cache.flatMap(\.state))
191+ return Measure(
192+ promptTokens: prompt.count, reusedTokens: start,
193+ prefillSeconds: info?.promptTime ?? 0,
194+ firstTokenSeconds: firstToken.map(Self.seconds) ?? 0,
195+ generatedTokens: info?.generationTokenCount ?? 0,
196+ answer: Self.visibleAnswer(text))
197+ }
198+
199+ // MARK: - Helpers
200+
201+ private func newCache() throws -> [KVCache] {
202+ let cache = try context.model.newCache(parameters: parameters)
203+ guard let bits = settings.kvBits else { return cache }
204+ return cache.map { entry in
205+ type(of: entry) == KVCacheSimple.self
206+ ? QuantizedKVCache(groupSize: 64, bits: bits) : entry
207+ }
208+ }
209+
210+ private func offset(of cache: [KVCache]) -> Int {
211+ cache.map(\.offset).max() ?? 0
212+ }
213+
214+ private func render(_ messages: [Chat.Message]) async throws -> [Int] {
215+ let input = try await context.processor.prepare(
216+ input: UserInput(chat: messages, additionalContext: ["enable_thinking": settings.think]))
217+ return input.text.tokens.asArray(Int.self)
218+ }
219+
220+ /// What a client shows and sends back: the answer without its reasoning.
221+ static func visibleAnswer(_ text: String) -> String {
222+ guard let end = text.range(of: "</think>") else {
223+ return text.trimmingCharacters(in: .whitespacesAndNewlines)
224+ }
225+ return text[end.upperBound...].trimmingCharacters(in: .whitespacesAndNewlines)
226+ }
227+
228+ static func seconds(_ duration: Duration) -> Double {
229+ Double(duration.components.seconds) + Double(duration.components.attoseconds) / 1e18
230+ }
231+
232+ // MARK: - The conversation
233+
234+ /// A system prompt, then pairs of notes and acknowledgements until the history is long enough.
235+ private func buildHistory() async throws -> [Chat.Message] {
236+ var messages: [Chat.Message] = [.system(Self.system)]
237+ var part = 1
238+ while try await render(messages).count < settings.historyTokens {
239+ messages.append(.user("Here are my notes for part \(part). \(Self.notes(part))"))
240+ messages.append(
241+ .assistant("Noted part \(part). \(Self.sentence(part * 7)) \(Self.sentence(part * 11))"))
242+ part += 1
243+ }
244+ return messages
245+ }
246+
247+ static let system = """
248+ You are the assistant of a small engineering team. You keep track of the notes they \
249+ send you, part by part, and answer questions about them. Answer briefly, in one or two \
250+ sentences, and quote the part number your answer comes from.
251+ """
252+
253+ static let questions = [
254+ "In one sentence, what is part 2 about?",
255+ "Which part mentions the cache budget first?",
256+ "Summarise part 5 in ten words.",
257+ "Which team is mentioned most often?",
258+ "What did part 1 say about deployments?",
259+ "List two risks mentioned in the notes.",
260+ ]
261+
262+ static func notes(_ part: Int) -> String {
263+ (0 ..< 6).map { sentence(part * 6 + $0) }.joined(separator: " ")
264+ }
265+
266+ static func sentence(_ seed: Int) -> String {
267+ let teams = ["The platform team", "The data team", "The mobile team", "The search team"]
268+ let verbs = ["reviewed", "postponed", "measured", "rewrote", "documented", "tested"]
269+ let things = [
270+ "the deployment pipeline", "the cache budget", "the login flow", "the billing export",
271+ "the nightly backups", "the API rate limits", "the onboarding guide",
272+ ]
273+ let endings = [
274+ "and found two regressions", "before the release", "with the new metrics",
275+ "after the incident review", "to reduce latency", "for the audit",
276+ ]
277+ return "\(teams[seed % teams.count]) \(verbs[(seed / 4) % verbs.count]) "
278+ + "\(things[(seed / 3) % things.count]) \(endings[(seed / 5) % endings.count])."
279+ }
280+}
281+
282+/// The results, as Markdown.
283+struct Report {
284+ let model: String
285+ let settings: Settings
286+ let historyTokens: Int
287+ let cold: Run
288+ let warm: Run
289+
290+ var text: String {
291+ var lines = [
292+ "## KV-cache reuse — \(model)",
293+ "",
294+ "History \(historyTokens) tokens, \(settings.turns) turns, max \(settings.maxTokens) "
295+ + "tokens per answer, thinking \(settings.think ? "on" : "off"), KV cache "
296+ + (settings.kvBits.map { "\($0)-bit" } ?? "not quantized") + ", prefill step "
297+ + (settings.prefillStep.map(String.init) ?? "default") + ".",
298+ "",
299+ "| Turn | Prompt tokens | Reused (warm) | Prefill cold (s) | Prefill warm (s) "
300+ + "| First token cold (s) | First token warm (s) | Same answer |",
301+ "| --- | --- | --- | --- | --- | --- | --- | --- |",
302+ ]
303+ for (index, (coldTurn, warmTurn)) in zip(cold.measures, warm.measures).enumerated() {
304+ let same = coldTurn.answer == warmTurn.answer ? "yes" : "**no**"
305+ lines.append(
306+ "| \(index + 1) | \(coldTurn.promptTokens) | \(warmTurn.reusedTokens) "
307+ + "| \(format(coldTurn.prefillSeconds)) | \(format(warmTurn.prefillSeconds)) "
308+ + "| \(format(coldTurn.firstTokenSeconds)) "
309+ + "| \(format(warmTurn.firstTokenSeconds)) | \(same) |")
310+ }
311+ // The first warm request has nothing to reuse; the gain is on the following ones.
312+ let coldNext = cold.measures.dropFirst().map(\.firstTokenSeconds).reduce(0, +)
313+ let warmNext = warm.measures.dropFirst().map(\.firstTokenSeconds).reduce(0, +)
314+ let same = zip(cold.measures, warm.measures).filter { $0.answer == $1.answer }.count
315+ lines += [
316+ "",
317+ "- Time to first token, turns 2 and later: cold \(format(coldNext)) s, "
318+ + "warm \(format(warmNext)) s"
319+ + (warmNext > 0 ? String(format: " (%.1f× faster)", coldNext / warmNext) : "")
320+ + ".",
321+ "- Same answers: \(same)/\(warm.measures.count).",
322+ "- KV cache after the last turn: \(warm.cachedTokens) tokens, "
323+ + "\(kib(warm.usedBytes)) used (\(perToken(warm.usedBytes, warm.cachedTokens)) "
324+ + "per token), \(kib(warm.allocatedBytes)) allocated.",
325+ ]
326+ for (index, (coldTurn, warmTurn)) in zip(cold.measures, warm.measures).enumerated() {
327+ lines.append("- Answer \(index + 1): \(warmTurn.answer.prefix(160))")
328+ if coldTurn.answer != warmTurn.answer {
329+ lines.append(" - cold: \(coldTurn.answer.prefix(160))")
330+ }
331+ }
332+ return lines.joined(separator: "\n")
333+ }
334+
335+ private func format(_ value: Double) -> String { String(format: "%.3f", value) }
336+
337+ private func kib(_ bytes: Int) -> String {
338+ String(format: "%.1f MiB", Double(bytes) / 1_048_576)
339+ }
340+
341+ private func perToken(_ bytes: Int, _ tokens: Int) -> String {
342+ tokens > 0 ? String(format: "%.1f KiB", Double(bytes) / Double(tokens) / 1024) : "—"
343+ }
344+}
345+
346+/// Status messages go to stderr so stdout carries only the report.
347+func log(_ message: String) {
348+ FileHandle.standardError.write(Data((message + "\n").utf8))
349+}