Repository navigation
Studio: keep a long GGUF chat's slot KV across a reload (#9037) - #17121
Conversation
Slot KV was saved to disk only by the idle unload, a media swap and the /unload route. The reload a Context Length change makes goes through /load, whose teardown is inside load_model, so nothing was saved and the next message prefilled the whole conversation again: 11 minutes for a 103k-token Qwen3.8 chat in the report. A restore was also refused whenever the context length differed, which is the one setting that reload exists to change. /load now saves the resident llama-server's slots before either of its teardowns, through the same budgeted, keep-KV-gated path /unload uses, and the restore accepts a launch that differs from the save only in its two context fields when every slot still holds its saved tokens. llama-server refuses a prompt longer than its slot on restore anyway; the capacity check only saves the round trip. The fingerprint itself is unchanged, so the load-time identity snapshot and every double that compares it whole behave as before. Measured on an M2 Pro with Qwen3-0.6B Q4_K_M, a 2,257-token chat, then a forced reload from 8,192 to 16,384 context and one more turn: main prefilled 2,280 tokens (cached n_tokens = 0); this branch restored the slot and prefilled 27 (cached n_tokens = 2,253, f_keep = 0.997). Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
@codex review |
1 similar comment
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 510f413a8c
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # Save slot KV before replacing llama-server, as /unload does (#9037). | ||
| if replacing and llama_backend.is_loaded: | ||
| from core.inference.chat_swap_kv import save_chat_kv_before_unload | ||
| await save_chat_kv_before_unload() |
There was a problem hiding this comment.
Exclude the initiating API request from the save's busy check
When an OpenAI request auto-switches the primary model, _maybe_auto_switch_model() calls this implementation with current_request_counted=True, and the initiating request remains in keep-warm's inflight count. This new call uses a helper whose _chat_busy() check counts requests with current_request_counted=False, so the initiating request alone causes the save to be skipped even when no generation is running. Consequently, switching away from and back to a long GGUF chat through the API still loses its KV cache and forces a full prefill. Pass the caller's counted state through the helper, including its abort predicate, so only other work prevents the save.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not changing this here. The /v1 auto-switch never saved chat KV on main either, so this is no regression; the busy check is shared with /unload and the media swap, and widening it is a separate change from the #9037 reload fix.
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Review + reproduction evidencePinned review: I reproduced it on Linux, T4, Qwen3-0.6B-GGUF Q4_K_M, merge base
Conclusion: the bug is real and fixed on this branch, with no regression in the load paths checked. Ready once CI on the current head is green. |
NilayYadav
left a comment
There was a problem hiding this comment.
Thank you for the PR! The goal of this PR is to keep a long GGUF chat's KV cache across a model reload, so changing Context Length or another load setting does not prefill the whole conversation again. As a summary, this PR saves the llama-server slot KV before both teardown points in the /load route (under the existing keep-KV setting, busy check and 45 s budget) and lets the restore accept a launch that differs only in context length when every saved slot still fits.
I pushed a few fixes on top: the per-slot capacity no longer divides the already per-slot context by the slot count again; a context-only restore is refused when the per-slot context crosses the model's original RoPE context (llama.cpp switches LongRoPE short/long factors there, e.g. Phi-3); and launches using --override-kv or a per-slot KV size (flag, underscore spelling or env) keep strict matching.
| Reviewers | Severity | Finding |
|---|---|---|
| - | - | No open findings on the current head. |
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Fixes the first half of #9037: a long GGUF chat redid its whole prefill after a model reload.
What was happening
Slot KV was saved to disk on three paths: the idle auto-unload, a media swap that evicts chat,
and the
/unloadroute. The reload a Context Length change makes is none of those. It goesthrough
/load, which tears the old llama-server down insideload_model(Phase 1), so nosave ran, and the next message prefilled the whole conversation again. For the reporter that
was 103k tokens and 11 minutes at 100% GPU.
A second gap compounded it. The restore compared the saved launch fingerprint to the new one
whole, and the fingerprint includes the context length, so a stash would have been refused on
exactly the reload that users make most: raising the Context Length after hitting the wall.
What this changes
routes/inference.py: both teardown sites in_load_model_impl(the GGUF relaunch and astandard load replacing llama-server) call
save_chat_kv_before_unload()first, after thepoint of no return and the preview handoff, before any teardown. It is the same budgeted
(45 s), keep-KV-gated, busy-checked path
/unloadalready uses, and it stashes by GGUF, soswitching to another model and back restores as well. An identical load never reaches it:
_reuse_loaded_ggufreturns before.llama_cpp.py: the fingerprint becomes aNamedTuplewith the same values (a plain tuple ofthe same values still compares equal), plus
slot_resume_fits(manifest): the fingerprint mustmatch except for its two context fields, and every slot's
n_savedmust fit the new per-slotcapacity (the context split across slots, or the whole context under a unified cache).
llama-server refuses a restore longer than the slot anyway; the check saves the round trip.
llama_keepwarm.restore_kv_resumeasks the backend'sslot_resume_fitswhen it has one andkeeps the strict comparison for doubles that do not.
Measured
Same machine (M2 Pro, Metal), same script, both trees: load
unsloth/Qwen3-0.6B-GGUFQ4_K_M at 8,192 context, hold a 2,257-token chat,
/loadthe same model at 16,384 withforce_reload, send one more turn, read the new llama-server's log.Restoring saved slot KV onto the reloaded modelcached n_tokenson the next turnprompt eval timeon the next turnTests
test_llama_cpp_slot_resume.py: per-slot capacity; an identical launch fits; a largercontext fits while the saved tokens fit a slot and not when a four-way split or a smaller
context no longer holds them; any other fingerprint field differing refuses; malformed and
empty manifests refuse; the fingerprint still tracks the context for the strict comparison;
and the whole chain through
stash_unload_kvandnote_model_loadedon a realLlamaCppBackendrestores onto a larger context and deletes a stash that no longer fits.test_gguf_reload_saves_slot_kv.py: pins on the source, like the suite's other orderingguards, that both teardowns in
_load_model_implsave first underreplacing and llama_backend.is_loaded, after_set_preview_resident(None)and before theteardown, and that
/unloadkeeps its own save.tests/tools/refactor_guard.py verifypasses; the keep-warm, swap-KV, load-route andparallel-slot suites pass (1,364 tests).
The same 602 ids rerun on a pristine
mainworktree fail identically, apart from threetraining-side files (online tokenization, safetensors pread) whose failing subset shifts
between xdist runs on both trees and which pass serially on both. The failures are this
machine's environment (pytest's
/private/vartemp dir rejected as a system folder,/proc, spawn-vs-fork, the MLX adapter), none in the slot-KV or load-route code.Not in this PR
The rest of #9037: persistence across a Studio restart (the stash is in-process and the slot
directory is swept at startup, on purpose, because saved KV encodes chat content), the
Thinking-effort change invalidating the prefix (the chat template puts it at the front of the
prompt), and the context meter. The first-token timeout is already a setting (0 = unlimited).
🤖 Generated with Claude Code