Skip to content

Studio: keep a long GGUF chat's slot KV across a reload (#9037) - #17121

Merged
Imagineer99 merged 11 commits into
unslothai:mainfrom
csun365:studio/gguf-reload-keeps-slot-kv
Nov 13, 2026
Merged

Imagineer99 merged 11 commits into
unslothai:mainfrom
csun365:studio/gguf-reload-keeps-slot-kv

Conversation

@csun365

@csun365 csun365 commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

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 /unload route. The reload a Context Length change makes is none of those. It goes
through /load, which tears the old llama-server down inside load_model (Phase 1), so no
save 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 a
    standard load replacing llama-server) call save_chat_kv_before_unload() first, after the
    point of no return and the preview handoff, before any teardown. It is the same budgeted
    (45 s), keep-KV-gated, busy-checked path /unload already uses, and it stashes by GGUF, so
    switching to another model and back restores as well. An identical load never reaches it:
    _reuse_loaded_gguf returns before.
  • llama_cpp.py: the fingerprint becomes a NamedTuple with the same values (a plain tuple of
    the same values still compares equal), plus slot_resume_fits(manifest): the fingerprint must
    match except for its two context fields, and every slot's n_saved must fit the new per-slot
    capacity (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_resume asks the backend's slot_resume_fits when it has one and
    keeps the strict comparison for doubles that do not.

Measured

Same machine (M2 Pro, Metal), same script, both trees: load unsloth/Qwen3-0.6B-GGUF
Q4_K_M at 8,192 context, hold a 2,257-token chat, /load the same model at 16,384 with
force_reload, send one more turn, read the new llama-server's log.

main this branch
backend log after the reload nothing Restoring saved slot KV onto the reloaded model
cached n_tokens on the next turn 0 2,253
prompt eval time on the next turn 691 ms / 2,280 tokens 46 ms / 27 tokens
slot files left behind none none (deleted after the restore)

Tests

  • test_llama_cpp_slot_resume.py: per-slot capacity; an identical launch fits; a larger
    context 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_kv and note_model_loaded on a real
    LlamaCppBackend restores onto a larger context and deletes a stash that no longer fits.
  • New test_gguf_reload_saves_slot_kv.py: pins on the source, like the suite's other ordering
    guards, that both teardowns in _load_model_impl save first under
    replacing and llama_backend.is_loaded, after _set_preview_resident(None) and before the
    teardown, and that /unload keeps its own save.
  • tests/tools/refactor_guard.py verify passes; the keep-warm, swap-KV, load-route and
    parallel-slot suites pass (1,364 tests).
  • Full backend suite on this branch (macOS, CPU torch): 94,707 passed, 500 failed, 106 errors.
    The same 602 ids rerun on a pristine main worktree fail identically, apart from three
    training-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/var temp 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

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]>
@NilayYadav NilayYadav self-assigned this Nov 9, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

1 similar comment
@NilayYadav

Copy link
Copy Markdown
Collaborator

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T15:19:17.187937Z 9e0675f Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 9e106d59aa

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 6cdb22be03

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 519ac36868

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Nov 9, 2026
@NilayYadav

Copy link
Copy Markdown
Collaborator

Review + reproduction evidence

Pinned review: 65773f1b8. Fixes pushed in 560874c, 9e106d5, 6cdb22b, 519ac36; no open findings.

I reproduced it on Linux, T4, Qwen3-0.6B-GGUF Q4_K_M, merge base ed3eec632 vs this branch, both installed with install.sh --local and driven through the same HTTP API the chat UI uses. A 2.2k-token chat, then /load the same model at 16384 context (from 8192) with force_reload, then one more turn:

merge base this branch
backend log after the reload nothing Restoring saved slot KV onto the reloaded model
cached tokens on the next turn 0 2254
prompt tokens processed 2275 21
prompt time 394.6 ms 48.1 ms
  • Plain model switch with keep-KV off (4 rounds): /load 2.0 to 2.3 s on this branch vs 2.6 to 5.2 s on the merge base, so no added delay.
  • Switch A to B to A with keep-KV on: the chat is restored on return (2215 cached tokens vs 0 on the merge base).
  • Ordinary first load on a fresh install: HTTP 200 and chat works on both sides.
  • Test differential is discriminating; 44 related test files: 5674 passed, and the 17 failures are identical on the 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 NilayYadav left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Imagineer99

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 9e0675f0ba

ℹ️ 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".

@Imagineer99
Imagineer99 merged commit 3c41a77 into unslothai:main Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants