Repository navigation
server: persist context checkpoints across slot save/restore - #20819
European-tech wants to merge 1 commit into
Conversation
For hybrid/recurrent models (Qwen3.5, Jamba, Falcon-H1), the server
creates context checkpoints during prompt processing that snapshot the
full recurrent state at regular intervals. These checkpoints are
essential to avoid full prompt re-processing when a slot is reused.
The existing /slots save/restore API persists the raw KV+recurrent
memory via llama_state_seq_{save,load}_file, and also restores the
token list. However, it does not persist the checkpoint metadata
stored in server_prompt::checkpoints. Without these, the hybrid model
cache validation logic in update_slots() cannot find any checkpoint to
restore from and falls back to full prompt re-processing.
This patch adds two small helper functions (slot_checkpoints_save and
slot_checkpoints_load) that write/read a companion file alongside the
main slot save file. The format is a versioned binary file with a
magic header.
This is particularly useful in router mode with --models-max 1, where
switching between models destroys the in-memory prompt cache. Users
can now call /slots/0?action=save before a model swap and
/slots/0?action=restore after, recovering the full cache including
checkpoints.
Tested with Qwen3.5-27B (64 layers, 16 attention + 48 recurrent):
- Without patch: cache_n=0, 23s re-processing after swap
- With patch: cache_n=26549, 75ms after swap
|
Hi @European-tech, thanks for your contribution! Per our contribution guidelines, the automated PR checker found the following issue(s) that need your attention:
Please note that maintainers reserve the right to make final decisions on PRs. If you believe there is a mistake, please comment below. |
|
Not sure how this can be made to stick to guidelines wrt AI generated code even in new PR. Just leaving this info: For use case: load prompt, save slot, shutdown llama-server, start llama-server, load slot, continue with prompt this requires part of #20955 to work (20955 minus auto-save/restore basically) |
Cherry-pick of ggml-org#20819 by European-tech. Persist context checkpoints in a companion .checkpoints file alongside slot saves. Without this, restoring a slot for hybrid/recurrent models triggers full prompt reprocessing (23s for 26K tokens on Qwen3.5-27B). With checkpoint persistence, restore takes 75ms. Binary format with magic 0x4C4C4350 ("LLCP"), versioned, backward compatible (old saves without companion file load normally).
|
@European-tech This is really cool! And it worked right up to 68e7ea3 , which broke it with a major refactor. But some of the updated models don't work on such an old version (Qwen3.6-27B). I would be really grateful if you could update this so I can cherry-pick it into my own fork - you'd probably have to update sooner or later anyway. |
|
I think I've managed to rebase these two commits with a lot of help from an AI (for those who want it too). |
Confirmed: works perfectly in production with Qwen3.6-27B + ROCmCherry-picked commit Hardware: AMD Ryzen 5 7600 + Radeon RX 7900 XT (ROCm) BEFORE the PR (no checkpoints persisted)Flow: save slot → shut down server → start server → restore slot → send continuation request. Result: full re-prefill of all tokens every time. ~303 seconds (5 minutes) of full re-prefill on every restart. AFTER the PR (with persistent checkpoints)Exact same flow: save slot → shut down server → start server → restore slot → send continuation request. On server startup (auto-restore): On manual snapshot restore: On continuation request: ~612ms to process only the 31 new tokens (the full checkpoint state was restored instantly from the Improvement summary
Integration noteI had to make a small type adaptation since my fork uses Excellent work on this PR. |
|
@calebrio02 Could you please review that my AI-based rebase (on top of basically vanilla upstream) is reasonable and not overengineered? It seems to work, but it also works without the last fix in that branch, and I don't understand nearly enough in the internals of llama.cpp to conduct an educated review. |
|
@dark-penguin I actually applied these patches with help from Claude and a Qwen3.6 35B A3B on hermes agent, but I tracked exactly what they were doing in the logs. Here is what I saw: Without your PR: Every restart wiped the memory, forcing a full 300s prefill. Is it overengineered? Definitely not. It's exactly what was needed. |
|
Thank the PR author, not me! 😄 I barely managed to rebase it! And really, huge thanks @European-tech ! It really is what we've been waiting for, and I can't believe it works so well! |
You're totally right, my apologies for the phrasing — huge thanks to @European-tech! 🙌 This is literally the dealbreaker I've been waiting for to finally use local LLMs comfortably. Removing the pain of context loss is going to make local inference so much more user-friendly. Truly amazing work! |
Cherry-pick of ggml-org#20819 by European-tech. Persist context checkpoints in a companion .checkpoints file alongside slot saves. Without this, restoring a slot for hybrid/recurrent models triggers full prompt reprocessing (23s for 26K tokens on Qwen3.5-27B). With checkpoint persistence, restore takes 75ms. Binary format with magic 0x4C4C4350 ("LLCP"), versioned, backward compatible (old saves without companion file load normally).
For hybrid/recurrent models (Qwen3.5, Jamba, Falcon-H1), the server
creates context checkpoints during prompt processing that snapshot the
full recurrent state at regular intervals. These checkpoints are
essential to avoid full prompt re-processing when a slot is reused.
The existing /slots save/restore API persists the raw KV+recurrent
memory via llama_state_seq_{save,load}_file, and also restores the
token list. However, it does not persist the checkpoint metadata
stored in server_prompt::checkpoints. Without these, the hybrid model
cache validation logic in update_slots() cannot find any checkpoint to
restore from and falls back to full prompt re-processing.
This patch adds two small helper functions (slot_checkpoints_save and
slot_checkpoints_load) that write/read a companion file alongside the
main slot save file. The format is a versioned binary file with a
magic header.
This is particularly useful in router mode with --models-max 1, where
switching between models destroys the in-memory prompt cache. Users
can now call /slots/0?action=save before a model swap and
/slots/0?action=restore after, recovering the full cache including
checkpoints.
Tested with Qwen3.5-27B (64 layers, 16 attention + 48 recurrent):
- Without patch: cache_n=0, 23s re-processing after swap
- With patch: cache_n=26549, 75ms after swap
(cherry picked from ggml-org#20819 by European-tech;
commit d5c3250)
POST /slots/{id}?action=save|restore never actually delivers the
KV-cache-reuse benefit it's documented to, found while building this
fleet's disk-persistence feature (master.slotSavePath) against a
draft-mtp (speculative decoding) deployment.
REVISION NOTE: the first version of this fix seeded one synthetic
full-range checkpoint after restore. That worked for the common case
(resuming a saved conversation by appending a new turn -- verified live:
3.0s vs 70.5s cold, cache_n=4533) but failed for a non-monotonic
continuation (resending a prompt SHORTER than what was saved, e.g. a
divergent retry) -- confirmed live: same 71.6s either way, cache_n=0.
Root cause of that gap: a single synthetic checkpoint's own pos_max
becomes a hard ceiling on how much reuse the very next request can ever
be trusted for (`cur.pos_max > pos_next` rejects it outright once the new
request's own match falls short of that ceiling), and there's no one
fixed pos_max that works for every possible future request. Superseded by
the approach below -- persisting whatever REAL checkpoints already
existed at save time, at their own natural positions, rather than
inventing one -- which searches correctly against any future request.
UPSTREAM PRIOR ART (found after building and testing the superseded
synthetic-checkpoint version above, before writing this one): this exact
bug is well-documented upstream --
- Issue ggml-org/llama.cpp#25913 ("/slots
save/restore silently loses all prompt reuse on hybrid/recurrent
models") -- open, matches our own symptom and log evidence exactly
(f_sim_best = 1.000 at slot selection, cache_n = 0 on the very next
request, "restore reports success and delivers zero benefit").
- PR ggml-org/llama.cpp#20819 -- an early fix
attempt, now stale/conflicting (unrebased since 2026-06), stalled on
the project's AI-disclosure contribution policy rather than a
technical objection.
- PR ggml-org/llama.cpp#28074 -- an independent
submission of the SAME synthetic-single-checkpoint approach this
fix's own superseded first version used. Closed by the author as a
duplicate of PR #26004 ("My synthetic full-range fallback only helps
empty-checkpoint case").
- PR ggml-org/llama.cpp#26004 -- OPEN,
MERGEABLE (no conflicts as of this vendoring), with a proper
regression test (tools/server/tests/unit/test_slot_save.py ::
test_slot_restore_preserves_context_checkpoints), and multiple
independent community confirmations across different hardware/model
combinations (Mac/Metal/Qwen3.6-35B-A3B; Vulkan/RADV/gfx1151/
Qwen3.8-Flash-Next; ROCm/Qwen3.6-27B). Not yet merged as of this
vendoring, apparently on maintainer review bandwidth rather than any
open technical objection. This commit's own save_slot_checkpoints/
load_slot_checkpoints functions below are adapted from that PR
(hand-ported to apply against our exact pinned commit -- PR #26004's
own diff did not apply byte-for-byte due to unrelated line drift from
its last rebase).
TWO DISTINCT FIXES, both needed for this fleet's draft-mtp deployments:
1. PR #26004's approach (save_slot_checkpoints/load_slot_checkpoints, and
their two call sites in SLOT_SAVE/SLOT_RESTORE): persist the
checkpoints that already existed in slot.prompt.checkpoints at save
time -- each with its own data_tgt/data_dft/data_spec -- as a tagged
appendix after the main llama-state payload in the same save file.
Old files without the appendix (no "SCKP" magic at the expected
offset) restore exactly as before -- silent no-op, not an error.
2. This fleet's own addition, NOT covered by PR #26004: neither
SLOT_SAVE nor SLOT_RESTORE persist ctx_dft (the draft model's own,
currently-live KV cache) directly -- only whatever data_dft happens
to be attached to an existing checkpoint. On a short conversation
that hasn't hit its first checkpoint yet, the restored slot's draft
model would silently start from an empty KV cache with no live
fallback. Implemented as a companion `<save-file>.dft` written
alongside the main save file, via
llama_state_seq_get_size_ext/get_data_ext (capture) and
llama_state_seq_set_data_ext (restore) -- the same primitives
common_prompt_checkpoint::update_dft/load_dft already use internally,
just driven directly here since there's no single-call file-based API
for a second context. A missing .dft file (an older save, or a
non-speculative deployment with ctx_dft == nullptr) is not an error.
Both verified together live: save -> evict (different conversation on the
same slot) -> restore -> resend-with-extension shows cache_n = 4533 (the
full restored prefix reused, only 17 new tokens processed), 3.0s versus
70.5s cold.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017R3QNP4GznFWhhf11QY18j
POST /slots/{id}?action=save|restore never actually delivers the
KV-cache-reuse benefit it's documented to, found while building this
fleet's disk-persistence feature (master.slotSavePath) against a
draft-mtp (speculative decoding) deployment.
REVISION NOTE: the first version of this fix seeded one synthetic
full-range checkpoint after restore. That worked for the common case
(resuming a saved conversation by appending a new turn -- verified live:
3.0s vs 70.5s cold, cache_n=4533) but failed for a non-monotonic
continuation (resending a prompt SHORTER than what was saved, e.g. a
divergent retry) -- confirmed live: same 71.6s either way, cache_n=0.
Root cause of that gap: a single synthetic checkpoint's own pos_max
becomes a hard ceiling on how much reuse the very next request can ever
be trusted for (`cur.pos_max > pos_next` rejects it outright once the new
request's own match falls short of that ceiling), and there's no one
fixed pos_max that works for every possible future request. Superseded by
the approach below -- persisting whatever REAL checkpoints already
existed at save time, at their own natural positions, rather than
inventing one -- which searches correctly against any future request.
UPSTREAM PRIOR ART (found after building and testing the superseded
synthetic-checkpoint version above, before writing this one): this exact
bug is well-documented upstream --
- Issue ggml-org/llama.cpp#25913 ("/slots
save/restore silently loses all prompt reuse on hybrid/recurrent
models") -- open, matches our own symptom and log evidence exactly
(f_sim_best = 1.000 at slot selection, cache_n = 0 on the very next
request, "restore reports success and delivers zero benefit").
- PR ggml-org/llama.cpp#20819 -- an early fix
attempt, now stale/conflicting (unrebased since 2026-06), stalled on
the project's AI-disclosure contribution policy rather than a
technical objection.
- PR ggml-org/llama.cpp#28074 -- an independent
submission of the SAME synthetic-single-checkpoint approach this
fix's own superseded first version used. Closed by the author as a
duplicate of PR #26004 ("My synthetic full-range fallback only helps
empty-checkpoint case").
- PR ggml-org/llama.cpp#26004 -- OPEN,
MERGEABLE (no conflicts as of this vendoring), with a proper
regression test (tools/server/tests/unit/test_slot_save.py ::
test_slot_restore_preserves_context_checkpoints), and multiple
independent community confirmations across different hardware/model
combinations (Mac/Metal/Qwen3.6-35B-A3B; Vulkan/RADV/gfx1151/
Qwen3.8-Flash-Next; ROCm/Qwen3.6-27B). Not yet merged as of this
vendoring, apparently on maintainer review bandwidth rather than any
open technical objection. This commit's own save_slot_checkpoints/
load_slot_checkpoints functions below are adapted from that PR
(hand-ported to apply against our exact pinned commit -- PR #26004's
own diff did not apply byte-for-byte due to unrelated line drift from
its last rebase).
TWO DISTINCT FIXES, both needed for this fleet's draft-mtp deployments:
1. PR #26004's approach (save_slot_checkpoints/load_slot_checkpoints, and
their two call sites in SLOT_SAVE/SLOT_RESTORE): persist the
checkpoints that already existed in slot.prompt.checkpoints at save
time -- each with its own data_tgt/data_dft/data_spec -- as a tagged
appendix after the main llama-state payload in the same save file.
Old files without the appendix (no "SCKP" magic at the expected
offset) restore exactly as before -- silent no-op, not an error.
2. This fleet's own addition, NOT covered by PR #26004: neither
SLOT_SAVE nor SLOT_RESTORE persist ctx_dft (the draft model's own,
currently-live KV cache) directly -- only whatever data_dft happens
to be attached to an existing checkpoint. On a short conversation
that hasn't hit its first checkpoint yet, the restored slot's draft
model would silently start from an empty KV cache with no live
fallback. Implemented as a companion `<save-file>.dft` written
alongside the main save file, via
llama_state_seq_get_size_ext/get_data_ext (capture) and
llama_state_seq_set_data_ext (restore) -- the same primitives
common_prompt_checkpoint::update_dft/load_dft already use internally,
just driven directly here since there's no single-call file-based API
for a second context. A missing .dft file (an older save, or a
non-speculative deployment with ctx_dft == nullptr) is not an error.
Both verified together live: save -> evict (different conversation on the
same slot) -> restore -> resend-with-extension shows cache_n = 4533 (the
full restored prefix reused, only 17 new tokens processed), 3.0s versus
70.5s cold.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017R3QNP4GznFWhhf11QY18j
POST /slots/{id}?action=save|restore never actually delivers the
KV-cache-reuse benefit it's documented to, found while building this
fleet's disk-persistence feature (master.slotSavePath) against a
draft-mtp (speculative decoding) deployment.
REVISION NOTE: the first version of this fix seeded one synthetic
full-range checkpoint after restore. That worked for the common case
(resuming a saved conversation by appending a new turn -- verified live:
3.0s vs 70.5s cold, cache_n=4533) but failed for a non-monotonic
continuation (resending a prompt SHORTER than what was saved, e.g. a
divergent retry) -- confirmed live: same 71.6s either way, cache_n=0.
Root cause of that gap: a single synthetic checkpoint's own pos_max
becomes a hard ceiling on how much reuse the very next request can ever
be trusted for (`cur.pos_max > pos_next` rejects it outright once the new
request's own match falls short of that ceiling), and there's no one
fixed pos_max that works for every possible future request. Superseded by
the approach below -- persisting whatever REAL checkpoints already
existed at save time, at their own natural positions, rather than
inventing one -- which searches correctly against any future request.
UPSTREAM PRIOR ART (found after building and testing the superseded
synthetic-checkpoint version above, before writing this one): this exact
bug is well-documented upstream --
- Issue ggml-org/llama.cpp#25913 ("/slots
save/restore silently loses all prompt reuse on hybrid/recurrent
models") -- open, matches our own symptom and log evidence exactly
(f_sim_best = 1.000 at slot selection, cache_n = 0 on the very next
request, "restore reports success and delivers zero benefit").
- PR ggml-org/llama.cpp#20819 -- an early fix
attempt, now stale/conflicting (unrebased since 2026-06), stalled on
the project's AI-disclosure contribution policy rather than a
technical objection.
- PR ggml-org/llama.cpp#28074 -- an independent
submission of the SAME synthetic-single-checkpoint approach this
fix's own superseded first version used. Closed by the author as a
duplicate of PR #26004 ("My synthetic full-range fallback only helps
empty-checkpoint case").
- PR ggml-org/llama.cpp#26004 -- OPEN,
MERGEABLE (no conflicts as of this vendoring), with a proper
regression test (tools/server/tests/unit/test_slot_save.py ::
test_slot_restore_preserves_context_checkpoints), and multiple
independent community confirmations across different hardware/model
combinations (Mac/Metal/Qwen3.6-35B-A3B; Vulkan/RADV/gfx1151/
Qwen3.8-Flash-Next; ROCm/Qwen3.6-27B). Not yet merged as of this
vendoring, apparently on maintainer review bandwidth rather than any
open technical objection. This commit's own save_slot_checkpoints/
load_slot_checkpoints functions below are adapted from that PR
(hand-ported to apply against our exact pinned commit -- PR #26004's
own diff did not apply byte-for-byte due to unrelated line drift from
its last rebase).
TWO DISTINCT FIXES, both needed for this fleet's draft-mtp deployments:
1. PR #26004's approach (save_slot_checkpoints/load_slot_checkpoints, and
their two call sites in SLOT_SAVE/SLOT_RESTORE): persist the
checkpoints that already existed in slot.prompt.checkpoints at save
time -- each with its own data_tgt/data_dft/data_spec -- as a tagged
appendix after the main llama-state payload in the same save file.
Old files without the appendix (no "SCKP" magic at the expected
offset) restore exactly as before -- silent no-op, not an error.
2. This fleet's own addition, NOT covered by PR #26004: neither
SLOT_SAVE nor SLOT_RESTORE persist ctx_dft (the draft model's own,
currently-live KV cache) directly -- only whatever data_dft happens
to be attached to an existing checkpoint. On a short conversation
that hasn't hit its first checkpoint yet, the restored slot's draft
model would silently start from an empty KV cache with no live
fallback. Implemented as a companion `<save-file>.dft` written
alongside the main save file, via
llama_state_seq_get_size_ext/get_data_ext (capture) and
llama_state_seq_set_data_ext (restore) -- the same primitives
common_prompt_checkpoint::update_dft/load_dft already use internally,
just driven directly here since there's no single-call file-based API
for a second context. A missing .dft file (an older save, or a
non-speculative deployment with ctx_dft == nullptr) is not an error.
Both verified together live: save -> evict (different conversation on the
same slot) -> restore -> resend-with-extension shows cache_n = 4533 (the
full restored prefix reused, only 17 new tokens processed), 3.0s versus
70.5s cold.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017R3QNP4GznFWhhf11QY18j
Summary
The
/slotssave/restore API persists the raw KV+recurrent memory and the token list, but does not persist the context checkpoints stored inserver_prompt::checkpoints.For hybrid/recurrent models (Qwen3.5, Jamba, Falcon-H1), these checkpoints are essential: without them,
update_slots()cannot find a valid recurrent state snapshot and falls back to full prompt re-processing on every slot reuse.This PR adds two helper functions that write/read a small companion file (
<filename>.checkpoints) next to the main slot save file, using a versioned binary format with a magic header.Motivation
In router mode with
--models-max 1, switching between models destroys the in-memory prompt cache (the child process is killed). Users can call/slots/0?action=savebefore a swap and/slots/0?action=restoreafter, but the restored slot had no checkpoints — triggering a full re-processing of the entire prompt.For a 26K-token conversation on Qwen3.5-27B (16 attention + 48 recurrent layers), this meant 23 seconds of wasted compute on every model swap return.
Results
Tested with Qwen3.5-27B in router mode (save → swap to MoE → swap back → restore → same prompt):
cache_nafter restoreChanges
server-context.cpp: Two static helper functions (slot_checkpoints_save,slot_checkpoints_load) + two one-line call sites in the existingSLOT_SAVE/SLOT_RESTOREhandlers.Backward compatibility
.checkpointscompanion are loaded normally (the load helper returnstruewhen the file is absent).File format
Disclosure
AI tools were used in an assistive capacity during the development of this patch. The code was manually reviewed, tested, and validated on real hardware (RTX 3090, Qwen3.5-27B + Qwen3.5-35B-A3B MoE in router mode).
Related
--cache-disk) #20697 — feature request for--cache-disk(persistent checkpoints)