v0.2 step 13 — reuse the KV cache between stateless requests (#48)
MLXEngine keeps the KV cache of the last chat request on each model and cuts it back to the token prefix the next prompt shares, so a long conversation is no longer prefilled from scratch on every request (spike #47: 25-30 s down to under 1 s on a 4k-token history). Reused tokens are reported in usage.prompt_tokens_details.cached_tokens and as cached=N in the request log. Opens #49 for the sampling parameters that are still ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
a485576 parent: b5ef2e8 modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +8 -0 | @@ -108,3 +108,11 @@ the background, the host.sh client must not be killed by a timeout). Trap: with | ||
| 108 | 108 | answers differ between cold and warm; that is prefill chunking noise (control with --prefill-step), |
| 109 | 109 | not a bug. Open question: prefill only ~140–190 tok/s on Qwen3-4B-4bit — check the chip / compare |
| 110 | 110 | with `rzb serve` logs before quoting absolute numbers. |
| 111 | + | |
| 112 | +## Update — #48 done (prefix KV cache), #49 open | |
| 113 | +Prompt cache implemented and closed (see summary). Open in the v0.2 milestone: #47 (spike: tasks 3–5 | |
| 114 | +— hybrid/rotating trimming on real models, 4-bit/TurboQuant KV, persisted caches — and 6, the report | |
| 115 | +already exists), #49 (sampling params; scope to decide with the user). Suggested to the user: watch | |
| 116 | +`cached=N` in the `rzb serve` log on a long conversation, and run `scripts/compat.sh` on the Mac | |
| 117 | +(not run since #44). Trap seen: `host.sh test` started with `&` inside a Bash call survives, but use | |
| 118 | +run_in_background so a notification arrives. | |
| @@ -108,3 +108,11 @@ the background, the host.sh client must not be killed by a timeout). Trap: with | |||
| 108 | answers differ between cold and warm; that is prefill chunking noise (control with --prefill-step), | 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 | 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. | 110 | with `rzb serve` logs before quoting absolute numbers. |
| 111 | + | ||
| 112 | +## Update — #48 done (prefix KV cache), #49 open | ||
| 113 | +Prompt cache implemented and closed (see summary). Open in the v0.2 milestone: #47 (spike: tasks 3–5 | ||
| 114 | +— hybrid/rotating trimming on real models, 4-bit/TurboQuant KV, persisted caches — and 6, the report | ||
| 115 | +already exists), #49 (sampling params; scope to decide with the user). Suggested to the user: watch | ||
| 116 | +`cached=N` in the `rzb serve` log on a long conversation, and run `scripts/compat.sh` on the Mac | ||
| 117 | +(not run since #44). Trap seen: `host.sh test` started with `&` inside a Bash call survives, but use | ||
| 118 | +run_in_background so a notification arrives. | ||
modified
.memory/history.md +16 -0 | @@ -278,3 +278,19 @@ MLXEngine, cached_tokens in usage); tasks 1–2 closed, 3–6 open, ticket open. | ||
| 278 | 278 | Gate measures samples too: first FAIL (run #22, swiftlint identifier_name ×4 and opening_brace in the |
| 279 | 279 | sample), fixed by renaming, PASS (run #23); sample rebuilt on the Mac after the fix. Observed prefill speed |
| 280 | 280 | ~140–190 tok/s for a 4B model looked low; not investigated. |
| 281 | + | |
| 282 | +## 2026-11-25 — #48 prefix KV-cache reuse (implemented), #49 opened | |
| 283 | + | |
| 284 | +User: implement the cache now; also asked which sampling parameters are handled. Answer: temperature, | |
| 285 | +top_p, max_tokens/max_completion_tokens, stop, seed, presence/frequency_penalty; top_k, min_p, | |
| 286 | +repetition_penalty and logit_bias are silently ignored; model generation_config.json not read → | |
| 287 | +ticket #49 (v0.2 milestone, needs a scope decision). #48 created and closed: `PromptCache` + | |
| 288 | +`MLXSession` (own file, ChatSession dropped), `PromptPrefix` in Core, `cachedPromptTokens` in | |
| 289 | +GenerationStats, `usage.prompt_tokens_details.cached_tokens` when > 0, ` cached=N` in the log. | |
| 290 | +Rejected: keeping ChatSession (reuse only within one session), an LRU of caches (memory accounting, | |
| 291 | +gain only when clients alternate), counting the cache in the budget (deferred). Tests: Linux 168, | |
| 292 | +Mac 193 incl. a smoke test (second turn reuses the cache, same answer as a fresh engine); compat Linux | |
| 293 | +48/20. Gate: FAIL (large_tuple in RequestUsage, send complexity 19, then MLXEngine file_length) → | |
| 294 | +fixed by a struct, splitting send, moving MLXSession to its own file → PASS. Docs EN+FR: lifecycle | |
| 295 | +section "Reusing the previous prompt", http-api usage field, cli log suffix, architecture step 4. | |
| 296 | +Not done: real `rzb serve` measurement and Mac compat run (need the user). | |
| @@ -278,3 +278,19 @@ MLXEngine, cached_tokens in usage); tasks 1–2 closed, 3–6 open, ticket open. | |||
| 278 | Gate measures samples too: first FAIL (run #22, swiftlint identifier_name ×4 and opening_brace in the | 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 | 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. | 280 | ~140–190 tok/s for a 4B model looked low; not investigated. |
| 281 | + | ||
| 282 | +## 2026-11-25 — #48 prefix KV-cache reuse (implemented), #49 opened | ||
| 283 | + | ||
| 284 | +User: implement the cache now; also asked which sampling parameters are handled. Answer: temperature, | ||
| 285 | +top_p, max_tokens/max_completion_tokens, stop, seed, presence/frequency_penalty; top_k, min_p, | ||
| 286 | +repetition_penalty and logit_bias are silently ignored; model generation_config.json not read → | ||
| 287 | +ticket #49 (v0.2 milestone, needs a scope decision). #48 created and closed: `PromptCache` + | ||
| 288 | +`MLXSession` (own file, ChatSession dropped), `PromptPrefix` in Core, `cachedPromptTokens` in | ||
| 289 | +GenerationStats, `usage.prompt_tokens_details.cached_tokens` when > 0, ` cached=N` in the log. | ||
| 290 | +Rejected: keeping ChatSession (reuse only within one session), an LRU of caches (memory accounting, | ||
| 291 | +gain only when clients alternate), counting the cache in the budget (deferred). Tests: Linux 168, | ||
| 292 | +Mac 193 incl. a smoke test (second turn reuses the cache, same answer as a fresh engine); compat Linux | ||
| 293 | +48/20. Gate: FAIL (large_tuple in RequestUsage, send complexity 19, then MLXEngine file_length) → | ||
| 294 | +fixed by a struct, splitting send, moving MLXSession to its own file → PASS. Docs EN+FR: lifecycle | ||
| 295 | +section "Reusing the previous prompt", http-api usage field, cli log suffix, architecture step 4. | ||
| 296 | +Not done: real `rzb serve` measurement and Mac compat run (need the user). | ||
modified
.memory/summary.md +15 -9 | @@ -92,14 +92,19 @@ server (tutorial, 10 how-to, 4 reference incl. `http-api.md` / `api-http.md`, 5 | ||
| 92 | 92 | only successful calls in ```bash blocks. v0.2 tickets #31–#45 closed; #47 (KV-cache spike) still |
| 93 | 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). | |
| 95 | +KV cache (#47 spike, tasks 1–2 done, report = comment 1 on #47; implemented in #48): `MLXEngine` | |
| 96 | +keeps one KV cache per loaded model (`PromptCache`, `Sources/RazorbillMLX/PromptCache.swift`) with | |
| 97 | +the tokens of the last chat prompt. `MLXSession` (own file) no longer uses mlx-swift-lm's | |
| 98 | +`ChatSession`: it renders the whole history (`processor.prepare`), `PromptCache.checkout` waits for | |
| 99 | +the previous generation task, cuts the cache to the common prefix (`PromptPrefix` in Core, unit | |
| 100 | +tested on Linux) or starts fresh when it cannot be trimmed (hybrid / wrapped rotating caches) or | |
| 101 | +when the model carries per-call state, then `TokenIterator` + `generateTask`. Reused tokens go to | |
| 102 | +`GenerationStats.cachedPromptTokens` → `usage.prompt_tokens_details.cached_tokens` (only when > 0) | |
| 103 | +and ` cached=N` in the request log. Raw completions do not use it. Cache freed on unload/load. One | |
| 104 | +cache per model (no LRU), not counted in the memory budget. Measured with | |
| 105 | +`samples/02-kv-cache-reuse` (Qwen3-4B-4bit, 4k history): TTFT 25–30 s → <1 s per turn; greedy | |
| 106 | +answers identical thinking off; with thinking on they can differ, as they do between two prefill | |
| 107 | +step sizes (numeric). Qwen3-4B KV = 144 KiB/token (bf16), 76.5 KiB (8-bit). | |
| 103 | 108 | |
| 104 | 109 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 105 | 110 | |
| @@ -201,7 +206,8 @@ server instead. Linux = fake engine (protocol only, `real_model` tests skipped): | ||
| 201 | 206 | Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes; re-run after them: |
| 202 | 207 | 46 pass, 1 skip (docs curl, until #45), 80 s. compat.sh always rebuilds rzb (incremental) unless RZB_BIN is set. |
| 203 | 208 | Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. After #44: Linux 161, Mac 185, compat on |
| 204 | -Linux 34 pass / 21 skip (Mac compat not re-run after #44). | |
| 209 | +Linux 34 pass / 21 skip (Mac compat not re-run after #44). After #48 (prompt cache): Linux 168, Mac 193, | |
| 210 | +compat on Linux 48 pass / 20 skip (Mac compat not re-run since #44). | |
| 205 | 211 | |
| 206 | 212 | ## mlx-swift-lm API version trap |
| 207 | 213 | |
| @@ -92,14 +92,19 @@ 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) still | 92 | 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 | 95 | +KV cache (#47 spike, tasks 1–2 done, report = comment 1 on #47; implemented in #48): `MLXEngine` |
| 96 | -today (one new `ChatSession` per request). Measured with `samples/02-kv-cache-reuse` (Qwen3-4B-4bit, | 96 | +keeps one KV cache per loaded model (`PromptCache`, `Sources/RazorbillMLX/PromptCache.swift`) with |
| 97 | -4k-token history): rewinding a kept cache to the common token prefix cuts time to first token from | 97 | +the tokens of the last chat prompt. `MLXSession` (own file) no longer uses mlx-swift-lm's |
| 98 | -25–30 s to <1 s per turn; greedy answers identical with thinking off; with thinking on they differ, | 98 | +`ChatSession`: it renders the whole history (`processor.prepare`), `PromptCache.checkout` waits for |
| 99 | -but changing only the prefill step size already changes them (numeric, not a reuse bug). Qwen3-4B | 99 | +the previous generation task, cuts the cache to the common prefix (`PromptPrefix` in Core, unit |
| 100 | -KV = 144 KiB/token (bf16), 76.5 KiB (8-bit). mlx-swift-lm's own reuse policy is internal to | 100 | +tested on Linux) or starts fresh when it cannot be trimmed (hybrid / wrapped rotating caches) or |
| 101 | -`ChatSession`; hybrid (ArraysCache/Mamba) caches cannot be trimmed, rotating ones only before | 101 | +when the model carries per-call state, then `TokenIterator` + `generateTask`. Reused tokens go to |
| 102 | -wrapping. Implementation not decided yet (proposal in the report). | 102 | +`GenerationStats.cachedPromptTokens` → `usage.prompt_tokens_details.cached_tokens` (only when > 0) |
| 103 | +and ` cached=N` in the request log. Raw completions do not use it. Cache freed on unload/load. One | ||
| 104 | +cache per model (no LRU), not counted in the memory budget. Measured with | ||
| 105 | +`samples/02-kv-cache-reuse` (Qwen3-4B-4bit, 4k history): TTFT 25–30 s → <1 s per turn; greedy | ||
| 106 | +answers identical thinking off; with thinking on they can differ, as they do between two prefill | ||
| 107 | +step sizes (numeric). Qwen3-4B KV = 144 KiB/token (bf16), 76.5 KiB (8-bit). | ||
| 103 | 108 | ||
| 104 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 109 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 105 | 110 | ||
| @@ -201,7 +206,8 @@ server instead. Linux = fake engine (protocol only, `real_model` tests skipped): | |||
| 201 | Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes; re-run after them: | 206 | Mac (MLX, Qwen3-4B + bge-small + Llama-3.2-3B): 45/46 before the #43 fixes; re-run after them: |
| 202 | 46 pass, 1 skip (docs curl, until #45), 80 s. compat.sh always rebuilds rzb (incremental) unless RZB_BIN is set. | 207 | 46 pass, 1 skip (docs curl, until #45), 80 s. compat.sh always rebuilds rzb (incremental) unless RZB_BIN is set. |
| 203 | Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. After #44: Linux 161, Mac 185, compat on | 208 | Tests 2026-11-25 after #43 fixes: Linux 155, Mac 178. After #44: Linux 161, Mac 185, compat on |
| 204 | -Linux 34 pass / 21 skip (Mac compat not re-run after #44). | 209 | +Linux 34 pass / 21 skip (Mac compat not re-run after #44). After #48 (prompt cache): Linux 168, Mac 193, |
| 210 | +compat on Linux 48 pass / 20 skip (Mac compat not re-run since #44). | ||
| 205 | 211 | ||
| 206 | ## mlx-swift-lm API version trap | 212 | ## mlx-swift-lm API version trap |
| 207 | 213 | ||
modified
.quality/history.jsonl +3 -0 | @@ -21,3 +21,6 @@ | ||
| 21 | 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 | 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 | 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"} |
| 24 | +{"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)", "code smells: 1 (max 0)"], "commit": "b5ef2e8", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 231, "complex": 559, "cyclo": 603, "fields": 1178, "funcs": 571, "lcom": 113, "lines": 10467, "loc": 8320}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 24, "smells": 1, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:37:24Z"} | |
| 25 | +{"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "b5ef2e8", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 232, "complex": 544, "cyclo": 601, "fields": 1182, "funcs": 573, "lcom": 114, "lines": 10488, "loc": 8337}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 25, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:37:51Z"} | |
| 26 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b5ef2e8", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 232, "complex": 544, "cyclo": 602, "fields": 1189, "funcs": 573, "lcom": 115, "lines": 10494, "loc": 8343}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 26, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:38:24Z"} | |
| @@ -21,3 +21,6 @@ | |||
| 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"} | 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"} | 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"} |
| 24 | +{"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)", "code smells: 1 (max 0)"], "commit": "b5ef2e8", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 231, "complex": 559, "cyclo": 603, "fields": 1178, "funcs": 571, "lcom": 113, "lines": 10467, "loc": 8320}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 24, "smells": 1, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:37:24Z"} | ||
| 25 | +{"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "b5ef2e8", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 232, "complex": 544, "cyclo": 601, "fields": 1182, "funcs": 573, "lcom": 114, "lines": 10488, "loc": 8337}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 25, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:37:51Z"} | ||
| 26 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b5ef2e8", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 232, "complex": 544, "cyclo": 602, "fields": 1189, "funcs": 573, "lcom": 115, "lines": 10494, "loc": 8343}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 26, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T21:38:24Z"} | ||
added
.quality/report-20261125T213724Z.md +86 -0 | new file mode 100644 | ||
| @@ -0,0 +1,86 @@ | ||
| 1 | +# Quality report — 2026-11-25T21:37:24Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `b5ef2e8` 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**: #24 (previous: 2026-11-25T21:28:10Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- warning-level issues: 1 (max 0) | |
| 12 | +- code smells: 1 (max 0) | |
| 13 | + | |
| 14 | +## Lint issues (`qlty check`) | |
| 15 | + | |
| 16 | +| level | count | vs previous | | |
| 17 | +|---|---|---| | |
| 18 | +| warning | 1 | — | | |
| 19 | + | |
| 20 | +### Top rules | |
| 21 | + | |
| 22 | +| rule | count | | |
| 23 | +|---|---| | |
| 24 | +| swiftlint:large_tuple | 1 | | |
| 25 | + | |
| 26 | +### Most affected files | |
| 27 | + | |
| 28 | +| file | issues | | |
| 29 | +|---|---| | |
| 30 | +| Sources/RazorbillServer/ServerContext.swift | 1 | | |
| 31 | + | |
| 32 | +## Code smells (`qlty smells`) | |
| 33 | + | |
| 34 | +Total: **1** (vs previous: +1) | |
| 35 | + | |
| 36 | +| smell | file | line | detail | | |
| 37 | +|---|---|---|---| | |
| 38 | +| qlty:function-complexity | Sources/RazorbillMLX/MLXEngine.swift | 252 | Function with high complexity (count = 19): send | | |
| 39 | + | |
| 40 | +## Metrics (`qlty metrics`) | |
| 41 | + | |
| 42 | +| metric | total | vs previous | | |
| 43 | +|---|---|---| | |
| 44 | +| funcs | 571 | +13 | | |
| 45 | +| classes | 231 | +4 | | |
| 46 | +| fields | 1178 | +34 | | |
| 47 | +| cyclo | 603 | +13 | | |
| 48 | +| complex | 559 | +21 | | |
| 49 | +| lcom | 113 | +3 | | |
| 50 | +| lines | 10467 | +278 | | |
| 51 | +| loc | 8320 | +204 | | |
| 52 | + | |
| 53 | +### Most complex files | |
| 54 | + | |
| 55 | +| file | complex | cyclo | loc | | |
| 56 | +|---|---|---|---| | |
| 57 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | |
| 58 | +| Sources/RazorbillMLX/MLXEngine.swift | 45 | 43 | 324 | | |
| 59 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | |
| 60 | +| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | |
| 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 | 137 | | |
| 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 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | |
| 78 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| 79 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 80 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| 81 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | |
| 82 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | |
| 83 | +| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | |
| 84 | +| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | |
| 85 | +| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | |
| 86 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,86 @@ | |||
| 1 | +# Quality report — 2026-11-25T21:37:24Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `b5ef2e8` 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**: #24 (previous: 2026-11-25T21:28:10Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- warning-level issues: 1 (max 0) | ||
| 12 | +- code smells: 1 (max 0) | ||
| 13 | + | ||
| 14 | +## Lint issues (`qlty check`) | ||
| 15 | + | ||
| 16 | +| level | count | vs previous | | ||
| 17 | +|---|---|---| | ||
| 18 | +| warning | 1 | — | | ||
| 19 | + | ||
| 20 | +### Top rules | ||
| 21 | + | ||
| 22 | +| rule | count | | ||
| 23 | +|---|---| | ||
| 24 | +| swiftlint:large_tuple | 1 | | ||
| 25 | + | ||
| 26 | +### Most affected files | ||
| 27 | + | ||
| 28 | +| file | issues | | ||
| 29 | +|---|---| | ||
| 30 | +| Sources/RazorbillServer/ServerContext.swift | 1 | | ||
| 31 | + | ||
| 32 | +## Code smells (`qlty smells`) | ||
| 33 | + | ||
| 34 | +Total: **1** (vs previous: +1) | ||
| 35 | + | ||
| 36 | +| smell | file | line | detail | | ||
| 37 | +|---|---|---|---| | ||
| 38 | +| qlty:function-complexity | Sources/RazorbillMLX/MLXEngine.swift | 252 | Function with high complexity (count = 19): send | | ||
| 39 | + | ||
| 40 | +## Metrics (`qlty metrics`) | ||
| 41 | + | ||
| 42 | +| metric | total | vs previous | | ||
| 43 | +|---|---|---| | ||
| 44 | +| funcs | 571 | +13 | | ||
| 45 | +| classes | 231 | +4 | | ||
| 46 | +| fields | 1178 | +34 | | ||
| 47 | +| cyclo | 603 | +13 | | ||
| 48 | +| complex | 559 | +21 | | ||
| 49 | +| lcom | 113 | +3 | | ||
| 50 | +| lines | 10467 | +278 | | ||
| 51 | +| loc | 8320 | +204 | | ||
| 52 | + | ||
| 53 | +### Most complex files | ||
| 54 | + | ||
| 55 | +| file | complex | cyclo | loc | | ||
| 56 | +|---|---|---|---| | ||
| 57 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | ||
| 58 | +| Sources/RazorbillMLX/MLXEngine.swift | 45 | 43 | 324 | | ||
| 59 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | ||
| 60 | +| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | ||
| 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 | 137 | | ||
| 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 | +| 15 | 2026-11-25T13:26:02Z | 0 | 0 | 0 | 377 | PASS | | ||
| 78 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
| 79 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 80 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
| 81 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | ||
| 82 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | ||
| 83 | +| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | ||
| 84 | +| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | ||
| 85 | +| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | ||
| 86 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | ||
added
.quality/report-20261125T213751Z.md +83 -0 | new file mode 100644 | ||
| @@ -0,0 +1,83 @@ | ||
| 1 | +# Quality report — 2026-11-25T21:37:51Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `b5ef2e8` 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**: #25 (previous: 2026-11-25T21:37:24Z) | |
| 8 | + | |
| 9 | +## Gate violations | |
| 10 | + | |
| 11 | +- warning-level issues: 1 (max 0) | |
| 12 | + | |
| 13 | +## Lint issues (`qlty check`) | |
| 14 | + | |
| 15 | +| level | count | vs previous | | |
| 16 | +|---|---|---| | |
| 17 | +| warning | 1 | ±0 | | |
| 18 | + | |
| 19 | +### Top rules | |
| 20 | + | |
| 21 | +| rule | count | | |
| 22 | +|---|---| | |
| 23 | +| swiftlint:file_length | 1 | | |
| 24 | + | |
| 25 | +### Most affected files | |
| 26 | + | |
| 27 | +| file | issues | | |
| 28 | +|---|---| | |
| 29 | +| Sources/RazorbillMLX/MLXEngine.swift | 1 | | |
| 30 | + | |
| 31 | +## Code smells (`qlty smells`) | |
| 32 | + | |
| 33 | +Total: **0** (vs previous: -1) | |
| 34 | + | |
| 35 | +_none_ | |
| 36 | + | |
| 37 | +## Metrics (`qlty metrics`) | |
| 38 | + | |
| 39 | +| metric | total | vs previous | | |
| 40 | +|---|---|---| | |
| 41 | +| funcs | 573 | +2 | | |
| 42 | +| classes | 232 | +1 | | |
| 43 | +| fields | 1182 | +4 | | |
| 44 | +| cyclo | 601 | -2 | | |
| 45 | +| complex | 544 | -15 | | |
| 46 | +| lcom | 114 | +1 | | |
| 47 | +| lines | 10488 | +21 | | |
| 48 | +| loc | 8337 | +17 | | |
| 49 | + | |
| 50 | +### Most complex files | |
| 51 | + | |
| 52 | +| file | complex | cyclo | loc | | |
| 53 | +|---|---|---|---| | |
| 54 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | |
| 55 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | |
| 56 | +| Sources/RazorbillMLX/MLXEngine.swift | 30 | 41 | 335 | | |
| 57 | +| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | |
| 58 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 59 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | |
| 60 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 61 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | |
| 62 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | |
| 63 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 137 | | |
| 64 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 65 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | |
| 66 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 67 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 68 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 69 | + | |
| 70 | +## Trend | |
| 71 | + | |
| 72 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 73 | +|---|---|---|---|---|---|---| | |
| 74 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | |
| 75 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 76 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| 77 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | |
| 78 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | |
| 79 | +| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | |
| 80 | +| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | |
| 81 | +| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | |
| 82 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | |
| 83 | +| 25 | 2026-11-25T21:37:51Z | 0 | 1 | 0 | 544 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | +# Quality report — 2026-11-25T21:37:51Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `b5ef2e8` 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**: #25 (previous: 2026-11-25T21:37:24Z) | ||
| 8 | + | ||
| 9 | +## Gate violations | ||
| 10 | + | ||
| 11 | +- warning-level issues: 1 (max 0) | ||
| 12 | + | ||
| 13 | +## Lint issues (`qlty check`) | ||
| 14 | + | ||
| 15 | +| level | count | vs previous | | ||
| 16 | +|---|---|---| | ||
| 17 | +| warning | 1 | ±0 | | ||
| 18 | + | ||
| 19 | +### Top rules | ||
| 20 | + | ||
| 21 | +| rule | count | | ||
| 22 | +|---|---| | ||
| 23 | +| swiftlint:file_length | 1 | | ||
| 24 | + | ||
| 25 | +### Most affected files | ||
| 26 | + | ||
| 27 | +| file | issues | | ||
| 28 | +|---|---| | ||
| 29 | +| Sources/RazorbillMLX/MLXEngine.swift | 1 | | ||
| 30 | + | ||
| 31 | +## Code smells (`qlty smells`) | ||
| 32 | + | ||
| 33 | +Total: **0** (vs previous: -1) | ||
| 34 | + | ||
| 35 | +_none_ | ||
| 36 | + | ||
| 37 | +## Metrics (`qlty metrics`) | ||
| 38 | + | ||
| 39 | +| metric | total | vs previous | | ||
| 40 | +|---|---|---| | ||
| 41 | +| funcs | 573 | +2 | | ||
| 42 | +| classes | 232 | +1 | | ||
| 43 | +| fields | 1182 | +4 | | ||
| 44 | +| cyclo | 601 | -2 | | ||
| 45 | +| complex | 544 | -15 | | ||
| 46 | +| lcom | 114 | +1 | | ||
| 47 | +| lines | 10488 | +21 | | ||
| 48 | +| loc | 8337 | +17 | | ||
| 49 | + | ||
| 50 | +### Most complex files | ||
| 51 | + | ||
| 52 | +| file | complex | cyclo | loc | | ||
| 53 | +|---|---|---|---| | ||
| 54 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | ||
| 55 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | ||
| 56 | +| Sources/RazorbillMLX/MLXEngine.swift | 30 | 41 | 335 | | ||
| 57 | +| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | ||
| 58 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 59 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | ||
| 60 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 61 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | ||
| 62 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | ||
| 63 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 137 | | ||
| 64 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 65 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | ||
| 66 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 67 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 68 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 69 | + | ||
| 70 | +## Trend | ||
| 71 | + | ||
| 72 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 73 | +|---|---|---|---|---|---|---| | ||
| 74 | +| 16 | 2026-11-25T13:38:25Z | 0 | 0 | 0 | 408 | PASS | | ||
| 75 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 76 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
| 77 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | ||
| 78 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | ||
| 79 | +| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | ||
| 80 | +| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | ||
| 81 | +| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | ||
| 82 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | ||
| 83 | +| 25 | 2026-11-25T21:37:51Z | 0 | 1 | 0 | 544 | FAIL | | ||
added
.quality/report-20261125T213824Z.md +75 -0 | new file mode 100644 | ||
| @@ -0,0 +1,75 @@ | ||
| 1 | +# Quality report — 2026-11-25T21:38:24Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `b5ef2e8` 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**: #26 (previous: 2026-11-25T21:37:51Z) | |
| 8 | + | |
| 9 | +## Lint issues (`qlty check`) | |
| 10 | + | |
| 11 | +| level | count | vs previous | | |
| 12 | +|---|---|---| | |
| 13 | +| warning | 0 | -1 | | |
| 14 | + | |
| 15 | +### Top rules | |
| 16 | + | |
| 17 | +_none_ | |
| 18 | + | |
| 19 | +### Most affected files | |
| 20 | + | |
| 21 | +_none_ | |
| 22 | + | |
| 23 | +## Code smells (`qlty smells`) | |
| 24 | + | |
| 25 | +Total: **0** (vs previous: ±0) | |
| 26 | + | |
| 27 | +_none_ | |
| 28 | + | |
| 29 | +## Metrics (`qlty metrics`) | |
| 30 | + | |
| 31 | +| metric | total | vs previous | | |
| 32 | +|---|---|---| | |
| 33 | +| funcs | 573 | ±0 | | |
| 34 | +| classes | 232 | ±0 | | |
| 35 | +| fields | 1189 | +7 | | |
| 36 | +| cyclo | 602 | +1 | | |
| 37 | +| complex | 544 | ±0 | | |
| 38 | +| lcom | 115 | +1 | | |
| 39 | +| lines | 10494 | +6 | | |
| 40 | +| loc | 8343 | +6 | | |
| 41 | + | |
| 42 | +### Most complex files | |
| 43 | + | |
| 44 | +| file | complex | cyclo | loc | | |
| 45 | +|---|---|---|---| | |
| 46 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | |
| 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | |
| 48 | +| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | |
| 49 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 242 | | |
| 50 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 51 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | |
| 52 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | |
| 53 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | |
| 54 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | |
| 55 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 137 | | |
| 56 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 57 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | |
| 58 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 59 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | |
| 60 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | |
| 61 | + | |
| 62 | +## Trend | |
| 63 | + | |
| 64 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 65 | +|---|---|---|---|---|---|---| | |
| 66 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | |
| 67 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | |
| 68 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | |
| 69 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | |
| 70 | +| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | |
| 71 | +| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | |
| 72 | +| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | |
| 73 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | |
| 74 | +| 25 | 2026-11-25T21:37:51Z | 0 | 1 | 0 | 544 | FAIL | | |
| 75 | +| 26 | 2026-11-25T21:38:24Z | 0 | 0 | 0 | 544 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,75 @@ | |||
| 1 | +# Quality report — 2026-11-25T21:38:24Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `b5ef2e8` 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**: #26 (previous: 2026-11-25T21:37:51Z) | ||
| 8 | + | ||
| 9 | +## Lint issues (`qlty check`) | ||
| 10 | + | ||
| 11 | +| level | count | vs previous | | ||
| 12 | +|---|---|---| | ||
| 13 | +| warning | 0 | -1 | | ||
| 14 | + | ||
| 15 | +### Top rules | ||
| 16 | + | ||
| 17 | +_none_ | ||
| 18 | + | ||
| 19 | +### Most affected files | ||
| 20 | + | ||
| 21 | +_none_ | ||
| 22 | + | ||
| 23 | +## Code smells (`qlty smells`) | ||
| 24 | + | ||
| 25 | +Total: **0** (vs previous: ±0) | ||
| 26 | + | ||
| 27 | +_none_ | ||
| 28 | + | ||
| 29 | +## Metrics (`qlty metrics`) | ||
| 30 | + | ||
| 31 | +| metric | total | vs previous | | ||
| 32 | +|---|---|---| | ||
| 33 | +| funcs | 573 | ±0 | | ||
| 34 | +| classes | 232 | ±0 | | ||
| 35 | +| fields | 1189 | +7 | | ||
| 36 | +| cyclo | 602 | +1 | | ||
| 37 | +| complex | 544 | ±0 | | ||
| 38 | +| lcom | 115 | +1 | | ||
| 39 | +| lines | 10494 | +6 | | ||
| 40 | +| loc | 8343 | +6 | | ||
| 41 | + | ||
| 42 | +### Most complex files | ||
| 43 | + | ||
| 44 | +| file | complex | cyclo | loc | | ||
| 45 | +|---|---|---|---| | ||
| 46 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | ||
| 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | ||
| 48 | +| samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | ||
| 49 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 242 | | ||
| 50 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 51 | +| Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | ||
| 52 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | ||
| 53 | +| Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | ||
| 54 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | ||
| 55 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 137 | | ||
| 56 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 57 | +| Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | ||
| 58 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 59 | +| Sources/RazorbillServer/EmbeddingsRoute.swift | 13 | 13 | 143 | | ||
| 60 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 12 | 13 | 51 | | ||
| 61 | + | ||
| 62 | +## Trend | ||
| 63 | + | ||
| 64 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 65 | +|---|---|---|---|---|---|---| | ||
| 66 | +| 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | | ||
| 67 | +| 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | ||
| 68 | +| 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | ||
| 69 | +| 20 | 2026-11-25T18:44:58Z | 0 | 0 | 0 | 512 | PASS | | ||
| 70 | +| 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | ||
| 71 | +| 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | ||
| 72 | +| 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | ||
| 73 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | ||
| 74 | +| 25 | 2026-11-25T21:37:51Z | 0 | 1 | 0 | 544 | FAIL | | ||
| 75 | +| 26 | 2026-11-25T21:38:24Z | 0 | 0 | 0 | 544 | PASS | | ||
modified
.quality/report-latest.md +18 -19 | @@ -1,16 +1,15 @@ | ||
| 1 | -# Quality report — 2026-11-25T21:28:10Z | |
| 1 | +# Quality report — 2026-11-25T21:38:24Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `f2a20f5` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `b5ef2e8` on `feature/v0.2-openai-server` | |
| 5 | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #23 (previous: 2026-11-25T21:27:49Z) | |
| 7 | +- **Run**: #26 (previous: 2026-11-25T21:37:51Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| 11 | 11 | | level | count | vs previous | |
| 12 | 12 | |---|---|---| |
| 13 | -| error | 0 | -4 | | |
| 14 | 13 | | warning | 0 | -1 | |
| 15 | 14 | |
| 16 | 15 | ### Top rules |
| @@ -31,29 +30,29 @@ _none_ | ||
| 31 | 30 | |
| 32 | 31 | | metric | total | vs previous | |
| 33 | 32 | |---|---|---| |
| 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 | | |
| 33 | +| funcs | 573 | ±0 | | |
| 34 | +| classes | 232 | ±0 | | |
| 35 | +| fields | 1189 | +7 | | |
| 36 | +| cyclo | 602 | +1 | | |
| 37 | +| complex | 544 | ±0 | | |
| 38 | +| lcom | 115 | +1 | | |
| 39 | +| lines | 10494 | +6 | | |
| 40 | +| loc | 8343 | +6 | | |
| 42 | 41 | |
| 43 | 42 | ### Most complex files |
| 44 | 43 | |
| 45 | 44 | | file | complex | cyclo | loc | |
| 46 | 45 | |---|---|---|---| |
| 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 | | |
| 46 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | | |
| 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | | |
| 50 | 48 | | samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | |
| 49 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 242 | | |
| 51 | 50 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 52 | 51 | | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | |
| 53 | 52 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | |
| 54 | 53 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | |
| 55 | 54 | | Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | |
| 56 | -| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 | | |
| 55 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 137 | | |
| 57 | 56 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 58 | 57 | | Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | |
| 59 | 58 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| @@ -64,9 +63,6 @@ _none_ | ||
| 64 | 63 | |
| 65 | 64 | | run | timestamp | error | warning | smells | complex | gate | |
| 66 | 65 | |---|---|---|---|---|---|---| |
| 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 | 66 | | 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | |
| 71 | 67 | | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | |
| 72 | 68 | | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | |
| @@ -74,3 +70,6 @@ _none_ | ||
| 74 | 70 | | 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | |
| 75 | 71 | | 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | |
| 76 | 72 | | 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | |
| 73 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | |
| 74 | +| 25 | 2026-11-25T21:37:51Z | 0 | 1 | 0 | 544 | FAIL | | |
| 75 | +| 26 | 2026-11-25T21:38:24Z | 0 | 0 | 0 | 544 | PASS | | |
| @@ -1,16 +1,15 @@ | |||
| 1 | -# Quality report — 2026-11-25T21:28:10Z | 1 | +# Quality report — 2026-11-25T21:38:24Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `f2a20f5` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `b5ef2e8` 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**: #23 (previous: 2026-11-25T21:27:49Z) | 7 | +- **Run**: #26 (previous: 2026-11-25T21:37:51Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| 11 | | level | count | vs previous | | 11 | | level | count | vs previous | |
| 12 | |---|---|---| | 12 | |---|---|---| |
| 13 | -| error | 0 | -4 | | ||
| 14 | | warning | 0 | -1 | | 13 | | warning | 0 | -1 | |
| 15 | 14 | ||
| 16 | ### Top rules | 15 | ### Top rules |
| @@ -31,29 +30,29 @@ _none_ | |||
| 31 | 30 | ||
| 32 | | metric | total | vs previous | | 31 | | metric | total | vs previous | |
| 33 | |---|---|---| | 32 | |---|---|---| |
| 34 | -| funcs | 558 | ±0 | | 33 | +| funcs | 573 | ±0 | |
| 35 | -| classes | 227 | ±0 | | 34 | +| classes | 232 | ±0 | |
| 36 | -| fields | 1144 | ±0 | | 35 | +| fields | 1189 | +7 | |
| 37 | -| cyclo | 590 | ±0 | | 36 | +| cyclo | 602 | +1 | |
| 38 | -| complex | 538 | ±0 | | 37 | +| complex | 544 | ±0 | |
| 39 | -| lcom | 110 | ±0 | | 38 | +| lcom | 115 | +1 | |
| 40 | -| lines | 10189 | +3 | | 39 | +| lines | 10494 | +6 | |
| 41 | -| loc | 8116 | +3 | | 40 | +| loc | 8343 | +6 | |
| 42 | 41 | ||
| 43 | ### Most complex files | 42 | ### Most complex files |
| 44 | 43 | ||
| 45 | | file | complex | cyclo | loc | | 44 | | file | complex | cyclo | loc | |
| 46 | |---|---|---|---| | 45 | |---|---|---|---| |
| 47 | -| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 239 | | 46 | +| Sources/RazorbillServer/CompletionsRoute.swift | 47 | 20 | 238 | |
| 48 | -| Sources/RazorbillMLX/MLXEngine.swift | 34 | 40 | 264 | | 47 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 31 | 20 | 125 | |
| 49 | -| Sources/RazorbillServer/Chat/CompletionStream.swift | 29 | 18 | 114 | | ||
| 50 | | samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | | 48 | | samples/02-kv-cache-reuse/Sources/KVCacheReuse/KVCacheReuse.swift | 26 | 20 | 285 | |
| 49 | +| Sources/RazorbillMLX/MLXEngine.swift | 23 | 35 | 242 | | ||
| 51 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 50 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 52 | | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | | 51 | | Sources/RazorbillCore/Config/ConfigValue+JSON.swift | 20 | 25 | 71 | |
| 53 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | | 52 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 215 | |
| 54 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | | 53 | | Sources/RazorbillServer/Chat/ToolsAndFormats.swift | 18 | 30 | 170 | |
| 55 | | Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | | 54 | | Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 17 | 24 | 271 | |
| 56 | -| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 138 | | 55 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 137 | |
| 57 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | 56 | | Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | |
| 58 | | Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | | 57 | | Sources/RazorbillCore/Config/OrderedJSONReader.swift | 15 | 24 | 140 | |
| 59 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 58 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| @@ -64,9 +63,6 @@ _none_ | |||
| 64 | 63 | ||
| 65 | | run | timestamp | error | warning | smells | complex | gate | | 64 | | run | timestamp | error | warning | smells | complex | gate | |
| 66 | |---|---|---|---|---|---|---| | 65 | |---|---|---|---|---|---|---| |
| 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 | | 66 | | 17 | 2026-11-25T17:55:15Z | 0 | 3 | 0 | 449 | FAIL | |
| 71 | | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | | 67 | | 18 | 2026-11-25T17:55:49Z | 0 | 0 | 0 | 449 | PASS | |
| 72 | | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | | 68 | | 19 | 2026-11-25T18:44:20Z | 0 | 0 | 2 | 513 | FAIL | |
| @@ -74,3 +70,6 @@ _none_ | |||
| 74 | | 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | | 70 | | 21 | 2026-11-25T19:12:45Z | 0 | 0 | 0 | 512 | PASS | |
| 75 | | 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | | 71 | | 22 | 2026-11-25T21:27:49Z | 4 | 1 | 0 | 538 | FAIL | |
| 76 | | 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | | 72 | | 23 | 2026-11-25T21:28:10Z | 0 | 0 | 0 | 538 | PASS | |
| 73 | +| 24 | 2026-11-25T21:37:24Z | 0 | 1 | 1 | 559 | FAIL | | ||
| 74 | +| 25 | 2026-11-25T21:37:51Z | 0 | 1 | 0 | 544 | FAIL | | ||
| 75 | +| 26 | 2026-11-25T21:38:24Z | 0 | 0 | 0 | 544 | PASS | | ||
added
.tickets/issues/0048-prefix-kv-cache-reuse-between-stateless-requests.yaml +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 48 | |
| 3 | +title: "Prefix KV-cache reuse between stateless requests" | |
| 4 | +state: closed | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-25T21:45:00.000Z | |
| 9 | +updatedAt: 2026-11-25T23:30:00.000Z | |
| 10 | +labels: | |
| 11 | + - "kind::feature" | |
| 12 | + - "area::engine" | |
| 13 | + - "mac-only" | |
| 14 | + - "priority::high" | |
| 15 | +milestone: "v0.2 — OpenAI-compatible MLX server" | |
| 16 | +epic: "Inference engine" | |
| 17 | +related: | |
| 18 | + - 47 | |
| 19 | + - 34 | |
| 20 | + - 35 | |
| 21 | + - 26 | |
| 22 | +body: | | |
| 23 | + Decided after spike #47 (report: comment 1 on #47). OpenAI clients resend the whole conversation; `rzb serve` prefills it from an empty KV cache every time (25–30 s on a 4k-token history with Qwen3-4B-4bit). Keeping the cache between requests and rewinding it to the common token prefix brings this under 1 s. | |
| 24 | + | |
| 25 | + ## Scope | |
| 26 | + - `MLXEngine` keeps one KV cache per loaded model with the tokens of the last prompt. Each chat request renders its prompt, rewinds the cache to the longest common prefix (`trimPromptCache`), and prefills only the rest. Requests run one at a time per model (#34); the next request waits for the previous generation to finish before touching the cache. | |
| 27 | + - Rebuild from empty when the cache cannot be trimmed (hybrid models with recurrent state, a sliding window that has wrapped) or after an error. | |
| 28 | + - Report the reused tokens as `usage.prompt_tokens_details.cached_tokens` (chat and streaming usage) and in the request log line. | |
| 29 | + - The cache is freed with the model (unload, `keep_alive`, shutdown). | |
| 30 | + - Raw completions (`/v1/completions`) stay as they are. | |
| 31 | + | |
| 32 | + ## Out of scope (later tickets) | |
| 33 | + `kv_bits`, hybrid-state snapshots, several cached conversations per model, counting the kept cache in the memory budget. | |
| 34 | +tasks: | |
| 35 | + - id: 1 | |
| 36 | + title: "Replace the per-request ChatSession with a prompt cache in MLXEngine" | |
| 37 | + state: closed | |
| 38 | + priority: high | |
| 39 | + author: | |
| 40 | + name: k33g | |
| 41 | + email: ph.charriere@gmail.com | |
| 42 | + createdAt: 2026-11-25T21:45:00.000Z | |
| 43 | + updatedAt: 2026-11-25T23:30:00.000Z | |
| 44 | + closedAt: 2026-11-25T23:30:00.000Z | |
| 45 | + - id: 2 | |
| 46 | + title: "Report cached tokens in usage and in the log" | |
| 47 | + state: closed | |
| 48 | + priority: high | |
| 49 | + author: | |
| 50 | + name: k33g | |
| 51 | + email: ph.charriere@gmail.com | |
| 52 | + createdAt: 2026-11-25T21:45:00.000Z | |
| 53 | + updatedAt: 2026-11-25T23:30:00.000Z | |
| 54 | + closedAt: 2026-11-25T23:30:00.000Z | |
| 55 | + - id: 3 | |
| 56 | + title: "Tests: unit tests for the prefix logic, Mac smoke test that a second turn reuses the cache with the same answer" | |
| 57 | + state: closed | |
| 58 | + priority: high | |
| 59 | + author: | |
| 60 | + name: k33g | |
| 61 | + email: ph.charriere@gmail.com | |
| 62 | + createdAt: 2026-11-25T21:45:00.000Z | |
| 63 | + updatedAt: 2026-11-25T23:30:00.000Z | |
| 64 | + closedAt: 2026-11-25T23:30:00.000Z | |
| 65 | + - id: 4 | |
| 66 | + title: "Docs EN + FR: HTTP API usage field, model lifecycle explanation" | |
| 67 | + state: closed | |
| 68 | + priority: medium | |
| 69 | + author: | |
| 70 | + name: k33g | |
| 71 | + email: ph.charriere@gmail.com | |
| 72 | + createdAt: 2026-11-25T21:45:00.000Z | |
| 73 | + updatedAt: 2026-11-25T23:30:00.000Z | |
| 74 | + closedAt: 2026-11-25T23:30:00.000Z | |
| 75 | +comments: | |
| 76 | + - id: 1 | |
| 77 | + author: | |
| 78 | + name: k33g | |
| 79 | + email: ph.charriere@gmail.com | |
| 80 | + createdAt: 2026-11-25T23:30:00.000Z | |
| 81 | + body: | | |
| 82 | + Done. | |
| 83 | + | |
| 84 | + - `MLXEngine` keeps one KV cache per loaded model (`PromptCache`). `MLXSession` no longer uses mlx-swift-lm's `ChatSession`. For each request it: | |
| 85 | + 1. renders the whole conversation; | |
| 86 | + 2. waits for the previous generation to stop; | |
| 87 | + 3. cuts the cache back to the token prefix shared with the previous prompt (`PromptPrefix`, in Core); | |
| 88 | + 4. prefills only the rest, with `TokenIterator` and `generateTask`. | |
| 89 | + | |
| 90 | + It starts from an empty cache when the cache cannot be trimmed (hybrid models, a sliding window that has wrapped), when the model carries per-call state, or after an error. | |
| 91 | + - Reused tokens are reported in `usage.prompt_tokens_details.cached_tokens` (only when > 0) and as ` cached=N` in the request log line. Raw completions are unchanged. The cache is freed on unload and when a model is loaded. | |
| 92 | + - Tests: | |
| 93 | + - Linux, 168 tests: 5 for `PromptPrefix`, plus usage and log tests on the server. | |
| 94 | + - Mac, 193 tests: a smoke test on Qwen3-0.6B. The second turn reuses more than 10 prompt tokens and gives exactly the answer a fresh engine gives. | |
| 95 | + - Linux compatibility suite: 48 passed, 20 skipped. | |
| 96 | + - Gate PASS. On the way, `MLXSession` moved to its own file (file_length) and `send` was split (complexity). | |
| 97 | + - Docs EN + FR: | |
| 98 | + - model lifecycle: new section "Reusing the previous prompt", plus rejected alternatives; | |
| 99 | + - HTTP API: the usage field; | |
| 100 | + - CLI: the log suffix; | |
| 101 | + - architecture: the request path. | |
| 102 | + - Not done: the kept cache is not counted in the memory budget; one cache per model only (no LRU); `kv_bits` not exposed. | |
| 103 | + | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 48 | ||
| 3 | +title: "Prefix KV-cache reuse between stateless requests" | ||
| 4 | +state: closed | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-25T21:45:00.000Z | ||
| 9 | +updatedAt: 2026-11-25T23:30:00.000Z | ||
| 10 | +labels: | ||
| 11 | + - "kind::feature" | ||
| 12 | + - "area::engine" | ||
| 13 | + - "mac-only" | ||
| 14 | + - "priority::high" | ||
| 15 | +milestone: "v0.2 — OpenAI-compatible MLX server" | ||
| 16 | +epic: "Inference engine" | ||
| 17 | +related: | ||
| 18 | + - 47 | ||
| 19 | + - 34 | ||
| 20 | + - 35 | ||
| 21 | + - 26 | ||
| 22 | +body: | | ||
| 23 | + Decided after spike #47 (report: comment 1 on #47). OpenAI clients resend the whole conversation; `rzb serve` prefills it from an empty KV cache every time (25–30 s on a 4k-token history with Qwen3-4B-4bit). Keeping the cache between requests and rewinding it to the common token prefix brings this under 1 s. | ||
| 24 | + | ||
| 25 | + ## Scope | ||
| 26 | + - `MLXEngine` keeps one KV cache per loaded model with the tokens of the last prompt. Each chat request renders its prompt, rewinds the cache to the longest common prefix (`trimPromptCache`), and prefills only the rest. Requests run one at a time per model (#34); the next request waits for the previous generation to finish before touching the cache. | ||
| 27 | + - Rebuild from empty when the cache cannot be trimmed (hybrid models with recurrent state, a sliding window that has wrapped) or after an error. | ||
| 28 | + - Report the reused tokens as `usage.prompt_tokens_details.cached_tokens` (chat and streaming usage) and in the request log line. | ||
| 29 | + - The cache is freed with the model (unload, `keep_alive`, shutdown). | ||
| 30 | + - Raw completions (`/v1/completions`) stay as they are. | ||
| 31 | + | ||
| 32 | + ## Out of scope (later tickets) | ||
| 33 | + `kv_bits`, hybrid-state snapshots, several cached conversations per model, counting the kept cache in the memory budget. | ||
| 34 | +tasks: | ||
| 35 | + - id: 1 | ||
| 36 | + title: "Replace the per-request ChatSession with a prompt cache in MLXEngine" | ||
| 37 | + state: closed | ||
| 38 | + priority: high | ||
| 39 | + author: | ||
| 40 | + name: k33g | ||
| 41 | + email: ph.charriere@gmail.com | ||
| 42 | + createdAt: 2026-11-25T21:45:00.000Z | ||
| 43 | + updatedAt: 2026-11-25T23:30:00.000Z | ||
| 44 | + closedAt: 2026-11-25T23:30:00.000Z | ||
| 45 | + - id: 2 | ||
| 46 | + title: "Report cached tokens in usage and in the log" | ||
| 47 | + state: closed | ||
| 48 | + priority: high | ||
| 49 | + author: | ||
| 50 | + name: k33g | ||
| 51 | + email: ph.charriere@gmail.com | ||
| 52 | + createdAt: 2026-11-25T21:45:00.000Z | ||
| 53 | + updatedAt: 2026-11-25T23:30:00.000Z | ||
| 54 | + closedAt: 2026-11-25T23:30:00.000Z | ||
| 55 | + - id: 3 | ||
| 56 | + title: "Tests: unit tests for the prefix logic, Mac smoke test that a second turn reuses the cache with the same answer" | ||
| 57 | + state: closed | ||
| 58 | + priority: high | ||
| 59 | + author: | ||
| 60 | + name: k33g | ||
| 61 | + email: ph.charriere@gmail.com | ||
| 62 | + createdAt: 2026-11-25T21:45:00.000Z | ||
| 63 | + updatedAt: 2026-11-25T23:30:00.000Z | ||
| 64 | + closedAt: 2026-11-25T23:30:00.000Z | ||
| 65 | + - id: 4 | ||
| 66 | + title: "Docs EN + FR: HTTP API usage field, model lifecycle explanation" | ||
| 67 | + state: closed | ||
| 68 | + priority: medium | ||
| 69 | + author: | ||
| 70 | + name: k33g | ||
| 71 | + email: ph.charriere@gmail.com | ||
| 72 | + createdAt: 2026-11-25T21:45:00.000Z | ||
| 73 | + updatedAt: 2026-11-25T23:30:00.000Z | ||
| 74 | + closedAt: 2026-11-25T23:30:00.000Z | ||
| 75 | +comments: | ||
| 76 | + - id: 1 | ||
| 77 | + author: | ||
| 78 | + name: k33g | ||
| 79 | + email: ph.charriere@gmail.com | ||
| 80 | + createdAt: 2026-11-25T23:30:00.000Z | ||
| 81 | + body: | | ||
| 82 | + Done. | ||
| 83 | + | ||
| 84 | + - `MLXEngine` keeps one KV cache per loaded model (`PromptCache`). `MLXSession` no longer uses mlx-swift-lm's `ChatSession`. For each request it: | ||
| 85 | + 1. renders the whole conversation; | ||
| 86 | + 2. waits for the previous generation to stop; | ||
| 87 | + 3. cuts the cache back to the token prefix shared with the previous prompt (`PromptPrefix`, in Core); | ||
| 88 | + 4. prefills only the rest, with `TokenIterator` and `generateTask`. | ||
| 89 | + | ||
| 90 | + It starts from an empty cache when the cache cannot be trimmed (hybrid models, a sliding window that has wrapped), when the model carries per-call state, or after an error. | ||
| 91 | + - Reused tokens are reported in `usage.prompt_tokens_details.cached_tokens` (only when > 0) and as ` cached=N` in the request log line. Raw completions are unchanged. The cache is freed on unload and when a model is loaded. | ||
| 92 | + - Tests: | ||
| 93 | + - Linux, 168 tests: 5 for `PromptPrefix`, plus usage and log tests on the server. | ||
| 94 | + - Mac, 193 tests: a smoke test on Qwen3-0.6B. The second turn reuses more than 10 prompt tokens and gives exactly the answer a fresh engine gives. | ||
| 95 | + - Linux compatibility suite: 48 passed, 20 skipped. | ||
| 96 | + - Gate PASS. On the way, `MLXSession` moved to its own file (file_length) and `send` was split (complexity). | ||
| 97 | + - Docs EN + FR: | ||
| 98 | + - model lifecycle: new section "Reusing the previous prompt", plus rejected alternatives; | ||
| 99 | + - HTTP API: the usage field; | ||
| 100 | + - CLI: the log suffix; | ||
| 101 | + - architecture: the request path. | ||
| 102 | + - Not done: the kept cache is not counted in the memory budget; one cache per model only (no LRU); `kv_bits` not exposed. | ||
| 103 | + | ||
added
.tickets/issues/0049-sampling-parameters-top-k-min-p-repetition-penalty.yaml +47 -0 | new file mode 100644 | ||
| @@ -0,0 +1,47 @@ | ||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | |
| 2 | +id: 49 | |
| 3 | +title: "Sampling parameters: top_k, min_p, repetition_penalty, logit_bias" | |
| 4 | +state: open | |
| 5 | +author: | |
| 6 | + name: k33g | |
| 7 | + email: ph.charriere@gmail.com | |
| 8 | +createdAt: 2026-11-25T21:45:00.000Z | |
| 9 | +updatedAt: 2026-11-25T21:45:00.000Z | |
| 10 | +labels: | |
| 11 | + - "kind::feature" | |
| 12 | + - "area::server" | |
| 13 | + - "priority::medium" | |
| 14 | +milestone: "v0.2 — OpenAI-compatible MLX server" | |
| 15 | +epic: "Inference engine" | |
| 16 | +related: | |
| 17 | + - 39 | |
| 18 | + - 48 | |
| 19 | +body: | | |
| 20 | + Asked by the user (2026-11-25): which sampling parameters does the server handle? | |
| 21 | + | |
| 22 | + Handled today: `temperature`, `top_p`, `max_tokens` / `max_completion_tokens`, `stop`, `seed`, `presence_penalty`, `frequency_penalty` (temperature, top_p and max_tokens also as configuration defaults / locked values). | |
| 23 | + | |
| 24 | + Silently ignored today (unknown fields): `top_k`, `min_p`, `repetition_penalty` — not in OpenAI's API, but accepted by vLLM, llama-server, Ollama and LM Studio and sent by many clients; mlx-swift-lm supports them (`topK`, `minP`, `repetitionPenalty`). `logit_bias` is ignored too and should be refused while unsupported. | |
| 25 | + | |
| 26 | + ## To decide / do | |
| 27 | + - Accept `top_k`, `min_p`, `repetition_penalty` on chat and completions, with range checks, configuration `defaults` / `locked`. | |
| 28 | + - Refuse `logit_bias` with 400 (or implement it with a logit processor). | |
| 29 | + - Optionally use the model's `generation_config.json` recommended values (Qwen3: temperature 0.6, top_p 0.95, top_k 20) as defaults below the configuration. | |
| 30 | +tasks: | |
| 31 | + - id: 1 | |
| 32 | + title: "Decide the scope (fields, generation_config.json defaults)" | |
| 33 | + state: open | |
| 34 | + priority: high | |
| 35 | + author: | |
| 36 | + name: k33g | |
| 37 | + email: ph.charriere@gmail.com | |
| 38 | + createdAt: 2026-11-25T21:45:00.000Z | |
| 39 | + - id: 2 | |
| 40 | + title: "Implement, test, document EN + FR" | |
| 41 | + state: open | |
| 42 | + priority: medium | |
| 43 | + author: | |
| 44 | + name: k33g | |
| 45 | + email: ph.charriere@gmail.com | |
| 46 | + createdAt: 2026-11-25T21:45:00.000Z | |
| 47 | +comments: [] | |
| new file mode 100644 | |||
| @@ -0,0 +1,47 @@ | |||
| 1 | +# Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | ||
| 2 | +id: 49 | ||
| 3 | +title: "Sampling parameters: top_k, min_p, repetition_penalty, logit_bias" | ||
| 4 | +state: open | ||
| 5 | +author: | ||
| 6 | + name: k33g | ||
| 7 | + email: ph.charriere@gmail.com | ||
| 8 | +createdAt: 2026-11-25T21:45:00.000Z | ||
| 9 | +updatedAt: 2026-11-25T21:45:00.000Z | ||
| 10 | +labels: | ||
| 11 | + - "kind::feature" | ||
| 12 | + - "area::server" | ||
| 13 | + - "priority::medium" | ||
| 14 | +milestone: "v0.2 — OpenAI-compatible MLX server" | ||
| 15 | +epic: "Inference engine" | ||
| 16 | +related: | ||
| 17 | + - 39 | ||
| 18 | + - 48 | ||
| 19 | +body: | | ||
| 20 | + Asked by the user (2026-11-25): which sampling parameters does the server handle? | ||
| 21 | + | ||
| 22 | + Handled today: `temperature`, `top_p`, `max_tokens` / `max_completion_tokens`, `stop`, `seed`, `presence_penalty`, `frequency_penalty` (temperature, top_p and max_tokens also as configuration defaults / locked values). | ||
| 23 | + | ||
| 24 | + Silently ignored today (unknown fields): `top_k`, `min_p`, `repetition_penalty` — not in OpenAI's API, but accepted by vLLM, llama-server, Ollama and LM Studio and sent by many clients; mlx-swift-lm supports them (`topK`, `minP`, `repetitionPenalty`). `logit_bias` is ignored too and should be refused while unsupported. | ||
| 25 | + | ||
| 26 | + ## To decide / do | ||
| 27 | + - Accept `top_k`, `min_p`, `repetition_penalty` on chat and completions, with range checks, configuration `defaults` / `locked`. | ||
| 28 | + - Refuse `logit_bias` with 400 (or implement it with a logit processor). | ||
| 29 | + - Optionally use the model's `generation_config.json` recommended values (Qwen3: temperature 0.6, top_p 0.95, top_k 20) as defaults below the configuration. | ||
| 30 | +tasks: | ||
| 31 | + - id: 1 | ||
| 32 | + title: "Decide the scope (fields, generation_config.json defaults)" | ||
| 33 | + state: open | ||
| 34 | + priority: high | ||
| 35 | + author: | ||
| 36 | + name: k33g | ||
| 37 | + email: ph.charriere@gmail.com | ||
| 38 | + createdAt: 2026-11-25T21:45:00.000Z | ||
| 39 | + - id: 2 | ||
| 40 | + title: "Implement, test, document EN + FR" | ||
| 41 | + state: open | ||
| 42 | + priority: medium | ||
| 43 | + author: | ||
| 44 | + name: k33g | ||
| 45 | + email: ph.charriere@gmail.com | ||
| 46 | + createdAt: 2026-11-25T21:45:00.000Z | ||
| 47 | +comments: [] | ||
modified
Sources/RazorbillCore/Engine/Messages.swift +5 -1 | @@ -91,14 +91,18 @@ public struct GenerationStats: Sendable, Equatable { | ||
| 91 | 91 | public var tokensPerSecond: Double |
| 92 | 92 | /// The answer was cut because it reached `maxTokens`. |
| 93 | 93 | public var hitTokenLimit: Bool |
| 94 | + /// Prompt tokens taken from the cache of the previous request instead of being computed | |
| 95 | + /// again; included in ``promptTokens``. | |
| 96 | + public var cachedPromptTokens: Int | |
| 94 | 97 | |
| 95 | 98 | public init( |
| 96 | 99 | promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double, |
| 97 | - hitTokenLimit: Bool = false | |
| 100 | + hitTokenLimit: Bool = false, cachedPromptTokens: Int = 0 | |
| 98 | 101 | ) { |
| 99 | 102 | self.promptTokens = promptTokens |
| 100 | 103 | self.generatedTokens = generatedTokens |
| 101 | 104 | self.tokensPerSecond = tokensPerSecond |
| 102 | 105 | self.hitTokenLimit = hitTokenLimit |
| 106 | + self.cachedPromptTokens = cachedPromptTokens | |
| 103 | 107 | } |
| 104 | 108 | } |
| @@ -91,14 +91,18 @@ public struct GenerationStats: Sendable, Equatable { | |||
| 91 | public var tokensPerSecond: Double | 91 | public var tokensPerSecond: Double |
| 92 | /// The answer was cut because it reached `maxTokens`. | 92 | /// The answer was cut because it reached `maxTokens`. |
| 93 | public var hitTokenLimit: Bool | 93 | public var hitTokenLimit: Bool |
| 94 | + /// Prompt tokens taken from the cache of the previous request instead of being computed | ||
| 95 | + /// again; included in ``promptTokens``. | ||
| 96 | + public var cachedPromptTokens: Int | ||
| 94 | 97 | ||
| 95 | public init( | 98 | public init( |
| 96 | promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double, | 99 | promptTokens: Int, generatedTokens: Int, tokensPerSecond: Double, |
| 97 | - hitTokenLimit: Bool = false | 100 | + hitTokenLimit: Bool = false, cachedPromptTokens: Int = 0 |
| 98 | ) { | 101 | ) { |
| 99 | self.promptTokens = promptTokens | 102 | self.promptTokens = promptTokens |
| 100 | self.generatedTokens = generatedTokens | 103 | self.generatedTokens = generatedTokens |
| 101 | self.tokensPerSecond = tokensPerSecond | 104 | self.tokensPerSecond = tokensPerSecond |
| 102 | self.hitTokenLimit = hitTokenLimit | 105 | self.hitTokenLimit = hitTokenLimit |
| 106 | + self.cachedPromptTokens = cachedPromptTokens | ||
| 103 | } | 107 | } |
| 104 | } | 108 | } |
added
Sources/RazorbillCore/Engine/PromptPrefix.swift +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +/// How much of a kept KV cache a new prompt can reuse. | |
| 2 | +/// | |
| 3 | +/// An OpenAI client resends the whole conversation with every request. The engine keeps the cache | |
| 4 | +/// of the previous request: it holds that prompt's tokens followed by the tokens generated for | |
| 5 | +/// it. The new prompt usually starts with the same tokens, so the cache is cut back to the part | |
| 6 | +/// both share and only the rest of the prompt is computed. | |
| 7 | +/// | |
| 8 | +/// ```swift | |
| 9 | +/// let reuse = PromptPrefix(prompt: [1, 2, 3, 9], previous: [1, 2, 3], cachedLength: 5) | |
| 10 | +/// // reuse.keep == 3 (tokens 1, 2, 3), reuse.trim == 2 (the 2 tokens generated last time) | |
| 11 | +/// ``` | |
| 12 | +public struct PromptPrefix: Equatable, Sendable { | |
| 13 | + /// Leading prompt tokens already in the cache; 0 means start from an empty cache. | |
| 14 | + public let keep: Int | |
| 15 | + /// Positions to remove from the end of the cache so that it holds exactly `keep` tokens. | |
| 16 | + public let trim: Int | |
| 17 | + | |
| 18 | + /// - Parameters: | |
| 19 | + /// - prompt: the new prompt's tokens. | |
| 20 | + /// - previous: the tokens of the prompt the cache was built from (empty: unknown). | |
| 21 | + /// - cachedLength: how many positions the cache holds (previous prompt + generated tokens). | |
| 22 | + public init(prompt: [Int], previous: [Int], cachedLength: Int) { | |
| 23 | + let common = zip(prompt, previous).prefix { $0 == $1 }.count | |
| 24 | + // At least one prompt token must be computed to get the first answer token. | |
| 25 | + let keep = max(0, min(common, prompt.count - 1, cachedLength)) | |
| 26 | + self.keep = keep | |
| 27 | + self.trim = keep == 0 ? 0 : cachedLength - keep | |
| 28 | + } | |
| 29 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +/// How much of a kept KV cache a new prompt can reuse. | ||
| 2 | +/// | ||
| 3 | +/// An OpenAI client resends the whole conversation with every request. The engine keeps the cache | ||
| 4 | +/// of the previous request: it holds that prompt's tokens followed by the tokens generated for | ||
| 5 | +/// it. The new prompt usually starts with the same tokens, so the cache is cut back to the part | ||
| 6 | +/// both share and only the rest of the prompt is computed. | ||
| 7 | +/// | ||
| 8 | +/// ```swift | ||
| 9 | +/// let reuse = PromptPrefix(prompt: [1, 2, 3, 9], previous: [1, 2, 3], cachedLength: 5) | ||
| 10 | +/// // reuse.keep == 3 (tokens 1, 2, 3), reuse.trim == 2 (the 2 tokens generated last time) | ||
| 11 | +/// ``` | ||
| 12 | +public struct PromptPrefix: Equatable, Sendable { | ||
| 13 | + /// Leading prompt tokens already in the cache; 0 means start from an empty cache. | ||
| 14 | + public let keep: Int | ||
| 15 | + /// Positions to remove from the end of the cache so that it holds exactly `keep` tokens. | ||
| 16 | + public let trim: Int | ||
| 17 | + | ||
| 18 | + /// - Parameters: | ||
| 19 | + /// - prompt: the new prompt's tokens. | ||
| 20 | + /// - previous: the tokens of the prompt the cache was built from (empty: unknown). | ||
| 21 | + /// - cachedLength: how many positions the cache holds (previous prompt + generated tokens). | ||
| 22 | + public init(prompt: [Int], previous: [Int], cachedLength: Int) { | ||
| 23 | + let common = zip(prompt, previous).prefix { $0 == $1 }.count | ||
| 24 | + // At least one prompt token must be computed to get the first answer token. | ||
| 25 | + let keep = max(0, min(common, prompt.count - 1, cachedLength)) | ||
| 26 | + self.keep = keep | ||
| 27 | + self.trim = keep == 0 ? 0 : cachedLength - keep | ||
| 28 | + } | ||
| 29 | +} | ||
modified
Sources/RazorbillMLX/MLXEngine.swift +23 -50 | @@ -26,6 +26,8 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 26 | 26 | private var grammars = GrammarSupport() |
| 27 | 27 | /// The model's own tool-call format, read at load time (see ``makeSession(_:)``). |
| 28 | 28 | private var nativeToolCallFormat: ToolCallFormat? |
| 29 | + /// The last chat request's KV cache, reused by the next one. | |
| 30 | + private let promptCache = PromptCache() | |
| 29 | 31 | |
| 30 | 32 | public init(store: ModelStore = ModelStore()) { |
| 31 | 33 | self.store = store |
| @@ -55,6 +57,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 55 | 57 | nativeToolCallFormat = format |
| 56 | 58 | grammars = GrammarSupport() // built for this model's tokenizer |
| 57 | 59 | } |
| 60 | + promptCache.clear() | |
| 58 | 61 | } |
| 59 | 62 | |
| 60 | 63 | public func download( |
| @@ -70,6 +73,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 70 | 73 | /// Drops the model; its weights are freed once no session uses them any more. |
| 71 | 74 | public func unload() async { |
| 72 | 75 | lock.withLock { container = nil } |
| 76 | + promptCache.clear() | |
| 73 | 77 | } |
| 74 | 78 | |
| 75 | 79 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| @@ -81,17 +85,17 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 81 | 85 | // answer starting with "{" (a JSON answer would then arrive in one piece). |
| 82 | 86 | parameters.toolCallPolicy.recovery = .disabled |
| 83 | 87 | } |
| 84 | - let session = ChatSession( | |
| 85 | - container, | |
| 86 | - instructions: setup.system.isEmpty ? nil : setup.system, | |
| 87 | - generateParameters: parameters, | |
| 88 | + let request = MLXSession.Request( | |
| 89 | + parameters: parameters, | |
| 88 | 90 | components: try await components(container, setup: setup), |
| 91 | + tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec), | |
| 89 | 92 | // Read by Qwen3-style chat templates; ignored by the others. |
| 90 | - additionalContext: ["enable_thinking": setup.generation.thinking], | |
| 91 | - tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec)) | |
| 93 | + templateContext: ["enable_thinking": setup.generation.thinking]) | |
| 92 | 94 | let opensThinking = await Self.promptOpensThinking( |
| 93 | 95 | container, thinking: setup.generation.thinking) |
| 94 | - return MLXSession(session: session, startsInsideThinking: opensThinking) | |
| 96 | + return MLXSession( | |
| 97 | + container: container, cache: promptCache, request: request, | |
| 98 | + system: setup.system, startsInsideThinking: opensThinking) | |
| 95 | 99 | } |
| 96 | 100 | |
| 97 | 101 | /// The prompt's tokens as they are (the tokenizer may add its BOS token, as for any raw |
| @@ -213,44 +217,6 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | ||
| 213 | 217 | } |
| 214 | 218 | } |
| 215 | 219 | |
| 216 | -/// One conversation: keeps mlx-swift-lm's `ChatSession` (history and KV cache). | |
| 217 | -/// Callers must not send twice at the same time on one session, which is what makes it safe to | |
| 218 | -/// share (the server will queue requests per model, ticket #34). | |
| 219 | -private final class MLXSession: EngineSession, @unchecked Sendable { | |
| 220 | - private let session: ChatSession | |
| 221 | - private let startsInsideThinking: Bool | |
| 222 | - | |
| 223 | - init(session: ChatSession, startsInsideThinking: Bool) { | |
| 224 | - self.session = session | |
| 225 | - self.startsInsideThinking = startsInsideThinking | |
| 226 | - } | |
| 227 | - | |
| 228 | - func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | |
| 229 | - AsyncThrowingStream { continuation in | |
| 230 | - let task = Task { | |
| 231 | - // Converted here: mlx-swift-lm's Chat.Message is not Sendable. | |
| 232 | - let chat = messages.map(MLXConversion.message) | |
| 233 | - var splitter = ThinkingSplitter(startsInsideThinking: self.startsInsideThinking) | |
| 234 | - do { | |
| 235 | - for try await generation in self.session.streamDetails(to: chat) { | |
| 236 | - try Task.checkCancellation() | |
| 237 | - for event in MLXConversion.events(generation, splitter: &splitter) { | |
| 238 | - continuation.yield(event) | |
| 239 | - } | |
| 240 | - } | |
| 241 | - for event in splitter.finish() { | |
| 242 | - continuation.yield(event) | |
| 243 | - } | |
| 244 | - continuation.finish() | |
| 245 | - } catch { | |
| 246 | - continuation.finish(throwing: error) | |
| 247 | - } | |
| 248 | - } | |
| 249 | - continuation.onTermination = { _ in task.cancel() } | |
| 250 | - } | |
| 251 | - } | |
| 252 | -} | |
| 253 | - | |
| 254 | 220 | /// Converts between razorbill's types and mlx-swift-lm's. |
| 255 | 221 | enum MLXConversion { |
| 256 | 222 | static func message(_ message: ChatMessage) -> Chat.Message { |
| @@ -262,8 +228,10 @@ enum MLXConversion { | ||
| 262 | 228 | } |
| 263 | 229 | } |
| 264 | 230 | |
| 231 | + /// `cachedPromptTokens`: prompt tokens taken from the prompt cache, which mlx-swift-lm does | |
| 232 | + /// not count in `promptTokenCount`. | |
| 265 | 233 | static func events( |
| 266 | - _ generation: Generation, splitter: inout ThinkingSplitter | |
| 234 | + _ generation: Generation, splitter: inout ThinkingSplitter, cachedPromptTokens: Int = 0 | |
| 267 | 235 | ) -> [EngineEvent] { |
| 268 | 236 | switch generation { |
| 269 | 237 | case .chunk(let text): |
| @@ -274,7 +242,8 @@ enum MLXConversion { | ||
| 274 | 242 | id: call.id, name: call.function.name, arguments: arguments) |
| 275 | 243 | return splitter.finish() + [.toolCall(toolCall)] |
| 276 | 244 | case .info(let info): |
| 277 | - return splitter.finish() + [.stats(stats(info))] | |
| 245 | + let summary = stats(info, cachedPromptTokens: cachedPromptTokens) | |
| 246 | + return splitter.finish() + [.stats(summary)] | |
| 278 | 247 | default: |
| 279 | 248 | return [] |
| 280 | 249 | } |
| @@ -304,10 +273,14 @@ enum MLXConversion { | ||
| 304 | 273 | } |
| 305 | 274 | } |
| 306 | 275 | |
| 307 | - static func stats(_ info: GenerateCompletionInfo) -> GenerationStats { | |
| 276 | + static func stats( | |
| 277 | + _ info: GenerateCompletionInfo, cachedPromptTokens: Int = 0 | |
| 278 | + ) -> GenerationStats { | |
| 308 | 279 | GenerationStats( |
| 309 | - promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | |
| 310 | - tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | |
| 280 | + promptTokens: info.promptTokenCount + cachedPromptTokens, | |
| 281 | + generatedTokens: info.generationTokenCount, | |
| 282 | + tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length, | |
| 283 | + cachedPromptTokens: cachedPromptTokens) | |
| 311 | 284 | } |
| 312 | 285 | |
| 313 | 286 | static func value(_ json: JSONValue) -> ConfigValue { |
| @@ -26,6 +26,8 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 26 | private var grammars = GrammarSupport() | 26 | private var grammars = GrammarSupport() |
| 27 | /// The model's own tool-call format, read at load time (see ``makeSession(_:)``). | 27 | /// The model's own tool-call format, read at load time (see ``makeSession(_:)``). |
| 28 | private var nativeToolCallFormat: ToolCallFormat? | 28 | private var nativeToolCallFormat: ToolCallFormat? |
| 29 | + /// The last chat request's KV cache, reused by the next one. | ||
| 30 | + private let promptCache = PromptCache() | ||
| 29 | 31 | ||
| 30 | public init(store: ModelStore = ModelStore()) { | 32 | public init(store: ModelStore = ModelStore()) { |
| 31 | self.store = store | 33 | self.store = store |
| @@ -55,6 +57,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 55 | nativeToolCallFormat = format | 57 | nativeToolCallFormat = format |
| 56 | grammars = GrammarSupport() // built for this model's tokenizer | 58 | grammars = GrammarSupport() // built for this model's tokenizer |
| 57 | } | 59 | } |
| 60 | + promptCache.clear() | ||
| 58 | } | 61 | } |
| 59 | 62 | ||
| 60 | public func download( | 63 | public func download( |
| @@ -70,6 +73,7 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 70 | /// Drops the model; its weights are freed once no session uses them any more. | 73 | /// Drops the model; its weights are freed once no session uses them any more. |
| 71 | public func unload() async { | 74 | public func unload() async { |
| 72 | lock.withLock { container = nil } | 75 | lock.withLock { container = nil } |
| 76 | + promptCache.clear() | ||
| 73 | } | 77 | } |
| 74 | 78 | ||
| 75 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 79 | public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| @@ -81,17 +85,17 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 81 | // answer starting with "{" (a JSON answer would then arrive in one piece). | 85 | // answer starting with "{" (a JSON answer would then arrive in one piece). |
| 82 | parameters.toolCallPolicy.recovery = .disabled | 86 | parameters.toolCallPolicy.recovery = .disabled |
| 83 | } | 87 | } |
| 84 | - let session = ChatSession( | 88 | + let request = MLXSession.Request( |
| 85 | - container, | 89 | + parameters: parameters, |
| 86 | - instructions: setup.system.isEmpty ? nil : setup.system, | ||
| 87 | - generateParameters: parameters, | ||
| 88 | components: try await components(container, setup: setup), | 90 | components: try await components(container, setup: setup), |
| 91 | + tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec), | ||
| 89 | // Read by Qwen3-style chat templates; ignored by the others. | 92 | // Read by Qwen3-style chat templates; ignored by the others. |
| 90 | - additionalContext: ["enable_thinking": setup.generation.thinking], | 93 | + templateContext: ["enable_thinking": setup.generation.thinking]) |
| 91 | - tools: setup.tools.isEmpty ? nil : setup.tools.map(MLXConversion.toolSpec)) | ||
| 92 | let opensThinking = await Self.promptOpensThinking( | 94 | let opensThinking = await Self.promptOpensThinking( |
| 93 | container, thinking: setup.generation.thinking) | 95 | container, thinking: setup.generation.thinking) |
| 94 | - return MLXSession(session: session, startsInsideThinking: opensThinking) | 96 | + return MLXSession( |
| 97 | + container: container, cache: promptCache, request: request, | ||
| 98 | + system: setup.system, startsInsideThinking: opensThinking) | ||
| 95 | } | 99 | } |
| 96 | 100 | ||
| 97 | /// The prompt's tokens as they are (the tokenizer may add its BOS token, as for any raw | 101 | /// The prompt's tokens as they are (the tokenizer may add its BOS token, as for any raw |
| @@ -213,44 +217,6 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable { | |||
| 213 | } | 217 | } |
| 214 | } | 218 | } |
| 215 | 219 | ||
| 216 | -/// One conversation: keeps mlx-swift-lm's `ChatSession` (history and KV cache). | ||
| 217 | -/// Callers must not send twice at the same time on one session, which is what makes it safe to | ||
| 218 | -/// share (the server will queue requests per model, ticket #34). | ||
| 219 | -private final class MLXSession: EngineSession, @unchecked Sendable { | ||
| 220 | - private let session: ChatSession | ||
| 221 | - private let startsInsideThinking: Bool | ||
| 222 | - | ||
| 223 | - init(session: ChatSession, startsInsideThinking: Bool) { | ||
| 224 | - self.session = session | ||
| 225 | - self.startsInsideThinking = startsInsideThinking | ||
| 226 | - } | ||
| 227 | - | ||
| 228 | - func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 229 | - AsyncThrowingStream { continuation in | ||
| 230 | - let task = Task { | ||
| 231 | - // Converted here: mlx-swift-lm's Chat.Message is not Sendable. | ||
| 232 | - let chat = messages.map(MLXConversion.message) | ||
| 233 | - var splitter = ThinkingSplitter(startsInsideThinking: self.startsInsideThinking) | ||
| 234 | - do { | ||
| 235 | - for try await generation in self.session.streamDetails(to: chat) { | ||
| 236 | - try Task.checkCancellation() | ||
| 237 | - for event in MLXConversion.events(generation, splitter: &splitter) { | ||
| 238 | - continuation.yield(event) | ||
| 239 | - } | ||
| 240 | - } | ||
| 241 | - for event in splitter.finish() { | ||
| 242 | - continuation.yield(event) | ||
| 243 | - } | ||
| 244 | - continuation.finish() | ||
| 245 | - } catch { | ||
| 246 | - continuation.finish(throwing: error) | ||
| 247 | - } | ||
| 248 | - } | ||
| 249 | - continuation.onTermination = { _ in task.cancel() } | ||
| 250 | - } | ||
| 251 | - } | ||
| 252 | -} | ||
| 253 | - | ||
| 254 | /// Converts between razorbill's types and mlx-swift-lm's. | 220 | /// Converts between razorbill's types and mlx-swift-lm's. |
| 255 | enum MLXConversion { | 221 | enum MLXConversion { |
| 256 | static func message(_ message: ChatMessage) -> Chat.Message { | 222 | static func message(_ message: ChatMessage) -> Chat.Message { |
| @@ -262,8 +228,10 @@ enum MLXConversion { | |||
| 262 | } | 228 | } |
| 263 | } | 229 | } |
| 264 | 230 | ||
| 231 | + /// `cachedPromptTokens`: prompt tokens taken from the prompt cache, which mlx-swift-lm does | ||
| 232 | + /// not count in `promptTokenCount`. | ||
| 265 | static func events( | 233 | static func events( |
| 266 | - _ generation: Generation, splitter: inout ThinkingSplitter | 234 | + _ generation: Generation, splitter: inout ThinkingSplitter, cachedPromptTokens: Int = 0 |
| 267 | ) -> [EngineEvent] { | 235 | ) -> [EngineEvent] { |
| 268 | switch generation { | 236 | switch generation { |
| 269 | case .chunk(let text): | 237 | case .chunk(let text): |
| @@ -274,7 +242,8 @@ enum MLXConversion { | |||
| 274 | id: call.id, name: call.function.name, arguments: arguments) | 242 | id: call.id, name: call.function.name, arguments: arguments) |
| 275 | return splitter.finish() + [.toolCall(toolCall)] | 243 | return splitter.finish() + [.toolCall(toolCall)] |
| 276 | case .info(let info): | 244 | case .info(let info): |
| 277 | - return splitter.finish() + [.stats(stats(info))] | 245 | + let summary = stats(info, cachedPromptTokens: cachedPromptTokens) |
| 246 | + return splitter.finish() + [.stats(summary)] | ||
| 278 | default: | 247 | default: |
| 279 | return [] | 248 | return [] |
| 280 | } | 249 | } |
| @@ -304,10 +273,14 @@ enum MLXConversion { | |||
| 304 | } | 273 | } |
| 305 | } | 274 | } |
| 306 | 275 | ||
| 307 | - static func stats(_ info: GenerateCompletionInfo) -> GenerationStats { | 276 | + static func stats( |
| 277 | + _ info: GenerateCompletionInfo, cachedPromptTokens: Int = 0 | ||
| 278 | + ) -> GenerationStats { | ||
| 308 | GenerationStats( | 279 | GenerationStats( |
| 309 | - promptTokens: info.promptTokenCount, generatedTokens: info.generationTokenCount, | 280 | + promptTokens: info.promptTokenCount + cachedPromptTokens, |
| 310 | - tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length) | 281 | + generatedTokens: info.generationTokenCount, |
| 282 | + tokensPerSecond: info.tokensPerSecond, hitTokenLimit: info.stopReason == .length, | ||
| 283 | + cachedPromptTokens: cachedPromptTokens) | ||
| 311 | } | 284 | } |
| 312 | 285 | ||
| 313 | static func value(_ json: JSONValue) -> ConfigValue { | 286 | static func value(_ json: JSONValue) -> ConfigValue { |
added
Sources/RazorbillMLX/MLXSession.swift +118 -0 | new file mode 100644 | ||
| @@ -0,0 +1,118 @@ | ||
| 1 | +#if canImport(MLXLLM) | |
| 2 | +import Foundation | |
| 3 | +import MLX | |
| 4 | +import MLXLMCommon | |
| 5 | +import RazorbillCore | |
| 6 | + | |
| 7 | +/// One conversation. Each call renders the whole history with the chat template and generates | |
| 8 | +/// from the model's ``PromptCache``, so only the part of the prompt the cache does not already | |
| 9 | +/// hold is computed. | |
| 10 | +/// Callers must not send twice at the same time on one session; the server runs one request per | |
| 11 | +/// model at a time (ticket #34). | |
| 12 | +final class MLXSession: EngineSession, @unchecked Sendable { | |
| 13 | + /// What every generation of this session uses. | |
| 14 | + struct Request: Sendable { | |
| 15 | + let parameters: GenerateParameters | |
| 16 | + let components: GenerationComponents | |
| 17 | + let tools: [MLXLMCommon.ToolSpec]? | |
| 18 | + let templateContext: [String: any Sendable] | |
| 19 | + } | |
| 20 | + | |
| 21 | + private let container: ModelContainer | |
| 22 | + private let cache: PromptCache | |
| 23 | + private let request: Request | |
| 24 | + private let startsInsideThinking: Bool | |
| 25 | + private let lock = NSLock() | |
| 26 | + private var history: [ChatMessage] | |
| 27 | + | |
| 28 | + init( | |
| 29 | + container: ModelContainer, cache: PromptCache, request: Request, system: String, | |
| 30 | + startsInsideThinking: Bool | |
| 31 | + ) { | |
| 32 | + self.container = container | |
| 33 | + self.cache = cache | |
| 34 | + self.request = request | |
| 35 | + self.startsInsideThinking = startsInsideThinking | |
| 36 | + self.history = system.isEmpty ? [] : [ChatMessage(role: .system, content: system)] | |
| 37 | + } | |
| 38 | + | |
| 39 | + func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | |
| 40 | + AsyncThrowingStream { continuation in | |
| 41 | + let task = Task { | |
| 42 | + do { | |
| 43 | + let answer = try await self.answer(messages, into: continuation) | |
| 44 | + self.lock.withLock { self.history.append(.assistant(answer)) } | |
| 45 | + continuation.finish() | |
| 46 | + } catch { | |
| 47 | + continuation.finish(throwing: error) | |
| 48 | + } | |
| 49 | + } | |
| 50 | + continuation.onTermination = { _ in task.cancel() } | |
| 51 | + } | |
| 52 | + } | |
| 53 | + | |
| 54 | + /// Streams the events of the answer to `messages` into `continuation`; returns its text. | |
| 55 | + private func answer( | |
| 56 | + _ messages: [ChatMessage], | |
| 57 | + into continuation: AsyncThrowingStream<EngineEvent, Error>.Continuation | |
| 58 | + ) async throws -> String { | |
| 59 | + let conversation = lock.withLock { | |
| 60 | + history += messages | |
| 61 | + return history | |
| 62 | + } | |
| 63 | + var splitter = ThinkingSplitter(startsInsideThinking: startsInsideThinking) | |
| 64 | + var text = "" | |
| 65 | + let (generations, reused) = try await start(conversation) | |
| 66 | + for await generation in generations { | |
| 67 | + try Task.checkCancellation() | |
| 68 | + let events = MLXConversion.events( | |
| 69 | + generation, splitter: &splitter, cachedPromptTokens: reused) | |
| 70 | + text += Self.yield(events, to: continuation) | |
| 71 | + } | |
| 72 | + return text + Self.yield(splitter.finish(), to: continuation) | |
| 73 | + } | |
| 74 | + | |
| 75 | + /// Passes `events` on and returns the answer text they carry. | |
| 76 | + private static func yield( | |
| 77 | + _ events: [EngineEvent], to continuation: AsyncThrowingStream<EngineEvent, Error>.Continuation | |
| 78 | + ) -> String { | |
| 79 | + var text = "" | |
| 80 | + for event in events { | |
| 81 | + if case .text(let piece) = event { text += piece } | |
| 82 | + continuation.yield(event) | |
| 83 | + } | |
| 84 | + return text | |
| 85 | + } | |
| 86 | + | |
| 87 | + /// Renders `conversation`, takes what the prompt cache already holds of it, and starts the | |
| 88 | + /// generation. Returns its events and the number of prompt tokens taken from the cache. | |
| 89 | + private func start( | |
| 90 | + _ conversation: [ChatMessage] | |
| 91 | + ) async throws -> (AsyncStream<Generation>, Int) { | |
| 92 | + let request = request | |
| 93 | + let cache = cache | |
| 94 | + return try await container.perform(values: conversation) { context, conversation in | |
| 95 | + let input = try await context.processor.prepare( | |
| 96 | + input: UserInput( | |
| 97 | + chat: conversation.map(MLXConversion.message), tools: request.tools, | |
| 98 | + additionalContext: request.templateContext)) | |
| 99 | + let prompt = input.text.tokens.asArray(Int.self) | |
| 100 | + let (kvCache, reused) = try await cache.checkout( | |
| 101 | + prompt, model: context.model, parameters: request.parameters) | |
| 102 | + let fed = reused == 0 ? input : LMInput(tokens: MLXArray(Array(prompt[reused...]))) | |
| 103 | + let iterator = try TokenIterator( | |
| 104 | + input: fed, model: context.model, cache: kvCache, parameters: request.parameters, | |
| 105 | + components: request.components) | |
| 106 | + // Models that carry state between calls (positions of multimodal models) cannot | |
| 107 | + // resume from the cache alone. | |
| 108 | + let reusable = iterator.state == nil | |
| 109 | + let (stream, task) = generateTask( | |
| 110 | + promptTokenCount: fed.text.tokens.size, modelConfiguration: context.configuration, | |
| 111 | + tokenizer: context.tokenizer, iterator: iterator, tools: request.tools, | |
| 112 | + toolCallPolicy: request.parameters.toolCallPolicy) | |
| 113 | + cache.started(task, prompt: prompt, reusable: reusable) | |
| 114 | + return (stream, reused) | |
| 115 | + } | |
| 116 | + } | |
| 117 | +} | |
| 118 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,118 @@ | |||
| 1 | +#if canImport(MLXLLM) | ||
| 2 | +import Foundation | ||
| 3 | +import MLX | ||
| 4 | +import MLXLMCommon | ||
| 5 | +import RazorbillCore | ||
| 6 | + | ||
| 7 | +/// One conversation. Each call renders the whole history with the chat template and generates | ||
| 8 | +/// from the model's ``PromptCache``, so only the part of the prompt the cache does not already | ||
| 9 | +/// hold is computed. | ||
| 10 | +/// Callers must not send twice at the same time on one session; the server runs one request per | ||
| 11 | +/// model at a time (ticket #34). | ||
| 12 | +final class MLXSession: EngineSession, @unchecked Sendable { | ||
| 13 | + /// What every generation of this session uses. | ||
| 14 | + struct Request: Sendable { | ||
| 15 | + let parameters: GenerateParameters | ||
| 16 | + let components: GenerationComponents | ||
| 17 | + let tools: [MLXLMCommon.ToolSpec]? | ||
| 18 | + let templateContext: [String: any Sendable] | ||
| 19 | + } | ||
| 20 | + | ||
| 21 | + private let container: ModelContainer | ||
| 22 | + private let cache: PromptCache | ||
| 23 | + private let request: Request | ||
| 24 | + private let startsInsideThinking: Bool | ||
| 25 | + private let lock = NSLock() | ||
| 26 | + private var history: [ChatMessage] | ||
| 27 | + | ||
| 28 | + init( | ||
| 29 | + container: ModelContainer, cache: PromptCache, request: Request, system: String, | ||
| 30 | + startsInsideThinking: Bool | ||
| 31 | + ) { | ||
| 32 | + self.container = container | ||
| 33 | + self.cache = cache | ||
| 34 | + self.request = request | ||
| 35 | + self.startsInsideThinking = startsInsideThinking | ||
| 36 | + self.history = system.isEmpty ? [] : [ChatMessage(role: .system, content: system)] | ||
| 37 | + } | ||
| 38 | + | ||
| 39 | + func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 40 | + AsyncThrowingStream { continuation in | ||
| 41 | + let task = Task { | ||
| 42 | + do { | ||
| 43 | + let answer = try await self.answer(messages, into: continuation) | ||
| 44 | + self.lock.withLock { self.history.append(.assistant(answer)) } | ||
| 45 | + continuation.finish() | ||
| 46 | + } catch { | ||
| 47 | + continuation.finish(throwing: error) | ||
| 48 | + } | ||
| 49 | + } | ||
| 50 | + continuation.onTermination = { _ in task.cancel() } | ||
| 51 | + } | ||
| 52 | + } | ||
| 53 | + | ||
| 54 | + /// Streams the events of the answer to `messages` into `continuation`; returns its text. | ||
| 55 | + private func answer( | ||
| 56 | + _ messages: [ChatMessage], | ||
| 57 | + into continuation: AsyncThrowingStream<EngineEvent, Error>.Continuation | ||
| 58 | + ) async throws -> String { | ||
| 59 | + let conversation = lock.withLock { | ||
| 60 | + history += messages | ||
| 61 | + return history | ||
| 62 | + } | ||
| 63 | + var splitter = ThinkingSplitter(startsInsideThinking: startsInsideThinking) | ||
| 64 | + var text = "" | ||
| 65 | + let (generations, reused) = try await start(conversation) | ||
| 66 | + for await generation in generations { | ||
| 67 | + try Task.checkCancellation() | ||
| 68 | + let events = MLXConversion.events( | ||
| 69 | + generation, splitter: &splitter, cachedPromptTokens: reused) | ||
| 70 | + text += Self.yield(events, to: continuation) | ||
| 71 | + } | ||
| 72 | + return text + Self.yield(splitter.finish(), to: continuation) | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + /// Passes `events` on and returns the answer text they carry. | ||
| 76 | + private static func yield( | ||
| 77 | + _ events: [EngineEvent], to continuation: AsyncThrowingStream<EngineEvent, Error>.Continuation | ||
| 78 | + ) -> String { | ||
| 79 | + var text = "" | ||
| 80 | + for event in events { | ||
| 81 | + if case .text(let piece) = event { text += piece } | ||
| 82 | + continuation.yield(event) | ||
| 83 | + } | ||
| 84 | + return text | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + /// Renders `conversation`, takes what the prompt cache already holds of it, and starts the | ||
| 88 | + /// generation. Returns its events and the number of prompt tokens taken from the cache. | ||
| 89 | + private func start( | ||
| 90 | + _ conversation: [ChatMessage] | ||
| 91 | + ) async throws -> (AsyncStream<Generation>, Int) { | ||
| 92 | + let request = request | ||
| 93 | + let cache = cache | ||
| 94 | + return try await container.perform(values: conversation) { context, conversation in | ||
| 95 | + let input = try await context.processor.prepare( | ||
| 96 | + input: UserInput( | ||
| 97 | + chat: conversation.map(MLXConversion.message), tools: request.tools, | ||
| 98 | + additionalContext: request.templateContext)) | ||
| 99 | + let prompt = input.text.tokens.asArray(Int.self) | ||
| 100 | + let (kvCache, reused) = try await cache.checkout( | ||
| 101 | + prompt, model: context.model, parameters: request.parameters) | ||
| 102 | + let fed = reused == 0 ? input : LMInput(tokens: MLXArray(Array(prompt[reused...]))) | ||
| 103 | + let iterator = try TokenIterator( | ||
| 104 | + input: fed, model: context.model, cache: kvCache, parameters: request.parameters, | ||
| 105 | + components: request.components) | ||
| 106 | + // Models that carry state between calls (positions of multimodal models) cannot | ||
| 107 | + // resume from the cache alone. | ||
| 108 | + let reusable = iterator.state == nil | ||
| 109 | + let (stream, task) = generateTask( | ||
| 110 | + promptTokenCount: fed.text.tokens.size, modelConfiguration: context.configuration, | ||
| 111 | + tokenizer: context.tokenizer, iterator: iterator, tools: request.tools, | ||
| 112 | + toolCallPolicy: request.parameters.toolCallPolicy) | ||
| 113 | + cache.started(task, prompt: prompt, reusable: reusable) | ||
| 114 | + return (stream, reused) | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | +} | ||
| 118 | +#endif | ||
added
Sources/RazorbillMLX/PromptCache.swift +69 -0 | new file mode 100644 | ||
| @@ -0,0 +1,69 @@ | ||
| 1 | +#if canImport(MLXLLM) | |
| 2 | +import Foundation | |
| 3 | +import MLXLMCommon | |
| 4 | +import RazorbillCore | |
| 5 | + | |
| 6 | +/// The KV cache of the last chat request on one model, kept for the next request. | |
| 7 | +/// | |
| 8 | +/// It holds the prompt's tokens and, after them, the tokens generated for it. An OpenAI client | |
| 9 | +/// resends the whole conversation, so the next prompt usually starts with the same tokens: the | |
| 10 | +/// cache is cut back to the shared start (``PromptPrefix``) and only the rest of the prompt is | |
| 11 | +/// computed. A cache that cannot be cut (recurrent state of hybrid models, a sliding window that | |
| 12 | +/// has wrapped) is replaced by an empty one. | |
| 13 | +/// | |
| 14 | +/// Requests on one model run one at a time (the model manager's queue); ``checkout(_:model:parameters:)`` | |
| 15 | +/// still waits for the previous generation to stop writing into the cache, since a cancelled | |
| 16 | +/// one can take a moment to notice. | |
| 17 | +final class PromptCache: @unchecked Sendable { | |
| 18 | + private let lock = NSLock() | |
| 19 | + private var cache: [KVCache] = [] | |
| 20 | + /// The prompt `cache` was built from; empty when its content is not known, so never reused. | |
| 21 | + private var prompt: [Int] = [] | |
| 22 | + private var generation: Task<Void, Never>? | |
| 23 | + | |
| 24 | + /// A cache that already holds the first `reused` tokens of `prompt`. | |
| 25 | + func checkout( | |
| 26 | + _ prompt: [Int], model: any LanguageModel, parameters: GenerateParameters | |
| 27 | + ) async throws -> (cache: [KVCache], reused: Int) { | |
| 28 | + if let running = lock.withLock({ generation }) { | |
| 29 | + await running.value | |
| 30 | + } | |
| 31 | + let (cache, previous) = lock.withLock { | |
| 32 | + // Unknown until the next generation starts: a failure in between must not leave a | |
| 33 | + // cache that looks reusable. | |
| 34 | + defer { self.prompt = [] } | |
| 35 | + return (self.cache, self.prompt) | |
| 36 | + } | |
| 37 | + let reuse = PromptPrefix( | |
| 38 | + prompt: prompt, previous: previous, cachedLength: cache.map(\.offset).max() ?? 0) | |
| 39 | + if reuse.keep > 0, Self.trim(cache, by: reuse.trim) { | |
| 40 | + return (cache, reuse.keep) | |
| 41 | + } | |
| 42 | + let fresh = try model.newCache(parameters: parameters) | |
| 43 | + lock.withLock { self.cache = fresh } | |
| 44 | + return (fresh, 0) | |
| 45 | + } | |
| 46 | + | |
| 47 | + /// `task` writes the answer to `prompt` into the cache returned by the last checkout. | |
| 48 | + /// `reusable` is false when the model carries state the cache alone does not restore. | |
| 49 | + func started(_ task: Task<Void, Never>, prompt: [Int], reusable: Bool) { | |
| 50 | + lock.withLock { | |
| 51 | + generation = task | |
| 52 | + self.prompt = reusable ? prompt : [] | |
| 53 | + } | |
| 54 | + } | |
| 55 | + | |
| 56 | + /// Frees the cache (the model is being unloaded or replaced). | |
| 57 | + func clear() { | |
| 58 | + lock.withLock { | |
| 59 | + cache = [] | |
| 60 | + prompt = [] | |
| 61 | + generation = nil | |
| 62 | + } | |
| 63 | + } | |
| 64 | + | |
| 65 | + private static func trim(_ cache: [KVCache], by count: Int) -> Bool { | |
| 66 | + count == 0 || (canTrimPromptCache(cache) && trimPromptCache(cache, numTokens: count) == count) | |
| 67 | + } | |
| 68 | +} | |
| 69 | +#endif | |
| new file mode 100644 | |||
| @@ -0,0 +1,69 @@ | |||
| 1 | +#if canImport(MLXLLM) | ||
| 2 | +import Foundation | ||
| 3 | +import MLXLMCommon | ||
| 4 | +import RazorbillCore | ||
| 5 | + | ||
| 6 | +/// The KV cache of the last chat request on one model, kept for the next request. | ||
| 7 | +/// | ||
| 8 | +/// It holds the prompt's tokens and, after them, the tokens generated for it. An OpenAI client | ||
| 9 | +/// resends the whole conversation, so the next prompt usually starts with the same tokens: the | ||
| 10 | +/// cache is cut back to the shared start (``PromptPrefix``) and only the rest of the prompt is | ||
| 11 | +/// computed. A cache that cannot be cut (recurrent state of hybrid models, a sliding window that | ||
| 12 | +/// has wrapped) is replaced by an empty one. | ||
| 13 | +/// | ||
| 14 | +/// Requests on one model run one at a time (the model manager's queue); ``checkout(_:model:parameters:)`` | ||
| 15 | +/// still waits for the previous generation to stop writing into the cache, since a cancelled | ||
| 16 | +/// one can take a moment to notice. | ||
| 17 | +final class PromptCache: @unchecked Sendable { | ||
| 18 | + private let lock = NSLock() | ||
| 19 | + private var cache: [KVCache] = [] | ||
| 20 | + /// The prompt `cache` was built from; empty when its content is not known, so never reused. | ||
| 21 | + private var prompt: [Int] = [] | ||
| 22 | + private var generation: Task<Void, Never>? | ||
| 23 | + | ||
| 24 | + /// A cache that already holds the first `reused` tokens of `prompt`. | ||
| 25 | + func checkout( | ||
| 26 | + _ prompt: [Int], model: any LanguageModel, parameters: GenerateParameters | ||
| 27 | + ) async throws -> (cache: [KVCache], reused: Int) { | ||
| 28 | + if let running = lock.withLock({ generation }) { | ||
| 29 | + await running.value | ||
| 30 | + } | ||
| 31 | + let (cache, previous) = lock.withLock { | ||
| 32 | + // Unknown until the next generation starts: a failure in between must not leave a | ||
| 33 | + // cache that looks reusable. | ||
| 34 | + defer { self.prompt = [] } | ||
| 35 | + return (self.cache, self.prompt) | ||
| 36 | + } | ||
| 37 | + let reuse = PromptPrefix( | ||
| 38 | + prompt: prompt, previous: previous, cachedLength: cache.map(\.offset).max() ?? 0) | ||
| 39 | + if reuse.keep > 0, Self.trim(cache, by: reuse.trim) { | ||
| 40 | + return (cache, reuse.keep) | ||
| 41 | + } | ||
| 42 | + let fresh = try model.newCache(parameters: parameters) | ||
| 43 | + lock.withLock { self.cache = fresh } | ||
| 44 | + return (fresh, 0) | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /// `task` writes the answer to `prompt` into the cache returned by the last checkout. | ||
| 48 | + /// `reusable` is false when the model carries state the cache alone does not restore. | ||
| 49 | + func started(_ task: Task<Void, Never>, prompt: [Int], reusable: Bool) { | ||
| 50 | + lock.withLock { | ||
| 51 | + generation = task | ||
| 52 | + self.prompt = reusable ? prompt : [] | ||
| 53 | + } | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + /// Frees the cache (the model is being unloaded or replaced). | ||
| 57 | + func clear() { | ||
| 58 | + lock.withLock { | ||
| 59 | + cache = [] | ||
| 60 | + prompt = [] | ||
| 61 | + generation = nil | ||
| 62 | + } | ||
| 63 | + } | ||
| 64 | + | ||
| 65 | + private static func trim(_ cache: [KVCache], by count: Int) -> Bool { | ||
| 66 | + count == 0 || (canTrimPromptCache(cache) && trimPromptCache(cache, numTokens: count) == count) | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | +#endif | ||
modified
Sources/RazorbillServer/Chat/ChatCompletionChunk.swift +1 -2 | @@ -156,8 +156,7 @@ extension ChatCompletionRoute { | ||
| 156 | 156 | do { |
| 157 | 157 | for try await piece in pieces { |
| 158 | 158 | if case .finished(let reason, let usage) = piece { |
| 159 | - outcome = | |
| 160 | - "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | |
| 159 | + outcome = "\(reason.rawValue) \(usage.logDescription)" | |
| 161 | 160 | } |
| 162 | 161 | for chunk in builder.chunks(for: piece) { continuation.yield(chunk) } |
| 163 | 162 | } |
| @@ -156,8 +156,7 @@ extension ChatCompletionRoute { | |||
| 156 | do { | 156 | do { |
| 157 | for try await piece in pieces { | 157 | for try await piece in pieces { |
| 158 | if case .finished(let reason, let usage) = piece { | 158 | if case .finished(let reason, let usage) = piece { |
| 159 | - outcome = | 159 | + outcome = "\(reason.rawValue) \(usage.logDescription)" |
| 160 | - "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | ||
| 161 | } | 160 | } |
| 162 | for chunk in builder.chunks(for: piece) { continuation.yield(chunk) } | 161 | for chunk in builder.chunks(for: piece) { continuation.yield(chunk) } |
| 163 | } | 162 | } |
modified
Sources/RazorbillServer/Chat/ChatCompletionRoute.swift +2 -1 | @@ -93,7 +93,8 @@ struct ChatCompletionRoute { | ||
| 93 | 93 | let response = try await complete(plan) |
| 94 | 94 | context.usage.record( |
| 95 | 95 | model: plan.model, promptTokens: response.usage.promptTokens, |
| 96 | - completionTokens: response.usage.completionTokens) | |
| 96 | + completionTokens: response.usage.completionTokens, | |
| 97 | + cachedTokens: response.usage.cachedTokens) | |
| 97 | 98 | return try jsonResponse(response) |
| 98 | 99 | } |
| 99 | 100 | |
| @@ -93,7 +93,8 @@ struct ChatCompletionRoute { | |||
| 93 | let response = try await complete(plan) | 93 | let response = try await complete(plan) |
| 94 | context.usage.record( | 94 | context.usage.record( |
| 95 | model: plan.model, promptTokens: response.usage.promptTokens, | 95 | model: plan.model, promptTokens: response.usage.promptTokens, |
| 96 | - completionTokens: response.usage.completionTokens) | 96 | + completionTokens: response.usage.completionTokens, |
| 97 | + cachedTokens: response.usage.cachedTokens) | ||
| 97 | return try jsonResponse(response) | 98 | return try jsonResponse(response) |
| 98 | } | 99 | } |
| 99 | 100 | ||
modified
Sources/RazorbillServer/Chat/CompletionStream.swift +16 -1 | @@ -11,16 +11,26 @@ enum FinishReason: String, Encodable, Sendable { | ||
| 11 | 11 | /// Token counts of one answer. |
| 12 | 12 | /// `completion_tokens_details.reasoning_tokens` is written only when the model thought; it counts |
| 13 | 13 | /// the pieces of reasoning received (about one per token), since MLX reports no separate count. |
| 14 | +/// `prompt_tokens_details.cached_tokens` is written only when part of the prompt came from the | |
| 15 | +/// cache of the previous request. | |
| 14 | 16 | struct Usage: Encodable, Equatable, Sendable { |
| 15 | 17 | let promptTokens: Int |
| 16 | 18 | let completionTokens: Int |
| 17 | 19 | var reasoningTokens = 0 |
| 20 | + var cachedTokens = 0 | |
| 18 | 21 | var totalTokens: Int { promptTokens + completionTokens } |
| 19 | 22 | |
| 23 | + /// `tokens=4108+64 cached=4078` (no `cached=` when nothing was reused), for the request log. | |
| 24 | + var logDescription: String { | |
| 25 | + "tokens=\(promptTokens)+\(completionTokens)" | |
| 26 | + + (cachedTokens > 0 ? " cached=\(cachedTokens)" : "") | |
| 27 | + } | |
| 28 | + | |
| 20 | 29 | enum CodingKeys: String, CodingKey { |
| 21 | 30 | case promptTokens = "prompt_tokens" |
| 22 | 31 | case completionTokens = "completion_tokens" |
| 23 | 32 | case totalTokens = "total_tokens" |
| 33 | + case promptDetails = "prompt_tokens_details" | |
| 24 | 34 | case details = "completion_tokens_details" |
| 25 | 35 | } |
| 26 | 36 | |
| @@ -29,6 +39,9 @@ struct Usage: Encodable, Equatable, Sendable { | ||
| 29 | 39 | try container.encode(promptTokens, forKey: .promptTokens) |
| 30 | 40 | try container.encode(completionTokens, forKey: .completionTokens) |
| 31 | 41 | try container.encode(totalTokens, forKey: .totalTokens) |
| 42 | + if cachedTokens > 0 { | |
| 43 | + try container.encode(["cached_tokens": cachedTokens], forKey: .promptDetails) | |
| 44 | + } | |
| 32 | 45 | if reasoningTokens > 0 { |
| 33 | 46 | try container.encode(["reasoning_tokens": reasoningTokens], forKey: .details) |
| 34 | 47 | } |
| @@ -129,7 +142,9 @@ enum CompletionStream { | ||
| 129 | 142 | } |
| 130 | 143 | var usage = |
| 131 | 144 | stats.map { |
| 132 | - Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens) | |
| 145 | + Usage( | |
| 146 | + promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens, | |
| 147 | + cachedTokens: $0.cachedPromptTokens) | |
| 133 | 148 | } |
| 134 | 149 | ?? Usage(promptTokens: 0, completionTokens: textPieces) |
| 135 | 150 | usage.reasoningTokens = reasoningPieces |
| @@ -11,16 +11,26 @@ enum FinishReason: String, Encodable, Sendable { | |||
| 11 | /// Token counts of one answer. | 11 | /// Token counts of one answer. |
| 12 | /// `completion_tokens_details.reasoning_tokens` is written only when the model thought; it counts | 12 | /// `completion_tokens_details.reasoning_tokens` is written only when the model thought; it counts |
| 13 | /// the pieces of reasoning received (about one per token), since MLX reports no separate count. | 13 | /// the pieces of reasoning received (about one per token), since MLX reports no separate count. |
| 14 | +/// `prompt_tokens_details.cached_tokens` is written only when part of the prompt came from the | ||
| 15 | +/// cache of the previous request. | ||
| 14 | struct Usage: Encodable, Equatable, Sendable { | 16 | struct Usage: Encodable, Equatable, Sendable { |
| 15 | let promptTokens: Int | 17 | let promptTokens: Int |
| 16 | let completionTokens: Int | 18 | let completionTokens: Int |
| 17 | var reasoningTokens = 0 | 19 | var reasoningTokens = 0 |
| 20 | + var cachedTokens = 0 | ||
| 18 | var totalTokens: Int { promptTokens + completionTokens } | 21 | var totalTokens: Int { promptTokens + completionTokens } |
| 19 | 22 | ||
| 23 | + /// `tokens=4108+64 cached=4078` (no `cached=` when nothing was reused), for the request log. | ||
| 24 | + var logDescription: String { | ||
| 25 | + "tokens=\(promptTokens)+\(completionTokens)" | ||
| 26 | + + (cachedTokens > 0 ? " cached=\(cachedTokens)" : "") | ||
| 27 | + } | ||
| 28 | + | ||
| 20 | enum CodingKeys: String, CodingKey { | 29 | enum CodingKeys: String, CodingKey { |
| 21 | case promptTokens = "prompt_tokens" | 30 | case promptTokens = "prompt_tokens" |
| 22 | case completionTokens = "completion_tokens" | 31 | case completionTokens = "completion_tokens" |
| 23 | case totalTokens = "total_tokens" | 32 | case totalTokens = "total_tokens" |
| 33 | + case promptDetails = "prompt_tokens_details" | ||
| 24 | case details = "completion_tokens_details" | 34 | case details = "completion_tokens_details" |
| 25 | } | 35 | } |
| 26 | 36 | ||
| @@ -29,6 +39,9 @@ struct Usage: Encodable, Equatable, Sendable { | |||
| 29 | try container.encode(promptTokens, forKey: .promptTokens) | 39 | try container.encode(promptTokens, forKey: .promptTokens) |
| 30 | try container.encode(completionTokens, forKey: .completionTokens) | 40 | try container.encode(completionTokens, forKey: .completionTokens) |
| 31 | try container.encode(totalTokens, forKey: .totalTokens) | 41 | try container.encode(totalTokens, forKey: .totalTokens) |
| 42 | + if cachedTokens > 0 { | ||
| 43 | + try container.encode(["cached_tokens": cachedTokens], forKey: .promptDetails) | ||
| 44 | + } | ||
| 32 | if reasoningTokens > 0 { | 45 | if reasoningTokens > 0 { |
| 33 | try container.encode(["reasoning_tokens": reasoningTokens], forKey: .details) | 46 | try container.encode(["reasoning_tokens": reasoningTokens], forKey: .details) |
| 34 | } | 47 | } |
| @@ -129,7 +142,9 @@ enum CompletionStream { | |||
| 129 | } | 142 | } |
| 130 | var usage = | 143 | var usage = |
| 131 | stats.map { | 144 | stats.map { |
| 132 | - Usage(promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens) | 145 | + Usage( |
| 146 | + promptTokens: $0.promptTokens, completionTokens: $0.generatedTokens, | ||
| 147 | + cachedTokens: $0.cachedPromptTokens) | ||
| 133 | } | 148 | } |
| 134 | ?? Usage(promptTokens: 0, completionTokens: textPieces) | 149 | ?? Usage(promptTokens: 0, completionTokens: textPieces) |
| 135 | usage.reasoningTokens = reasoningPieces | 150 | usage.reasoningTokens = reasoningPieces |
modified
Sources/RazorbillServer/CompletionsRoute.swift +1 -2 | @@ -245,8 +245,7 @@ struct CompletionsRoute { | ||
| 245 | 245 | switch piece { |
| 246 | 246 | case .content(let text): continuation.yield(chunk(text)) |
| 247 | 247 | case .finished(let reason, let usage): |
| 248 | - outcome = | |
| 249 | - "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | |
| 248 | + outcome = "\(reason.rawValue) \(usage.logDescription)" | |
| 250 | 249 | continuation.yield(chunk("", reason)) |
| 251 | 250 | if plan.includeUsage { |
| 252 | 251 | continuation.yield( |
| @@ -245,8 +245,7 @@ struct CompletionsRoute { | |||
| 245 | switch piece { | 245 | switch piece { |
| 246 | case .content(let text): continuation.yield(chunk(text)) | 246 | case .content(let text): continuation.yield(chunk(text)) |
| 247 | case .finished(let reason, let usage): | 247 | case .finished(let reason, let usage): |
| 248 | - outcome = | 248 | + outcome = "\(reason.rawValue) \(usage.logDescription)" |
| 249 | - "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | ||
| 250 | continuation.yield(chunk("", reason)) | 249 | continuation.yield(chunk("", reason)) |
| 251 | if plan.includeUsage { | 250 | if plan.includeUsage { |
| 252 | continuation.yield( | 251 | continuation.yield( |
modified
Sources/RazorbillServer/ServerContext.swift +17 -4 | @@ -33,26 +33,39 @@ public struct ServerContext: RequestContext { | ||
| 33 | 33 | public final class RequestUsage: @unchecked Sendable { |
| 34 | 34 | private let lock = NSLock() |
| 35 | 35 | private var storedModel: String? |
| 36 | - private var storedTokens: (prompt: Int, completion: Int)? | |
| 36 | + private var storedTokens: Tokens? | |
| 37 | + | |
| 38 | + private struct Tokens { | |
| 39 | + let prompt: Int | |
| 40 | + let completion: Int | |
| 41 | + let cached: Int | |
| 42 | + } | |
| 37 | 43 | |
| 38 | 44 | public init() {} |
| 39 | 45 | |
| 40 | - public func record(model: String, promptTokens: Int? = nil, completionTokens: Int? = nil) { | |
| 46 | + /// `cachedTokens`: prompt tokens reused from the previous request's cache. | |
| 47 | + public func record( | |
| 48 | + model: String, promptTokens: Int? = nil, completionTokens: Int? = nil, | |
| 49 | + cachedTokens: Int = 0 | |
| 50 | + ) { | |
| 41 | 51 | lock.withLock { |
| 42 | 52 | storedModel = model |
| 43 | 53 | if let promptTokens, let completionTokens { |
| 44 | - storedTokens = (promptTokens, completionTokens) | |
| 54 | + storedTokens = Tokens( | |
| 55 | + prompt: promptTokens, completion: completionTokens, cached: cachedTokens) | |
| 45 | 56 | } |
| 46 | 57 | } |
| 47 | 58 | } |
| 48 | 59 | |
| 49 | - /// ` model=qwen3 tokens=12+40`, or an empty string when nothing was recorded. | |
| 60 | + /// ` model=qwen3 tokens=12+40` (plus ` cached=8` when the prompt reused a cache), or an | |
| 61 | + /// empty string when nothing was recorded. | |
| 50 | 62 | var logSuffix: String { |
| 51 | 63 | lock.withLock { |
| 52 | 64 | var suffix = "" |
| 53 | 65 | if let storedModel { suffix += " model=\(storedModel)" } |
| 54 | 66 | if let storedTokens { |
| 55 | 67 | suffix += " tokens=\(storedTokens.prompt)+\(storedTokens.completion)" |
| 68 | + if storedTokens.cached > 0 { suffix += " cached=\(storedTokens.cached)" } | |
| 56 | 69 | } |
| 57 | 70 | return suffix |
| 58 | 71 | } |
| @@ -33,26 +33,39 @@ public struct ServerContext: RequestContext { | |||
| 33 | public final class RequestUsage: @unchecked Sendable { | 33 | public final class RequestUsage: @unchecked Sendable { |
| 34 | private let lock = NSLock() | 34 | private let lock = NSLock() |
| 35 | private var storedModel: String? | 35 | private var storedModel: String? |
| 36 | - private var storedTokens: (prompt: Int, completion: Int)? | 36 | + private var storedTokens: Tokens? |
| 37 | + | ||
| 38 | + private struct Tokens { | ||
| 39 | + let prompt: Int | ||
| 40 | + let completion: Int | ||
| 41 | + let cached: Int | ||
| 42 | + } | ||
| 37 | 43 | ||
| 38 | public init() {} | 44 | public init() {} |
| 39 | 45 | ||
| 40 | - public func record(model: String, promptTokens: Int? = nil, completionTokens: Int? = nil) { | 46 | + /// `cachedTokens`: prompt tokens reused from the previous request's cache. |
| 47 | + public func record( | ||
| 48 | + model: String, promptTokens: Int? = nil, completionTokens: Int? = nil, | ||
| 49 | + cachedTokens: Int = 0 | ||
| 50 | + ) { | ||
| 41 | lock.withLock { | 51 | lock.withLock { |
| 42 | storedModel = model | 52 | storedModel = model |
| 43 | if let promptTokens, let completionTokens { | 53 | if let promptTokens, let completionTokens { |
| 44 | - storedTokens = (promptTokens, completionTokens) | 54 | + storedTokens = Tokens( |
| 55 | + prompt: promptTokens, completion: completionTokens, cached: cachedTokens) | ||
| 45 | } | 56 | } |
| 46 | } | 57 | } |
| 47 | } | 58 | } |
| 48 | 59 | ||
| 49 | - /// ` model=qwen3 tokens=12+40`, or an empty string when nothing was recorded. | 60 | + /// ` model=qwen3 tokens=12+40` (plus ` cached=8` when the prompt reused a cache), or an |
| 61 | + /// empty string when nothing was recorded. | ||
| 50 | var logSuffix: String { | 62 | var logSuffix: String { |
| 51 | lock.withLock { | 63 | lock.withLock { |
| 52 | var suffix = "" | 64 | var suffix = "" |
| 53 | if let storedModel { suffix += " model=\(storedModel)" } | 65 | if let storedModel { suffix += " model=\(storedModel)" } |
| 54 | if let storedTokens { | 66 | if let storedTokens { |
| 55 | suffix += " tokens=\(storedTokens.prompt)+\(storedTokens.completion)" | 67 | suffix += " tokens=\(storedTokens.prompt)+\(storedTokens.completion)" |
| 68 | + if storedTokens.cached > 0 { suffix += " cached=\(storedTokens.cached)" } | ||
| 56 | } | 69 | } |
| 57 | return suffix | 70 | return suffix |
| 58 | } | 71 | } |
added
Tests/RazorbillCoreTests/PromptPrefixTests.swift +37 -0 | new file mode 100644 | ||
| @@ -0,0 +1,37 @@ | ||
| 1 | +import Testing | |
| 2 | + | |
| 3 | +@testable import RazorbillCore | |
| 4 | + | |
| 5 | +struct PromptPrefixTests { | |
| 6 | + @Test func keepsTheSharedPromptAndDropsTheGeneratedTokens() { | |
| 7 | + let reuse = PromptPrefix(prompt: [1, 2, 3, 7, 8], previous: [1, 2, 3], cachedLength: 6) | |
| 8 | + #expect(reuse == PromptPrefix(keep: 3, trim: 3)) | |
| 9 | + } | |
| 10 | + | |
| 11 | + @Test func stopsAtTheFirstDifferentToken() { | |
| 12 | + let reuse = PromptPrefix(prompt: [1, 2, 5, 6], previous: [1, 2, 3, 4], cachedLength: 4) | |
| 13 | + #expect(reuse == PromptPrefix(keep: 2, trim: 2)) | |
| 14 | + } | |
| 15 | + | |
| 16 | + @Test func leavesOneTokenToCompute() { | |
| 17 | + let reuse = PromptPrefix(prompt: [1, 2, 3], previous: [1, 2, 3], cachedLength: 5) | |
| 18 | + #expect(reuse == PromptPrefix(keep: 2, trim: 3)) | |
| 19 | + } | |
| 20 | + | |
| 21 | + @Test func startsAfreshWhenNothingIsShared() { | |
| 22 | + #expect(PromptPrefix(prompt: [4, 5], previous: [1, 2], cachedLength: 3).keep == 0) | |
| 23 | + #expect(PromptPrefix(prompt: [4, 5], previous: [], cachedLength: 0).keep == 0) | |
| 24 | + #expect(PromptPrefix(prompt: [4], previous: [4], cachedLength: 2).keep == 0) | |
| 25 | + } | |
| 26 | + | |
| 27 | + @Test func neverKeepsMoreThanTheCacheHolds() { | |
| 28 | + let reuse = PromptPrefix(prompt: [1, 2, 3, 4], previous: [1, 2, 3], cachedLength: 2) | |
| 29 | + #expect(reuse == PromptPrefix(keep: 2, trim: 0)) | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +extension PromptPrefix { | |
| 34 | + init(keep: Int, trim: Int) { | |
| 35 | + self.init(prompt: Array(0 ... keep), previous: Array(0 ..< keep), cachedLength: keep + trim) | |
| 36 | + } | |
| 37 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,37 @@ | |||
| 1 | +import Testing | ||
| 2 | + | ||
| 3 | +@testable import RazorbillCore | ||
| 4 | + | ||
| 5 | +struct PromptPrefixTests { | ||
| 6 | + @Test func keepsTheSharedPromptAndDropsTheGeneratedTokens() { | ||
| 7 | + let reuse = PromptPrefix(prompt: [1, 2, 3, 7, 8], previous: [1, 2, 3], cachedLength: 6) | ||
| 8 | + #expect(reuse == PromptPrefix(keep: 3, trim: 3)) | ||
| 9 | + } | ||
| 10 | + | ||
| 11 | + @Test func stopsAtTheFirstDifferentToken() { | ||
| 12 | + let reuse = PromptPrefix(prompt: [1, 2, 5, 6], previous: [1, 2, 3, 4], cachedLength: 4) | ||
| 13 | + #expect(reuse == PromptPrefix(keep: 2, trim: 2)) | ||
| 14 | + } | ||
| 15 | + | ||
| 16 | + @Test func leavesOneTokenToCompute() { | ||
| 17 | + let reuse = PromptPrefix(prompt: [1, 2, 3], previous: [1, 2, 3], cachedLength: 5) | ||
| 18 | + #expect(reuse == PromptPrefix(keep: 2, trim: 3)) | ||
| 19 | + } | ||
| 20 | + | ||
| 21 | + @Test func startsAfreshWhenNothingIsShared() { | ||
| 22 | + #expect(PromptPrefix(prompt: [4, 5], previous: [1, 2], cachedLength: 3).keep == 0) | ||
| 23 | + #expect(PromptPrefix(prompt: [4, 5], previous: [], cachedLength: 0).keep == 0) | ||
| 24 | + #expect(PromptPrefix(prompt: [4], previous: [4], cachedLength: 2).keep == 0) | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + @Test func neverKeepsMoreThanTheCacheHolds() { | ||
| 28 | + let reuse = PromptPrefix(prompt: [1, 2, 3, 4], previous: [1, 2, 3], cachedLength: 2) | ||
| 29 | + #expect(reuse == PromptPrefix(keep: 2, trim: 0)) | ||
| 30 | + } | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +extension PromptPrefix { | ||
| 34 | + init(keep: Int, trim: Int) { | ||
| 35 | + self.init(prompt: Array(0 ... keep), previous: Array(0 ..< keep), cachedLength: keep + trim) | ||
| 36 | + } | ||
| 37 | +} | ||
modified
Tests/RazorbillMLXTests/ChatSmokeTests.swift +26 -0 | @@ -99,6 +99,32 @@ struct ChatSmokeTests { | ||
| 99 | 99 | #expect(budgeted.choices.first?.message.content?.isEmpty == false) |
| 100 | 100 | } |
| 101 | 101 | |
| 102 | + /// A client resends the conversation: the second request takes the shared start from the | |
| 103 | + /// cache of the first, and answers exactly as a fresh engine does. | |
| 104 | + @Test func secondTurnReusesTheCacheWithTheSameAnswer() async throws { | |
| 105 | + let first = plan("What is the capital of France?") | |
| 106 | + let answer = try await route().complete(first) | |
| 107 | + var second = first | |
| 108 | + second.messages += [ | |
| 109 | + .assistant(answer.choices.first?.message.content ?? ""), | |
| 110 | + .user("And the capital of Italy?"), | |
| 111 | + ] | |
| 112 | + let warm = try await route().complete(second) | |
| 113 | + #expect(warm.usage.cachedTokens > 10) | |
| 114 | + #expect(warm.usage.cachedTokens < warm.usage.promptTokens) | |
| 115 | + | |
| 116 | + let fresh = ModelManager( | |
| 117 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), | |
| 118 | + limits: ServerLimits() | |
| 119 | + ) { _ in MLXEngine() } | |
| 120 | + let cold = try await ChatCompletionRoute(models: fresh).complete(second) | |
| 121 | + await fresh.unloadAll() | |
| 122 | + #expect(cold.usage.cachedTokens == 0) | |
| 123 | + #expect(cold.usage.promptTokens == warm.usage.promptTokens) | |
| 124 | + #expect(cold.choices.first?.message.content == warm.choices.first?.message.content) | |
| 125 | + #expect(warm.choices.first?.message.content?.contains("Rome") == true) | |
| 126 | + } | |
| 127 | + | |
| 102 | 128 | @Test func tokenLimitGivesLength() async throws { |
| 103 | 129 | let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8)) |
| 104 | 130 | #expect(response.choices.first?.finishReason == .length) |
| @@ -99,6 +99,32 @@ struct ChatSmokeTests { | |||
| 99 | #expect(budgeted.choices.first?.message.content?.isEmpty == false) | 99 | #expect(budgeted.choices.first?.message.content?.isEmpty == false) |
| 100 | } | 100 | } |
| 101 | 101 | ||
| 102 | + /// A client resends the conversation: the second request takes the shared start from the | ||
| 103 | + /// cache of the first, and answers exactly as a fresh engine does. | ||
| 104 | + @Test func secondTurnReusesTheCacheWithTheSameAnswer() async throws { | ||
| 105 | + let first = plan("What is the capital of France?") | ||
| 106 | + let answer = try await route().complete(first) | ||
| 107 | + var second = first | ||
| 108 | + second.messages += [ | ||
| 109 | + .assistant(answer.choices.first?.message.content ?? ""), | ||
| 110 | + .user("And the capital of Italy?"), | ||
| 111 | + ] | ||
| 112 | + let warm = try await route().complete(second) | ||
| 113 | + #expect(warm.usage.cachedTokens > 10) | ||
| 114 | + #expect(warm.usage.cachedTokens < warm.usage.promptTokens) | ||
| 115 | + | ||
| 116 | + let fresh = ModelManager( | ||
| 117 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), | ||
| 118 | + limits: ServerLimits() | ||
| 119 | + ) { _ in MLXEngine() } | ||
| 120 | + let cold = try await ChatCompletionRoute(models: fresh).complete(second) | ||
| 121 | + await fresh.unloadAll() | ||
| 122 | + #expect(cold.usage.cachedTokens == 0) | ||
| 123 | + #expect(cold.usage.promptTokens == warm.usage.promptTokens) | ||
| 124 | + #expect(cold.choices.first?.message.content == warm.choices.first?.message.content) | ||
| 125 | + #expect(warm.choices.first?.message.content?.contains("Rome") == true) | ||
| 126 | + } | ||
| 127 | + | ||
| 102 | @Test func tokenLimitGivesLength() async throws { | 128 | @Test func tokenLimitGivesLength() async throws { |
| 103 | let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8)) | 129 | let response = try await route().complete(plan("Count from 1 to 100.", maxTokens: 8)) |
| 104 | #expect(response.choices.first?.finishReason == .length) | 130 | #expect(response.choices.first?.finishReason == .length) |
modified
Tests/RazorbillServerTests/ChatCompletionTests.swift +22 -0 | @@ -236,6 +236,28 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri | ||
| 236 | 236 | #expect(!logs.messages.contains { $0.contains("secret") }) |
| 237 | 237 | } |
| 238 | 238 | |
| 239 | + @Test func reusedPromptTokensAreReportedAndLogged() async throws { | |
| 240 | + let stats = GenerationStats( | |
| 241 | + promptTokens: 40, generatedTokens: 2, tokensPerSecond: 1, cachedPromptTokens: 32) | |
| 242 | + let engines = TestEngines(script: [[.text("Hi"), .stats(stats)]]) | |
| 243 | + let logs = LogCapture() | |
| 244 | + try await withLiveServer(logs: logs, engines: engines) { client in | |
| 245 | + let body = try json(try await post(client, simpleRequest())) | |
| 246 | + let usage = try #require(body["usage"] as? [String: Any]) | |
| 247 | + #expect(usage["prompt_tokens"] as? Int == 40) | |
| 248 | + #expect((usage["prompt_tokens_details"] as? [String: Int]) == ["cached_tokens": 32]) | |
| 249 | + } | |
| 250 | + #expect(logs.messages.contains { $0.hasSuffix("model=org/m tokens=40+2 cached=32") }) | |
| 251 | + } | |
| 252 | + | |
| 253 | + @Test func nothingReusedLeavesThePromptDetailsOut() async throws { | |
| 254 | + try await withLiveServer { client in | |
| 255 | + let body = try json(try await post(client, simpleRequest())) | |
| 256 | + let usage = try #require(body["usage"] as? [String: Any]) | |
| 257 | + #expect(usage["prompt_tokens_details"] == nil) | |
| 258 | + } | |
| 259 | + } | |
| 260 | + | |
| 239 | 261 | @Test func clientDisconnectCancelsTheGeneration() async throws { |
| 240 | 262 | let engines = TestEngines(hang: true) |
| 241 | 263 | try await withLiveServer(engines: engines) { client in |
| @@ -236,6 +236,28 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri | |||
| 236 | #expect(!logs.messages.contains { $0.contains("secret") }) | 236 | #expect(!logs.messages.contains { $0.contains("secret") }) |
| 237 | } | 237 | } |
| 238 | 238 | ||
| 239 | + @Test func reusedPromptTokensAreReportedAndLogged() async throws { | ||
| 240 | + let stats = GenerationStats( | ||
| 241 | + promptTokens: 40, generatedTokens: 2, tokensPerSecond: 1, cachedPromptTokens: 32) | ||
| 242 | + let engines = TestEngines(script: [[.text("Hi"), .stats(stats)]]) | ||
| 243 | + let logs = LogCapture() | ||
| 244 | + try await withLiveServer(logs: logs, engines: engines) { client in | ||
| 245 | + let body = try json(try await post(client, simpleRequest())) | ||
| 246 | + let usage = try #require(body["usage"] as? [String: Any]) | ||
| 247 | + #expect(usage["prompt_tokens"] as? Int == 40) | ||
| 248 | + #expect((usage["prompt_tokens_details"] as? [String: Int]) == ["cached_tokens": 32]) | ||
| 249 | + } | ||
| 250 | + #expect(logs.messages.contains { $0.hasSuffix("model=org/m tokens=40+2 cached=32") }) | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + @Test func nothingReusedLeavesThePromptDetailsOut() async throws { | ||
| 254 | + try await withLiveServer { client in | ||
| 255 | + let body = try json(try await post(client, simpleRequest())) | ||
| 256 | + let usage = try #require(body["usage"] as? [String: Any]) | ||
| 257 | + #expect(usage["prompt_tokens_details"] == nil) | ||
| 258 | + } | ||
| 259 | + } | ||
| 260 | + | ||
| 239 | @Test func clientDisconnectCancelsTheGeneration() async throws { | 261 | @Test func clientDisconnectCancelsTheGeneration() async throws { |
| 240 | let engines = TestEngines(hang: true) | 262 | let engines = TestEngines(hang: true) |
| 241 | try await withLiveServer(engines: engines) { client in | 263 | try await withLiveServer(engines: engines) { client in |
modified
docs/en/explanation/architecture.md +1 -1 | @@ -31,7 +31,7 @@ Everything points towards `RazorbillCore`, and `RazorbillCore` knows nothing abo | ||
| 31 | 31 | 1. Hummingbird receives `POST /v1/chat/completions`. Middlewares log it, apply CORS, check the API key, and turn any error into OpenAI's error body. |
| 32 | 32 | 2. The body is decoded and validated into a `ChatPlan`; JSON Schemas are re-read to keep their key order. With `response_format`, an instruction carrying the schema is added to the system message. |
| 33 | 33 | 3. The model manager resolves the name (declared id, or Hugging Face id), loads the model if needed, and gives the request a **lease**: one generation per model at a time, the others wait in a queue (see [model lifecycle](model-lifecycle.md)). |
| 34 | -4. The engine opens a fresh session with the request's settings and constraint, renders the conversation with the model's chat template, and streams events. | |
| 34 | +4. The engine opens a fresh session with the request's settings and constraint, renders the conversation with the model's chat template, reuses the part of the KV cache the previous request left that matches it ([why](model-lifecycle.md#reusing-the-previous-prompt)), and streams events. | |
| 35 | 35 | 5. The events become OpenAI pieces: stop sequences are applied, reasoning is separated or hidden, tool calls are numbered, and `finish_reason` and `usage` are computed. |
| 36 | 36 | 6. The pieces are gathered into one `chat.completion`, or sent as Server-Sent Events as they come. When the answer ends — or the client disconnects — the lease is released. |
| 37 | 37 | |
| @@ -31,7 +31,7 @@ Everything points towards `RazorbillCore`, and `RazorbillCore` knows nothing abo | |||
| 31 | 1. Hummingbird receives `POST /v1/chat/completions`. Middlewares log it, apply CORS, check the API key, and turn any error into OpenAI's error body. | 31 | 1. Hummingbird receives `POST /v1/chat/completions`. Middlewares log it, apply CORS, check the API key, and turn any error into OpenAI's error body. |
| 32 | 2. The body is decoded and validated into a `ChatPlan`; JSON Schemas are re-read to keep their key order. With `response_format`, an instruction carrying the schema is added to the system message. | 32 | 2. The body is decoded and validated into a `ChatPlan`; JSON Schemas are re-read to keep their key order. With `response_format`, an instruction carrying the schema is added to the system message. |
| 33 | 3. The model manager resolves the name (declared id, or Hugging Face id), loads the model if needed, and gives the request a **lease**: one generation per model at a time, the others wait in a queue (see [model lifecycle](model-lifecycle.md)). | 33 | 3. The model manager resolves the name (declared id, or Hugging Face id), loads the model if needed, and gives the request a **lease**: one generation per model at a time, the others wait in a queue (see [model lifecycle](model-lifecycle.md)). |
| 34 | -4. The engine opens a fresh session with the request's settings and constraint, renders the conversation with the model's chat template, and streams events. | 34 | +4. The engine opens a fresh session with the request's settings and constraint, renders the conversation with the model's chat template, reuses the part of the KV cache the previous request left that matches it ([why](model-lifecycle.md#reusing-the-previous-prompt)), and streams events. |
| 35 | 5. The events become OpenAI pieces: stop sequences are applied, reasoning is separated or hidden, tool calls are numbered, and `finish_reason` and `usage` are computed. | 35 | 5. The events become OpenAI pieces: stop sequences are applied, reasoning is separated or hidden, tool calls are numbered, and `finish_reason` and `usage` are computed. |
| 36 | 6. The pieces are gathered into one `chat.completion`, or sent as Server-Sent Events as they come. When the answer ends — or the client disconnects — the lease is released. | 36 | 6. The pieces are gathered into one `chat.completion`, or sent as Server-Sent Events as they come. When the answer ends — or the client disconnects — the lease is released. |
| 37 | 37 | ||
modified
docs/en/explanation/model-lifecycle.md +14 -0 | @@ -16,6 +16,18 @@ Why not run several generations of one model at once? Token generation on Apple | ||
| 16 | 16 | |
| 17 | 17 | Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues. |
| 18 | 18 | |
| 19 | +## Reusing the previous prompt | |
| 20 | + | |
| 21 | +An OpenAI client keeps no state on the server: every request carries the whole conversation, system prompt, tool definitions and earlier turns included. Before it writes the first word of an answer, a model has to read the prompt and fill its **KV cache**, which holds the attention keys and values of every token read so far. On a long conversation this reading dominates: about 25 to 30 seconds for 4,000 tokens with Qwen3-4B on the Mac used to measure it. | |
| 22 | + | |
| 23 | +The chat engine therefore keeps the KV cache of the last request on each model. That cache holds the previous prompt followed by the answer generated for it. The next request of the same conversation repeats that prompt and adds the answer, as the client received it, and a new question. The engine compares the tokens, cuts the cache back to the part both prompts share, and reads only the rest. On the same 4,000-token conversation the first word then comes in under a second. The answer is the one a fresh cache would give: with greedy decoding the two are identical, apart from the rare token where computing the prompt in different chunks changes a rounding. | |
| 24 | + | |
| 25 | +The answer itself is always read again, because the client sends back only the visible text: the reasoning of thinking models is not in it, and the chat template renders earlier turns its own way. This costs a few dozen tokens per turn. | |
| 26 | + | |
| 27 | +Some caches cannot be cut back. Hybrid models (Qwen3.5, Qwen3-Next, LFM2…) keep a recurrent state that cannot be rewound, and models with a sliding window (Gemma 3…) lose the start of a long conversation once the window has moved past it. For those the engine starts from an empty cache, as it does when the conversation changes (another client, another system prompt): only the shared start is ever reused, so a different conversation simply shares little or nothing. | |
| 28 | + | |
| 29 | +Only one conversation per model is kept. Two clients that alternate on the same model each find the other's cache and reuse only what their prompts have in common, often just the system prompt. The cache is freed with the model, and it lives in the memory left outside the weight budget, as every KV cache already did while a request was running. Responses report the reused tokens in `usage.prompt_tokens_details.cached_tokens`, and the request log adds `cached=N`. | |
| 30 | + | |
| 19 | 31 | ## Making room |
| 20 | 32 | |
| 21 | 33 | Two limits decide how many models stay loaded: |
| @@ -40,6 +52,8 @@ During a stream, a client that vanishes is noticed only when a write fails. Whil | ||
| 40 | 52 | - **One process per model** (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator. |
| 41 | 53 | - **Unloading on a memory-pressure signal from macOS** instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable. |
| 42 | 54 | - **Waiting for room instead of answering 503**: a request could wait indefinitely behind long generations; a clear error is easier to act on. |
| 55 | +- **Several cached conversations per model** (an LRU of caches, like llama-server slots or vLLM's prefix caching): more memory to account for, for a gain only when clients alternate. One cache covers the common case of one agent or one chat at a time. | |
| 56 | +- **Letting mlx-swift-lm's `ChatSession` reuse the cache**: it does, but only within one session that owns the conversation, whereas each HTTP request brings its own copy of the conversation. | |
| 43 | 57 | |
| 44 | 58 | ## How it relates to the rest |
| 45 | 59 | |
| @@ -16,6 +16,18 @@ Why not run several generations of one model at once? Token generation on Apple | |||
| 16 | 16 | ||
| 17 | Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues. | 17 | Different models do run in parallel: a chat answer and an embedding request use two different models, and therefore two different queues. |
| 18 | 18 | ||
| 19 | +## Reusing the previous prompt | ||
| 20 | + | ||
| 21 | +An OpenAI client keeps no state on the server: every request carries the whole conversation, system prompt, tool definitions and earlier turns included. Before it writes the first word of an answer, a model has to read the prompt and fill its **KV cache**, which holds the attention keys and values of every token read so far. On a long conversation this reading dominates: about 25 to 30 seconds for 4,000 tokens with Qwen3-4B on the Mac used to measure it. | ||
| 22 | + | ||
| 23 | +The chat engine therefore keeps the KV cache of the last request on each model. That cache holds the previous prompt followed by the answer generated for it. The next request of the same conversation repeats that prompt and adds the answer, as the client received it, and a new question. The engine compares the tokens, cuts the cache back to the part both prompts share, and reads only the rest. On the same 4,000-token conversation the first word then comes in under a second. The answer is the one a fresh cache would give: with greedy decoding the two are identical, apart from the rare token where computing the prompt in different chunks changes a rounding. | ||
| 24 | + | ||
| 25 | +The answer itself is always read again, because the client sends back only the visible text: the reasoning of thinking models is not in it, and the chat template renders earlier turns its own way. This costs a few dozen tokens per turn. | ||
| 26 | + | ||
| 27 | +Some caches cannot be cut back. Hybrid models (Qwen3.5, Qwen3-Next, LFM2…) keep a recurrent state that cannot be rewound, and models with a sliding window (Gemma 3…) lose the start of a long conversation once the window has moved past it. For those the engine starts from an empty cache, as it does when the conversation changes (another client, another system prompt): only the shared start is ever reused, so a different conversation simply shares little or nothing. | ||
| 28 | + | ||
| 29 | +Only one conversation per model is kept. Two clients that alternate on the same model each find the other's cache and reuse only what their prompts have in common, often just the system prompt. The cache is freed with the model, and it lives in the memory left outside the weight budget, as every KV cache already did while a request was running. Responses report the reused tokens in `usage.prompt_tokens_details.cached_tokens`, and the request log adds `cached=N`. | ||
| 30 | + | ||
| 19 | ## Making room | 31 | ## Making room |
| 20 | 32 | ||
| 21 | Two limits decide how many models stay loaded: | 33 | Two limits decide how many models stay loaded: |
| @@ -40,6 +52,8 @@ During a stream, a client that vanishes is noticed only when a write fails. Whil | |||
| 40 | - **One process per model** (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator. | 52 | - **One process per model** (as some servers do): isolation, but every model would pay the runtime's memory, and sharing limits across processes needs a coordinator. |
| 41 | - **Unloading on a memory-pressure signal from macOS** instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable. | 53 | - **Unloading on a memory-pressure signal from macOS** instead of a budget: the signal arrives late, when swapping has already started; a budget is predictable. |
| 42 | - **Waiting for room instead of answering 503**: a request could wait indefinitely behind long generations; a clear error is easier to act on. | 54 | - **Waiting for room instead of answering 503**: a request could wait indefinitely behind long generations; a clear error is easier to act on. |
| 55 | +- **Several cached conversations per model** (an LRU of caches, like llama-server slots or vLLM's prefix caching): more memory to account for, for a gain only when clients alternate. One cache covers the common case of one agent or one chat at a time. | ||
| 56 | +- **Letting mlx-swift-lm's `ChatSession` reuse the cache**: it does, but only within one session that owns the conversation, whereas each HTTP request brings its own copy of the conversation. | ||
| 43 | 57 | ||
| 44 | ## How it relates to the rest | 58 | ## How it relates to the rest |
| 45 | 59 | ||
modified
docs/en/reference/cli.md +1 -1 | @@ -38,7 +38,7 @@ config: server.yaml (2 declared models) | ||
| 38 | 38 | rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop |
| 39 | 39 | ``` |
| 40 | 40 | |
| 41 | -The first line appears only with `--config`. Warnings (`warning: …`) are printed before the banner when the server listens on a network address without an API key, or allows every CORS origin without one. Then one log line per request: method, path, status, duration, and the model and token counts (`model=… tokens=<prompt>+<completion>`); prompts and answers are never logged. | |
| 41 | +The first line appears only with `--config`. Warnings (`warning: …`) are printed before the banner when the server listens on a network address without an API key, or allows every CORS origin without one. Then one log line per request: method, path, status, duration, and the model and token counts (`model=… tokens=<prompt>+<completion>`, plus `cached=<n>` when part of the prompt was reused from the previous request); prompts and answers are never logged. | |
| 42 | 42 | |
| 43 | 43 | The engine is the first one of the build: `mlx` on the Mac, `fake` on Linux (which answers `echo: <last message>` without a model). |
| 44 | 44 | |
| @@ -38,7 +38,7 @@ config: server.yaml (2 declared models) | |||
| 38 | rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop | 38 | rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop |
| 39 | ``` | 39 | ``` |
| 40 | 40 | ||
| 41 | -The first line appears only with `--config`. Warnings (`warning: …`) are printed before the banner when the server listens on a network address without an API key, or allows every CORS origin without one. Then one log line per request: method, path, status, duration, and the model and token counts (`model=… tokens=<prompt>+<completion>`); prompts and answers are never logged. | 41 | +The first line appears only with `--config`. Warnings (`warning: …`) are printed before the banner when the server listens on a network address without an API key, or allows every CORS origin without one. Then one log line per request: method, path, status, duration, and the model and token counts (`model=… tokens=<prompt>+<completion>`, plus `cached=<n>` when part of the prompt was reused from the previous request); prompts and answers are never logged. |
| 42 | 42 | ||
| 43 | The engine is the first one of the build: `mlx` on the Mac, `fake` on Linux (which answers `echo: <last message>` without a model). | 43 | The engine is the first one of the build: `mlx` on the Mac, `fake` on Linux (which answers `echo: <last message>` without a model). |
| 44 | 44 | ||
modified
docs/en/reference/http-api.md +1 -0 | @@ -161,6 +161,7 @@ The conversation is rendered with the model's own chat template. The server keep | ||
| 161 | 161 | | `message.reasoning_content` | when the model thought and reasoning is shown | The reasoning, without the `<think>` tags | |
| 162 | 162 | | `message.tool_calls` | when the model called tools | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` a JSON string | |
| 163 | 163 | | `finish_reason` | always | `stop`, `length` (token limit) or `tool_calls` | |
| 164 | +| `usage.prompt_tokens_details.cached_tokens` | when part of the prompt was reused | Prompt tokens taken from the KV cache of the previous request instead of being read again; included in `prompt_tokens` ([why](../explanation/model-lifecycle.md#reusing-the-previous-prompt)) | | |
| 164 | 165 | | `usage.completion_tokens_details.reasoning_tokens` | when the model thought | Pieces of reasoning received (about one per token), also counted when reasoning is hidden | |
| 165 | 166 | |
| 166 | 167 | When a stop sequence ends the answer, the engine is interrupted before it reports its counts: `usage` then counts one token per piece of text and `prompt_tokens` is 0. |
| @@ -161,6 +161,7 @@ The conversation is rendered with the model's own chat template. The server keep | |||
| 161 | | `message.reasoning_content` | when the model thought and reasoning is shown | The reasoning, without the `<think>` tags | | 161 | | `message.reasoning_content` | when the model thought and reasoning is shown | The reasoning, without the `<think>` tags | |
| 162 | | `message.tool_calls` | when the model called tools | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` a JSON string | | 162 | | `message.tool_calls` | when the model called tools | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` a JSON string | |
| 163 | | `finish_reason` | always | `stop`, `length` (token limit) or `tool_calls` | | 163 | | `finish_reason` | always | `stop`, `length` (token limit) or `tool_calls` | |
| 164 | +| `usage.prompt_tokens_details.cached_tokens` | when part of the prompt was reused | Prompt tokens taken from the KV cache of the previous request instead of being read again; included in `prompt_tokens` ([why](../explanation/model-lifecycle.md#reusing-the-previous-prompt)) | | ||
| 164 | | `usage.completion_tokens_details.reasoning_tokens` | when the model thought | Pieces of reasoning received (about one per token), also counted when reasoning is hidden | | 165 | | `usage.completion_tokens_details.reasoning_tokens` | when the model thought | Pieces of reasoning received (about one per token), also counted when reasoning is hidden | |
| 165 | 166 | ||
| 166 | When a stop sequence ends the answer, the engine is interrupted before it reports its counts: `usage` then counts one token per piece of text and `prompt_tokens` is 0. | 167 | When a stop sequence ends the answer, the engine is interrupted before it reports its counts: `usage` then counts one token per piece of text and `prompt_tokens` is 0. |
modified
docs/fr/explanation/architecture.md +1 -1 | @@ -31,7 +31,7 @@ Tout pointe vers `RazorbillCore`, et `RazorbillCore` ne sait rien de MLX, de HTT | ||
| 31 | 31 | 1. Hummingbird reçoit `POST /v1/chat/completions`. Des middlewares la journalisent, appliquent CORS, vérifient la clé d'API et transforment toute erreur en corps d'erreur OpenAI. |
| 32 | 32 | 2. Le corps est décodé et validé en un `ChatPlan` ; les JSON Schemas sont relus pour garder l'ordre de leurs clés. Avec `response_format`, une consigne contenant le schéma est ajoutée au message système. |
| 33 | 33 | 3. Le gestionnaire de modèles résout le nom (identifiant déclaré, ou identifiant Hugging Face), charge le modèle si besoin et donne à la requête un **bail** : une génération par modèle à la fois, les autres attendent dans une file (voir [cycle de vie des modèles](cycle-de-vie-des-modeles.md)). |
| 34 | -4. Le moteur ouvre une nouvelle session avec les réglages et la contrainte de la requête, met la conversation en forme avec le chat template du modèle et produit des événements. | |
| 34 | +4. Le moteur ouvre une nouvelle session avec les réglages et la contrainte de la requête, met la conversation en forme avec le chat template du modèle, réutilise la partie du cache KV laissé par la requête précédente qui lui correspond ([pourquoi](cycle-de-vie-des-modeles.md#réutiliser-le-prompt-précédent)), et produit des événements. | |
| 35 | 35 | 5. Les événements deviennent des morceaux OpenAI : les séquences d'arrêt sont appliquées, le raisonnement est séparé ou masqué, les appels d'outils sont numérotés, `finish_reason` et `usage` sont calculés. |
| 36 | 36 | 6. Les morceaux sont rassemblés en un `chat.completion`, ou envoyés en Server-Sent Events au fil de l'eau. Quand la réponse se termine — ou que le client se déconnecte — le bail est libéré. |
| 37 | 37 | |
| @@ -31,7 +31,7 @@ Tout pointe vers `RazorbillCore`, et `RazorbillCore` ne sait rien de MLX, de HTT | |||
| 31 | 1. Hummingbird reçoit `POST /v1/chat/completions`. Des middlewares la journalisent, appliquent CORS, vérifient la clé d'API et transforment toute erreur en corps d'erreur OpenAI. | 31 | 1. Hummingbird reçoit `POST /v1/chat/completions`. Des middlewares la journalisent, appliquent CORS, vérifient la clé d'API et transforment toute erreur en corps d'erreur OpenAI. |
| 32 | 2. Le corps est décodé et validé en un `ChatPlan` ; les JSON Schemas sont relus pour garder l'ordre de leurs clés. Avec `response_format`, une consigne contenant le schéma est ajoutée au message système. | 32 | 2. Le corps est décodé et validé en un `ChatPlan` ; les JSON Schemas sont relus pour garder l'ordre de leurs clés. Avec `response_format`, une consigne contenant le schéma est ajoutée au message système. |
| 33 | 3. Le gestionnaire de modèles résout le nom (identifiant déclaré, ou identifiant Hugging Face), charge le modèle si besoin et donne à la requête un **bail** : une génération par modèle à la fois, les autres attendent dans une file (voir [cycle de vie des modèles](cycle-de-vie-des-modeles.md)). | 33 | 3. Le gestionnaire de modèles résout le nom (identifiant déclaré, ou identifiant Hugging Face), charge le modèle si besoin et donne à la requête un **bail** : une génération par modèle à la fois, les autres attendent dans une file (voir [cycle de vie des modèles](cycle-de-vie-des-modeles.md)). |
| 34 | -4. Le moteur ouvre une nouvelle session avec les réglages et la contrainte de la requête, met la conversation en forme avec le chat template du modèle et produit des événements. | 34 | +4. Le moteur ouvre une nouvelle session avec les réglages et la contrainte de la requête, met la conversation en forme avec le chat template du modèle, réutilise la partie du cache KV laissé par la requête précédente qui lui correspond ([pourquoi](cycle-de-vie-des-modeles.md#réutiliser-le-prompt-précédent)), et produit des événements. |
| 35 | 5. Les événements deviennent des morceaux OpenAI : les séquences d'arrêt sont appliquées, le raisonnement est séparé ou masqué, les appels d'outils sont numérotés, `finish_reason` et `usage` sont calculés. | 35 | 5. Les événements deviennent des morceaux OpenAI : les séquences d'arrêt sont appliquées, le raisonnement est séparé ou masqué, les appels d'outils sont numérotés, `finish_reason` et `usage` sont calculés. |
| 36 | 6. Les morceaux sont rassemblés en un `chat.completion`, ou envoyés en Server-Sent Events au fil de l'eau. Quand la réponse se termine — ou que le client se déconnecte — le bail est libéré. | 36 | 6. Les morceaux sont rassemblés en un `chat.completion`, ou envoyés en Server-Sent Events au fil de l'eau. Quand la réponse se termine — ou que le client se déconnecte — le bail est libéré. |
| 37 | 37 | ||
modified
docs/fr/explanation/cycle-de-vie-des-modeles.md +14 -0 | @@ -16,6 +16,18 @@ Pourquoi ne pas faire tourner plusieurs générations d'un même modèle à la f | ||
| 16 | 16 | |
| 17 | 17 | Des modèles différents, eux, tournent en parallèle : une réponse de chat et une requête d'embedding utilisent deux modèles différents, donc deux files différentes. |
| 18 | 18 | |
| 19 | +## Réutiliser le prompt précédent | |
| 20 | + | |
| 21 | +Un client OpenAI ne garde aucun état sur le serveur : chaque requête porte toute la conversation, prompt système, définitions d'outils et tours précédents compris. Avant d'écrire le premier mot d'une réponse, le modèle doit lire le prompt et remplir son **cache KV**, qui garde les clés et valeurs d'attention de chaque token déjà lu. Sur une longue conversation, cette lecture domine : 25 à 30 secondes environ pour 4 000 tokens avec Qwen3-4B sur le Mac de mesure. | |
| 22 | + | |
| 23 | +Le moteur de chat garde donc le cache KV de la dernière requête de chaque modèle. Ce cache contient le prompt précédent suivi de la réponse générée pour lui. La requête suivante de la même conversation répète ce prompt, puis ajoute la réponse, telle que le client l'a reçue, et une nouvelle question. Le moteur compare les tokens, coupe le cache à la partie commune aux deux prompts, et ne lit que le reste. Sur la même conversation de 4 000 tokens, le premier mot arrive alors en moins d'une seconde. La réponse est celle qu'aurait donnée un cache vide : en décodage glouton les deux sont identiques, à part le token rare où le calcul du prompt par blocs différents change un arrondi. | |
| 24 | + | |
| 25 | +La réponse elle-même est toujours relue, car le client ne renvoie que le texte visible : le raisonnement des modèles qui réfléchissent n'y est pas, et le template de chat rend les tours précédents à sa façon. Cela coûte quelques dizaines de tokens par tour. | |
| 26 | + | |
| 27 | +Certains caches ne peuvent pas être coupés. Les modèles hybrides (Qwen3.5, Qwen3-Next, LFM2…) gardent un état récurrent impossible à rembobiner, et les modèles à fenêtre glissante (Gemma 3…) perdent le début d'une longue conversation dès que la fenêtre l'a dépassé. Pour eux, le moteur repart d'un cache vide, comme lorsque la conversation change (autre client, autre prompt système) : seul le début commun est réutilisé, si bien qu'une autre conversation partage simplement peu ou rien. | |
| 28 | + | |
| 29 | +Une seule conversation est gardée par modèle. Deux clients qui alternent sur le même modèle trouvent chacun le cache de l'autre et ne réutilisent que ce que leurs prompts ont en commun, souvent le seul prompt système. Le cache est libéré avec le modèle, et il occupe la mémoire laissée hors du budget des poids, comme tout cache KV le faisait déjà pendant une requête. Les réponses indiquent les tokens réutilisés dans `usage.prompt_tokens_details.cached_tokens`, et le journal des requêtes ajoute `cached=N`. | |
| 30 | + | |
| 19 | 31 | ## Faire de la place |
| 20 | 32 | |
| 21 | 33 | Deux limites décident du nombre de modèles chargés : |
| @@ -40,6 +52,8 @@ Pendant un flux, un client disparu n'est remarqué que lorsqu'une écriture éch | ||
| 40 | 52 | - **Un processus par modèle** (comme le font certains serveurs) : de l'isolation, mais chaque modèle paierait la mémoire du runtime, et partager des limites entre processus demande un coordinateur. |
| 41 | 53 | - **Décharger sur un signal de pression mémoire de macOS** au lieu d'un budget : le signal arrive tard, quand le swap a déjà commencé ; un budget est prévisible. |
| 42 | 54 | - **Attendre de la place au lieu de répondre 503** : une requête pourrait attendre indéfiniment derrière de longues générations ; une erreur claire est plus facile à traiter. |
| 55 | +- **Plusieurs conversations en cache par modèle** (un LRU de caches, comme les slots de llama-server ou le prefix caching de vLLM) : plus de mémoire à comptabiliser, pour un gain seulement quand des clients alternent. Un seul cache couvre le cas courant d'un agent ou d'une conversation à la fois. | |
| 56 | +- **Laisser la `ChatSession` de mlx-swift-lm réutiliser le cache** : elle le fait, mais seulement dans une session qui possède la conversation, alors que chaque requête HTTP apporte sa propre copie de la conversation. | |
| 43 | 57 | |
| 44 | 58 | ## Lien avec le reste |
| 45 | 59 | |
| @@ -16,6 +16,18 @@ Pourquoi ne pas faire tourner plusieurs générations d'un même modèle à la f | |||
| 16 | 16 | ||
| 17 | Des modèles différents, eux, tournent en parallèle : une réponse de chat et une requête d'embedding utilisent deux modèles différents, donc deux files différentes. | 17 | Des modèles différents, eux, tournent en parallèle : une réponse de chat et une requête d'embedding utilisent deux modèles différents, donc deux files différentes. |
| 18 | 18 | ||
| 19 | +## Réutiliser le prompt précédent | ||
| 20 | + | ||
| 21 | +Un client OpenAI ne garde aucun état sur le serveur : chaque requête porte toute la conversation, prompt système, définitions d'outils et tours précédents compris. Avant d'écrire le premier mot d'une réponse, le modèle doit lire le prompt et remplir son **cache KV**, qui garde les clés et valeurs d'attention de chaque token déjà lu. Sur une longue conversation, cette lecture domine : 25 à 30 secondes environ pour 4 000 tokens avec Qwen3-4B sur le Mac de mesure. | ||
| 22 | + | ||
| 23 | +Le moteur de chat garde donc le cache KV de la dernière requête de chaque modèle. Ce cache contient le prompt précédent suivi de la réponse générée pour lui. La requête suivante de la même conversation répète ce prompt, puis ajoute la réponse, telle que le client l'a reçue, et une nouvelle question. Le moteur compare les tokens, coupe le cache à la partie commune aux deux prompts, et ne lit que le reste. Sur la même conversation de 4 000 tokens, le premier mot arrive alors en moins d'une seconde. La réponse est celle qu'aurait donnée un cache vide : en décodage glouton les deux sont identiques, à part le token rare où le calcul du prompt par blocs différents change un arrondi. | ||
| 24 | + | ||
| 25 | +La réponse elle-même est toujours relue, car le client ne renvoie que le texte visible : le raisonnement des modèles qui réfléchissent n'y est pas, et le template de chat rend les tours précédents à sa façon. Cela coûte quelques dizaines de tokens par tour. | ||
| 26 | + | ||
| 27 | +Certains caches ne peuvent pas être coupés. Les modèles hybrides (Qwen3.5, Qwen3-Next, LFM2…) gardent un état récurrent impossible à rembobiner, et les modèles à fenêtre glissante (Gemma 3…) perdent le début d'une longue conversation dès que la fenêtre l'a dépassé. Pour eux, le moteur repart d'un cache vide, comme lorsque la conversation change (autre client, autre prompt système) : seul le début commun est réutilisé, si bien qu'une autre conversation partage simplement peu ou rien. | ||
| 28 | + | ||
| 29 | +Une seule conversation est gardée par modèle. Deux clients qui alternent sur le même modèle trouvent chacun le cache de l'autre et ne réutilisent que ce que leurs prompts ont en commun, souvent le seul prompt système. Le cache est libéré avec le modèle, et il occupe la mémoire laissée hors du budget des poids, comme tout cache KV le faisait déjà pendant une requête. Les réponses indiquent les tokens réutilisés dans `usage.prompt_tokens_details.cached_tokens`, et le journal des requêtes ajoute `cached=N`. | ||
| 30 | + | ||
| 19 | ## Faire de la place | 31 | ## Faire de la place |
| 20 | 32 | ||
| 21 | Deux limites décident du nombre de modèles chargés : | 33 | Deux limites décident du nombre de modèles chargés : |
| @@ -40,6 +52,8 @@ Pendant un flux, un client disparu n'est remarqué que lorsqu'une écriture éch | |||
| 40 | - **Un processus par modèle** (comme le font certains serveurs) : de l'isolation, mais chaque modèle paierait la mémoire du runtime, et partager des limites entre processus demande un coordinateur. | 52 | - **Un processus par modèle** (comme le font certains serveurs) : de l'isolation, mais chaque modèle paierait la mémoire du runtime, et partager des limites entre processus demande un coordinateur. |
| 41 | - **Décharger sur un signal de pression mémoire de macOS** au lieu d'un budget : le signal arrive tard, quand le swap a déjà commencé ; un budget est prévisible. | 53 | - **Décharger sur un signal de pression mémoire de macOS** au lieu d'un budget : le signal arrive tard, quand le swap a déjà commencé ; un budget est prévisible. |
| 42 | - **Attendre de la place au lieu de répondre 503** : une requête pourrait attendre indéfiniment derrière de longues générations ; une erreur claire est plus facile à traiter. | 54 | - **Attendre de la place au lieu de répondre 503** : une requête pourrait attendre indéfiniment derrière de longues générations ; une erreur claire est plus facile à traiter. |
| 55 | +- **Plusieurs conversations en cache par modèle** (un LRU de caches, comme les slots de llama-server ou le prefix caching de vLLM) : plus de mémoire à comptabiliser, pour un gain seulement quand des clients alternent. Un seul cache couvre le cas courant d'un agent ou d'une conversation à la fois. | ||
| 56 | +- **Laisser la `ChatSession` de mlx-swift-lm réutiliser le cache** : elle le fait, mais seulement dans une session qui possède la conversation, alors que chaque requête HTTP apporte sa propre copie de la conversation. | ||
| 43 | 57 | ||
| 44 | ## Lien avec le reste | 58 | ## Lien avec le reste |
| 45 | 59 | ||
modified
docs/fr/reference/api-http.md +1 -0 | @@ -161,6 +161,7 @@ La conversation est mise en forme avec le chat template du modèle. Le serveur n | ||
| 161 | 161 | | `message.reasoning_content` | quand le modèle a réfléchi et que le raisonnement est montré | Le raisonnement, sans les balises `<think>` | |
| 162 | 162 | | `message.tool_calls` | quand le modèle a appelé des outils | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` étant une chaîne JSON | |
| 163 | 163 | | `finish_reason` | toujours | `stop`, `length` (limite de tokens) ou `tool_calls` | |
| 164 | +| `usage.prompt_tokens_details.cached_tokens` | quand une partie du prompt a été réutilisée | Tokens du prompt repris du cache KV de la requête précédente au lieu d'être relus ; compris dans `prompt_tokens` ([pourquoi](../explanation/cycle-de-vie-des-modeles.md#réutiliser-le-prompt-précédent)) | | |
| 164 | 165 | | `usage.completion_tokens_details.reasoning_tokens` | quand le modèle a réfléchi | Morceaux de raisonnement reçus (environ un par token), comptés même quand le raisonnement est masqué | |
| 165 | 166 | |
| 166 | 167 | Quand une séquence d'arrêt termine la réponse, le moteur est interrompu avant de fournir ses comptes : `usage` compte alors un token par morceau de texte et `prompt_tokens` vaut 0. |
| @@ -161,6 +161,7 @@ La conversation est mise en forme avec le chat template du modèle. Le serveur n | |||
| 161 | | `message.reasoning_content` | quand le modèle a réfléchi et que le raisonnement est montré | Le raisonnement, sans les balises `<think>` | | 161 | | `message.reasoning_content` | quand le modèle a réfléchi et que le raisonnement est montré | Le raisonnement, sans les balises `<think>` | |
| 162 | | `message.tool_calls` | quand le modèle a appelé des outils | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` étant une chaîne JSON | | 162 | | `message.tool_calls` | quand le modèle a appelé des outils | `[{"id", "type": "function", "function": {"name", "arguments"}}]`, `arguments` étant une chaîne JSON | |
| 163 | | `finish_reason` | toujours | `stop`, `length` (limite de tokens) ou `tool_calls` | | 163 | | `finish_reason` | toujours | `stop`, `length` (limite de tokens) ou `tool_calls` | |
| 164 | +| `usage.prompt_tokens_details.cached_tokens` | quand une partie du prompt a été réutilisée | Tokens du prompt repris du cache KV de la requête précédente au lieu d'être relus ; compris dans `prompt_tokens` ([pourquoi](../explanation/cycle-de-vie-des-modeles.md#réutiliser-le-prompt-précédent)) | | ||
| 164 | | `usage.completion_tokens_details.reasoning_tokens` | quand le modèle a réfléchi | Morceaux de raisonnement reçus (environ un par token), comptés même quand le raisonnement est masqué | | 165 | | `usage.completion_tokens_details.reasoning_tokens` | quand le modèle a réfléchi | Morceaux de raisonnement reçus (environ un par token), comptés même quand le raisonnement est masqué | |
| 165 | 166 | ||
| 166 | Quand une séquence d'arrêt termine la réponse, le moteur est interrompu avant de fournir ses comptes : `usage` compte alors un token par morceau de texte et `prompt_tokens` vaut 0. | 167 | Quand une séquence d'arrêt termine la réponse, le moteur est interrompu avant de fournir ses comptes : `usage` compte alors un token par morceau de texte et `prompt_tokens` vaut 0. |
modified
docs/fr/reference/ligne-de-commande.md +1 -1 | @@ -38,7 +38,7 @@ config: server.yaml (2 declared models) | ||
| 38 | 38 | rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop |
| 39 | 39 | ``` |
| 40 | 40 | |
| 41 | -La première ligne n'apparaît qu'avec `--config`. Des avertissements (`warning: …`) précèdent la bannière quand le serveur écoute sur une adresse réseau sans clé d'API, ou autorise toutes les origines CORS sans clé. Ensuite, une ligne de journal par requête : méthode, chemin, statut, durée, et le modèle et les nombres de tokens (`model=… tokens=<prompt>+<complétion>`) ; les prompts et les réponses ne sont jamais journalisés. | |
| 41 | +La première ligne n'apparaît qu'avec `--config`. Des avertissements (`warning: …`) précèdent la bannière quand le serveur écoute sur une adresse réseau sans clé d'API, ou autorise toutes les origines CORS sans clé. Ensuite, une ligne de journal par requête : méthode, chemin, statut, durée, et le modèle et les nombres de tokens (`model=… tokens=<prompt>+<complétion>`, plus `cached=<n>` quand une partie du prompt a été reprise de la requête précédente) ; les prompts et les réponses ne sont jamais journalisés. | |
| 42 | 42 | |
| 43 | 43 | Le moteur est le premier de la compilation : `mlx` sur le Mac, `fake` sous Linux (qui répond `echo: <dernier message>` sans modèle). |
| 44 | 44 | |
| @@ -38,7 +38,7 @@ config: server.yaml (2 declared models) | |||
| 38 | rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop | 38 | rzb 0.1.0 serving http://127.0.0.1:8080/v1 (API key from $RZB_API_KEY) — Ctrl-C to stop |
| 39 | ``` | 39 | ``` |
| 40 | 40 | ||
| 41 | -La première ligne n'apparaît qu'avec `--config`. Des avertissements (`warning: …`) précèdent la bannière quand le serveur écoute sur une adresse réseau sans clé d'API, ou autorise toutes les origines CORS sans clé. Ensuite, une ligne de journal par requête : méthode, chemin, statut, durée, et le modèle et les nombres de tokens (`model=… tokens=<prompt>+<complétion>`) ; les prompts et les réponses ne sont jamais journalisés. | 41 | +La première ligne n'apparaît qu'avec `--config`. Des avertissements (`warning: …`) précèdent la bannière quand le serveur écoute sur une adresse réseau sans clé d'API, ou autorise toutes les origines CORS sans clé. Ensuite, une ligne de journal par requête : méthode, chemin, statut, durée, et le modèle et les nombres de tokens (`model=… tokens=<prompt>+<complétion>`, plus `cached=<n>` quand une partie du prompt a été reprise de la requête précédente) ; les prompts et les réponses ne sont jamais journalisés. |
| 42 | 42 | ||
| 43 | Le moteur est le premier de la compilation : `mlx` sur le Mac, `fake` sous Linux (qui répond `echo: <dernier message>` sans modèle). | 43 | Le moteur est le premier de la compilation : `mlx` sur le Mac, `fake` sous Linux (qui répond `echo: <dernier message>` sans modèle). |
| 44 | 44 | ||