Repository navigation
Conversation
On a snapshot family with no other way back to the boundary state (Gemma 3 past its sliding window, Raon-1 mini) the second identical chat request, a retry or regenerate, missed the prompt cache and only the third hit. The background warm-up restores the turn's history-boundary snapshot, prefills the reply as history and stores the next turn's history prefix as a Boundary entry. That insert ran the session-chain supersede and removed the boundary snapshot it had just restored from, which is the only stored vector that is a prefix of the same prompt sent again. `PromptCacheStore::insert_snapshot_preserving` takes the snapshot the new entry was restored from and leaves one shorter entry of the chain in place: the longest one whose tokens are a prefix of that snapshot's. `insert_snapshot` is the same call with `None`. `insert_model_state_snapshot` gains a `preserve` argument; the warm-up passes the entry its lookup returned and every other caller passes `None`. Between a warm-up and the next turn a conversation therefore holds both boundary entries. The next turn restores the warmed one and its own boundary insert supersedes both, so the chain stays bounded. The kept entry is chosen by token prefix and not by `Arc::ptr_eq` as the issue proposed. The two agree when the warm-up restored from the boundary snapshot, which is every chat turn by default (no completion snapshot is stored since lablup#3040). With `MLXCEL_PROMPT_CACHE_DECODED_TAIL=1` the turn also stores `prompt + reply`, and on a template whose history render extends the sampled reply that Completion entry is the longest stored prefix of the warm-up target. It is in another supersede chain, so an identity exemption keeps nothing and the retry still misses; the prefix rule keeps the boundary snapshot that entry extends. Measured on gemma-3-1b-it-4bit with a 2,321-token prompt, four identical requests report cached_tokens 0, 0, 2318, 2318 before and 0, 2318, 2318, 2318 after. Qwen 3.5 already hit on the second request through its turn-boundary state checkpoint (lablup#3047); there the change only keeps the extra entry. The extra entry is bounded by the store's byte budget and entry cap like any other. Under pressure LRU drops the least recently used entry instead of the supersede dropping the boundary, so a store sized for exactly the previous footprint sees an LRU eviction where it saw none. Closes lablup#3467
4 of 5 tasks
6 of 8 tasks
inureyes
pushed a commit
that referenced
this pull request
Nov 28, 2026
Prompt-cache snapshots now cover quantized KV cache modes (int8/int4 K/V, Turbo3Asym and Turbo4 rings including packed-V layouts), so a quantized server reuses a cached prefix instead of rejecting the snapshot. Restores validate the whole layout before assigning anything, a packed-width guard rejects malformed parts instead of panicking in `TurboQuantParams::new`, and the in-place marker is cleared on restore so buffers shared with the stored snapshot are never written in place. Hardening review: merged main locally (the only conflict was `CHANGELOG.md`, where the entry moved to a new `[Unreleased]` section after the v0.9.0-beta.3 release), ran fmt, the repo checks, 2241 mlxcel and 646 mlxcel-core CUDA tests, a composition check with #3492, and real-model checks: Gemma 3 1B int8 K/V and Gemma 4 12B fp16+turbo4 hit the cache on turn 2 and on an identical retry with replies byte-identical to a cold fresh-server run. Closes #3250
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes #3467.
A background prompt-cache warm-up restores a turn's history-boundary snapshot, prefills the reply as history, and stores the next turn's history prefix as a
Boundaryentry. That insert ran the session-chain supersede and removed the boundary snapshot it had restored from, which is the only stored vector that is a prefix of the same prompt sent again. A retry or regenerate of the turn therefore prefilled from cold, stored the boundary again, and only the request after it hit.This PR makes the warm-up's insert keep that boundary snapshot. On
mlx-community/gemma-3-1b-it-4bitwith a 2,321-token prompt, four identical/v1/chat/completionsrequests reportcached_tokens0, 0, 2318, 2318 on main and 0, 2318, 2318, 2318 with this change; the second request's TTFT goes from 0.180 s to 0.017 s.Two things measured here differ from the issue text and are described below: the kept entry is chosen by token prefix rather than by
Arc::ptr_eq, and Qwen 3.5 did not show the miss on main.What changed
src/server/prompt_cache/store.rs:PromptCacheStore::insert_snapshot_preserving(key, entry, preserve: Option<&Arc<ModelSnapshotEntry>>). WithSome(restored), the supersede leaves one shorter entry of the new entry's chain in place: the longest one whose token vector is a prefix ofrestored's.insert_snapshotis a one-line wrapper passingNone, so every existing caller and test keeps its behavior.src/server/batch/scheduler/prompt_cache.rs:insert_model_state_snapshotgains a trailingpreserveargument and callsinsert_snapshot_preserving.run_next_prompt_cache_warmuppassesSome(&entry), the entry itspeek_snapshot_prefixreturned. The other five callers passNone. The comment at the warm-up's insert no longer says it supersedes the turn's boundary entry, and the helper'sUsed by:list now names all six callers.src/server/batch/scheduler/prompt_end_snapshot.rs: the sixth caller,None.src/server/prompt_cache/snapshot_sizing.rs: the per-conversation entry count in the doc comment.MODEL_AWARE_SNAPSHOT_TARGET_ENTRIESstays 6.Resulting footprint, measured (tests and real servers below): a conversation holds its boundary snapshot through a turn, and the boundary snapshot plus the warmed prefix from the warm-up until the next turn. The next turn restores the warmed prefix and its own boundary insert supersedes both. The count does not grow with the number of turns.
Where this differs from the issue text
Arc::ptr_eq. The issue's filter (!preserve.is_some_and(|p| Arc::ptr_eq(&slot.entry, p))) keeps the entry the warm-up restored from. The two rules pick the same entry whenever the warm-up restored from the boundary snapshot, which is every chat turn in the default configuration: since fix(prompt-cache): restoring a completion snapshot diverges from a cold prefill #3040 a chat turn with a history boundary stores no completion snapshot, so the boundary snapshot is the longest stored prefix of the warm-up target. WithMLXCEL_PROMPT_CACHE_DECODED_TAIL=1the turn also storesprompt + reply, and on a template whose history render extends the sampled reply (Gemma 3) thatCompletionentry is the longest stored prefix of the warm-up target, so the warm-up restores from it. It is in another supersede chain, so the identity exemption keeps nothing and the retry still misses. I built the issue's exact form as a separate arm to check this: on the real Gemma 3 server withMLXCEL_PROMPT_CACHE_DECODED_TAIL=1it reportscached_tokens0, 0, 2318, 2318, the same as main, and this PR reports 0, 2318, 2318, 2318. The prefix rule keeps the boundary snapshot that the completion entry extends. The issue's signature is unchanged.Consequences of choosing by tokens: a restore source that was replaced by an identical vector since the lookup still names the entry to keep; one that is gone keeps the next longest entry its tokens cover, if the chain has one. Both are pinned by
a_restore_source_that_left_the_store_keeps_what_its_tokens_cover.B,H'and a completion entry. The completion entry exists only withMLXCEL_PROMPT_CACHE_DECODED_TAIL=1or for requests without a history boundary (fix(prompt-cache): restoring a completion snapshot diverges from a cold prefill #3040). Thesnapshot_sizing.rscomment is written for what the code stores.tiny_gemma3does not fail on main at "offset 0". That fixture's single global-attention layer accepts a truncating restore (feat: Partial snapshot restore at the longest common prefix for unwrapped rotating layers (rotating-attention families only) #1145), so on main the retry adopts the warmed entry cut back to its 36-token common prefix with the prompt, which is the history boundary, and reproduces the cold logits. On that fixture the test fails on main only at the entry count (1 instead of 2). The offset-0 failure the issue describes is reproduced on a fixture that cannot truncate (the same tiny Gemma 3 with its layer made a sliding one) and on Raon.Verification
Spark2: NVIDIA GB10, driver 580.178.04, CUDA 13.0, Linux 7.0.0-1019-nvidia aarch64, the pinned toolchain (rustc 1.97.1),
--features cuda,--profile test-fast,MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1. Baseef0076b96de51effc6c6e3dcafeb3498fdbe6958. Tested treeeab730a4f02ba97112565f66148f6980264d1baa, the tree of the commit.mainhas since moved to944dbfc2d(#3489, #3490, #3491, none of which touchessrc/server/prompt_cacheorsrc/server/batch);git merge-tree --write-tree origin/main HEADmerges without conflict (tree1ef58937). Nothing was re-run on the merged tree.cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 scripts/ci/check_used_by.py(OK, 78 top-level pub fn in 2 shared files, 57 annotated, 636 caller-file references resolved),bash scripts/ci/check_used_by_test.sh,python3 scripts/insert_apache_header.py --check,python3 scripts/ci/check_env_var_docs.py,python3 scripts/ci/check_kernel_dtype_keys.py,python3 scripts/ci/check_cross_repo_refs.py: all exit 0. The tree was the tested tree before and after.cargo test --locked --profile test-fast --features cuda -p mlxcel --lib -- --test-threads=1 scheduler_warmup_boundary_tests a_retried_turn_restores_the_boundary_snapshot_its_warmup_extended a_repeated_raon_turn_restores_its_boundary_after_the_warmup preserving_insert_keeps_the_restored_boundary snapshot_preserve_tests: 25 passed.scheduler_model_owned_cache6 passed;server::prompt_cache::store::tests43 passed;scheduler_prompt_cache_metrics_tests7 passed (includeswarmup_snapshot_hit_is_not_counted_and_still_warms);server::prompt_cache::270 passed;server::batch::646 passed, 10 ignored;routes::cache21 passed. The existing supersede tests instore_tests.rsare unchanged and pass.make verify-test-cudawith a private 0700TMPDIR: 17,406 passed, 5 failed, 517 ignored over 199test resultlines, 198 of themok. The tree was the tested tree before and after, and all 25 new tests ranokinside the gate. The library target has 13,109 passed, 5 failed, 254 ignored. The five failures aremodels::raon1_mini::speculative::tests::{a_steered_verify_block_applies_the_alpha_exactly_as_decode_does, a_verify_block_equals_the_decode_chain_byte_for_byte, rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens, the_exactness_probe_passes_on_the_tiny_model}andmodels::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit. The same five, run from a build of unmodifiedef0076b96, fail with the same messages (low: verify row 0 vs decode step,unsteered: verify row 0 vs decode step,accepted 0: every layer's state after rollback,width 3: verify block position 0 differs from the single-token chain in 34 of 128 logit bytes,d 64 seed 0 dtype 12 rows 1: h_res); the other four tests ofraon1_mini::speculativepass on both. The open PR fix(models): keep Raon DFlash2 verify blocks byte-exact on CUDA #3476 names these tests. None of them touches the prompt cache.Tests
Run against unmodified main (
ef0076b96with only the new scheduler test code applied; the store tests need the new function and cannot compile there) and against this PR.scheduler_model_owned_cache_tests::a_retried_turn_restores_the_boundary_snapshot_its_warmup_extended(the issue's sequence ontiny_gemma3: cold turn, warm-up withprompt_cache_warmups_runincremented, identical turn;snapshot_hits == 1,prefill_start_offset == boundary, restored suffix logits equal a cold split prefill bit for bit, same greedy tokens)scheduler_model_owned_cache_raon_tests::a_repeated_raon_turn_restores_its_boundary_after_the_warmup(the same on Raon-1 mini)(snapshot_hits, offset)(0, 0)!=(1, 12)scheduler_warmup_boundary_tests::a_retried_turn_restores_its_boundary_on_a_model_that_cannot_truncate(0, 0)!=(1, 36)...::a_warmup_restored_from_the_completion_snapshot_keeps_the_boundary(end-of-generation snapshot on)(1, 39)!=(1, 36)on the plain fixture...::the_next_turn_restores_the_warmed_prefix_and_supersedes_both_boundaries(0, 0)!=(1, 36)...::a_long_conversation_holds_one_more_entry_between_a_warmup_and_the_next_turn[1; 8], after each warm-up[1; 8], retry restores its boundary[false; 8][1; 8],[2; 8],[true; 8]...::a_long_conversation_with_completion_snapshots_holds_one_more_entry_too[2; 8],[2; 8],[false; 8][2; 8],[3; 8],[true; 8]; and[2..=9],[3..=10]where the completion chain never supersedes...::the_entry_cap_bounds_the_kept_boundary(4 snapshot slots)[2, 3, 4, 4, 4, 4, 4, 4]both,[false; 8][2, 3, 4, 4, 4, 4, 4, 4],[3, 4, 4, 4, 4, 4, 4, 4],[true; 8]...::keep_previous_turn_holds_two_entries_with_the_kept_boundarystore::tests::preserving_insert_keeps_the_restored_boundary_until_the_next_turnand 15 tests insnapshot_preserve_tests.rsWhat the long-conversation tests show about growth: with the default configuration the conversation holds 1 entry through each turn and 2 after each warm-up for all of N = 1..8. With the end-of-generation snapshot on, 2 and 3. In the one case where the count grows with N (
[2..=9]), the cause is the completion chain, whose entries are not prefixes of each other when the history render does not extend the sampled reply; that growth is the same on main and is bounded by the store's LRU, whichthe_entry_cap_bounds_the_kept_boundarypins.Things the issue does not spell out, each pinned in
src/server/prompt_cache/snapshot_preserve_tests.rs:a_restore_source_that_left_the_store_keeps_what_its_tokens_cover.SystemRootorCheckpointentry:an_entry_past_the_restore_point_is_still_superseded(the base ends before the boundary, covers no boundary entry, and the insert supersedes as before; the base itself stays).Completionbase:a_completion_restore_source_keeps_the_boundary_it_extends,only_the_newest_covered_entry_is_kept.Checkpointinsert:a_session_less_insert_supersedes_nothing_either_way,another_session_is_left_alone,a_checkpoint_insert_supersedes_nothing_either_way.keep_previous_turn:keep_previous_turn_and_the_kept_boundary_do_not_stack(the two exemptions name the same entry and keep one).the_kept_entry_is_accounted_and_released_with_the_next_turn(4,096 + 6,144 bytes while both are resident, 8,192 after the next turn's insert,snapshot_growth_bytesreduced by the kept entry).under_byte_pressure_lru_drops_the_completion_before_a_restored_boundary,under_byte_pressure_lru_drops_a_boundary_the_warmup_did_not_touch,a_budget_for_one_entry_keeps_the_warmed_one,the_entry_cap_drops_the_oldest_entry_for_the_kept_one.Mutations
Each reverts only production code in the fix tree; the 25 new tests were run on each.
preservekeep_previous_turnguards, the session-less insert, theCheckpointinsert, and the base that covers no boundary entry)Nonekeep_previous_turnguard); the guard and the 16 store tests passedArc::ptr_eqrule in place of the prefix rule(1, 39)on the plain fixture and(0, 0)on the one that cannot truncate, against(1, 36)) and five store tests (a_completion_restore_source_keeps_the_boundary_it_extends,only_the_newest_covered_entry_is_kept,a_restore_source_that_covers_nothing_keeps_nothing,a_restore_source_that_left_the_store_keeps_what_its_tokens_cover,under_byte_pressure_lru_drops_a_boundary_the_warmup_did_not_touch). The default-configuration tests pass.Real servers
mlxcel-server -m <model> --host 127.0.0.1 --port <port> --metrics, one server at a time, built from main (ef0076b96, sha2567f038b86…) and from this PR (ca4031e4…). Requests are streamed/v1/chat/completionsat temperature 0 withstream_options.include_usage; TTFT is the time to the first streamed delta. After each request the driver waits until/v1/cache/statsshows the request's warm-up ran or was skipped. Each server process ran three conversations under threeuserkeys: the identical request four times, a two-turn conversation, and a 40-turn conversation.mlx-community/gemma-3-1b-it-4bit(rev2d44e83d), 2,321-token prompt (past the 512-token sliding window, so no truncating restore applies):cached_tokenscached_tokenscached_tokenscolumns and TTFT 0.614, 0.175, 0.022, 0.018 s on main and 0.500, 0.016, 0.020, 0.016 s with this PR.cached_tokens1986 on both, so the next real turn still restores the warmed entry. Its TTFT in the second run was 0.126 s on main and 0.107 s with this PR. In the first run main's turn 2 took 13.158 s. That was the first time a process of this task ran that request, and it did not recur in the second run; a first-use CUDA kernel compile into this task's new kernel cache directory is the likely cause, which I did not confirm.cached_tokensat least 98.4% of the prompt). Whole snapshots held by that conversation after each turn's warm-up: 1 on main and 2 with this PR, at all 40 turns. Their bytes grow with the context: 16.4 MB at turn 1 and 23.3 MB at turn 40 on main, 32.9 MB and 45.2 MB with this PR.mlxcel_prompt_cache_entries/mlxcel_prompt_cache_byteson/metricsat the end, for all three conversations of the process: 5 / 117.8 MB on main, 8 / 180.5 MB with this PR. No LRU eviction on either.The server's debug log shows where each warm-up restored from. In the runs above the first warm-up reports
restored=2318 delta=56 warmed=2374: the boundary snapshot. WithMLXCEL_PROMPT_CACHE_DECODED_TAIL=1it reportsrestored=2368 delta=6 warmed=2374on all three binaries below: the completion snapshot (the prompt and the 47 reply tokens its state holds).The same requests with
MLXCEL_PROMPT_CACHE_DECODED_TAIL=1, three binaries:ptr_eqformThe 40-turn conversation holds 2 entries on main and on the
ptr_eqform and 3 with this PR, constant over the 40 turns (44.1 MB and 66.3 MB at turn 40).mlx-community/Qwen3.5-4B-4bit(rev0e7ffd5c),enable_thinking: false, 2,328-token prompt:cached_tokenscached_tokensTTFT in the second run of each binary: 2.255, 0.081, 0.085, 0.082 s on main and 2.164, 0.092, 0.086, 0.089 s with this PR. (In the first run main's request 1 took 22.36 s; it was the first Qwen 3.5 request of this task and likewise did not recur.)
The miss does not reproduce on Qwen 3.5. On main the store holds one whole snapshot after request 1 (the boundary was superseded,
snapshot_supersedes1), and request 2 still restores 2,321 tokens: the server's/v1/cache/statsreportsstate_checkpoint_hits4 at the end of the run (0 on Gemma 3), so the retry is served by the turn-boundary state checkpoint of #3047, rebuilt over the warmed entry. With this PRcached_tokensis the same on every request,state_checkpoint_hitsis 1 (the retries now restore the whole boundary snapshot), and the conversation holds two whole snapshots instead of one between a warm-up and the next turn: 267.7 MB instead of 133.9 MB at turn 40 of the 40-turn conversation (2,302 prompt tokens). So for a family whose boundary state a state checkpoint can rebuild, this change costs one resident snapshot and gains nothing I could measure. The issue lists Qwen 3.5 as affected and asks for the exemption on every family, which is what this PR does; limiting it to conversations without a usable state checkpoint would be a further change to the store rule and is not attempted here.Memory watchdog: each of the eleven server processes (seven in the first pass, four in the second) ran under a watchdog that stops it if host
MemAvailabledrops under 25 GiB or its RSS exceeds 40 GiB. No trip; lowestMemAvailable105.9 GiB, largest server RSS 5.9 GiB. No server ran beside a cargo build or the gate.Review lessons applied
a_restore_source_that_covers_nothing_keeps_nothingruns the rule with a restore source of 0 tokens, 1 token, one token short of the stored entry, a vector that diverges from it, one exactly as long as the stored entry (kept), and an empty chain. Budgets are run at one entry, at two of three entries, and at an entry cap of 2 and of 4.Nonedoes no extra work.a_preserving_insert_over_a_long_chain_takes_linear_timebuilds a chain of 2,000 prefixes of 8,192 tokens and bounds the insert at 5 s; the whole 25-test run, this test included, took 1.86 s. Comparing every chain member with every other would be 2,000 times the work.grep -rn "insert_model_state_snapshot(" srclists six call sites: the warm-up (Some), andinsert_prompt_end_snapshot,insert_history_boundary_snapshot,insert_system_root_snapshot,insert_checkpoint_snapshot,donate_finished_sequence_cache(None: none of them stores a state it restored and then extended past another entry of its own chain that a later request needs).insert_snapshothas no production caller left (the scheduler was the only one and now callsinsert_snapshot_preserving); its 53 existing test call sites are unchanged.peek_snapshot_prefixhas one production caller, the warm-up. The warm-up is submitted fromroutes/chat.rs(streaming and non-streaming) andin_process/chat.rs, and all of them reach the onerun_next_prompt_cache_warmup.SnapshotOrigin::Boundaryis produced in two places, the turn's boundary insert and the warm-up.cargo fmt --all -- --checkpasses on the committed tree (rustfmt changed three test hunks during development; they are in the commit).Verification limits
under_byte_pressure_lru_drops_a_boundary_the_warmup_did_not_touch). The retry then misses as on main.6f327113, which differs from the committed tree only in two test comments; on the committed tree they ran inside the gate.BatchedColdcohort and MTP burst paths, which take no boundary snapshot, are out of scope as the issue says and were not exercised.