diff --git a/docs/docs/instructions/server/prefix_cache.md b/docs/docs/instructions/server/prefix_cache.md
index ee80cb590..e1421ca4e 100644
--- a/docs/docs/instructions/server/prefix_cache.md
+++ b/docs/docs/instructions/server/prefix_cache.md
@@ -37,7 +37,7 @@ The other supported models gain the same way. Measured on shorter prompts (about
| | Prefix cache |
|---|---|
-| Models | **Qwen:** `qwen3.5:0.8b` / `2b` / `4b` / `9b`, `qwen3.6-moe:35b-a3b`, `qwen3:0.6b` / `1.7b` / `4b` / `8b`, `qwen3-it:4b`, `qwen3-tk:4b`, `qwen2.5-it:3b`, `qwen3vl-it:4b`, `qwen2.5vl-it:3b`, `qwen3.8-mtp:27b` and `qwen3.8-dflash2:27b` (the shared system prompt only, see below)
**Llama and DeepSeek:** `llama3.2:1b` / `3b`, `llama3.1:8b`, `deepseek-r1:8b`, `deepseek-r1-0528:8b`
**Phi and Nanbeige:** `phi4-mini-it:4b`, `nanbeige4.1:3b`
**LFM:** `lfm2:1.2b`, `lfm2:2.6b`, `lfm2-trans:2.6b`, `lfm2.5-it:1.2b`, `lfm2.5-tk:1.2b`
**gpt-oss:** `gpt-oss:20b`, `gpt-oss-sg:20b`
**Gemma:** `gemma3:1b`, `gemma3:4b`, `medgemma:4b`, `medgemma1.5:4b`, `translategemma:4b`, `gemma4-it:e2b` / `e4b` / `12b`, `nemotron3.5-bolt:e4b`
**MiniCPM:** `minicpm-v-4.7:1b`, `minicpm-v-4.7-moe:35b-a3b` |
+| Models | **Qwen:** `qwen3.5:0.8b` / `2b` / `4b` / `9b`, `qwen3.6-moe:35b-a3b`, `qwen3:0.6b` / `1.7b` / `4b` / `8b`, `qwen3-it:4b`, `qwen3-tk:4b`, `qwen2.5-it:3b`, `qwen3vl-it:4b`, `qwen2.5vl-it:3b`, `qwen3.8-mtp:27b` and `qwen3.8-dflash2:27b` (the shared start only, see below)
**Llama and DeepSeek:** `llama3.2:1b` / `3b`, `llama3.1:8b`, `deepseek-r1:8b`, `deepseek-r1-0528:8b`
**Phi and Nanbeige:** `phi4-mini-it:4b`, `nanbeige4.1:3b`
**LFM:** `lfm2:1.2b`, `lfm2:2.6b`, `lfm2-trans:2.6b`, `lfm2.5-it:1.2b`, `lfm2.5-tk:1.2b`
**gpt-oss:** `gpt-oss:20b`, `gpt-oss-sg:20b`
**Gemma:** `gemma3:1b`, `gemma3:4b`, `medgemma:4b`, `medgemma1.5:4b`, `translategemma:4b`, `gemma4-it:e2b` / `e4b` / `12b`, `nemotron3.5-bolt:e4b`
**MiniCPM:** `minicpm-v-4.7:1b`, `minicpm-v-4.7-moe:35b-a3b` |
| Endpoint | `POST /v1/chat/completions` of `flm serve` (what Hermes, Open WebUI and most agents use), streaming or not |
| Not covered | `flm run` (CLI mode) and the Ollama endpoints `/api/chat` and `/api/generate`, which keep the older single-checkpoint reuse. A request on an Ollama endpoint also empties the prefix cache, so a client that mixes both APIs loses its cached prompts. |
@@ -146,7 +146,7 @@ Measured with four unrelated 15k-token conversations taking turns and default op
[WARNING] Prefix cache: a 140000-token prompt needs 4424 MiB, more than --prefix-cache-mb (4096 MiB); it is not saved. Raise --prefix-cache-mb to reuse prompts this long.
```
-When a limit is reached, FLM drops the least useful saved prompt first: older replies of a conversation that has a newer one, then the least recently used reply, and only then a shared system-prompt copy that nothing depends on.
+When a limit is reached, FLM drops the least useful saved prompt first: older replies of a conversation that has a newer one, then the least recently used reply, and only then a shared start that nothing depends on (a system-prompt copy, or a history shared by prompts which differ in their last message, see How it works below). A history is kept over every reply, so a workload with many different histories (edited messages, agents which branch) leaves fewer slots for replies; raise `--prefix-slots` (and `--prefix-cache-mb`) for it.
---
@@ -173,7 +173,7 @@ The server log shows each decision:
## 🧠How it works
-1. While FLM reads a prompt it saves a **snapshot** of the model's state at the end of the system prompt and tools, and another one at the end of the prompt.
+1. While FLM reads a prompt it saves a **snapshot** of the model's state at the end of the system prompt and tools (when they are at least 512 tokens long), and another one at the end of the prompt. When the prompt before shared everything up to the last user turn (a user message, or tool results) and went on with another one, it also saves one at the start of that turn. This snapshot serves prompts which share everything but their last message, like the same few-shot examples or the same document followed by different questions. A chat, whose every turn only continues the turn before, does not save it, since saving it needs a prefill pass of its own. It is saved only when it is at least 512 tokens into the prompt and adds at least `--prefix-min-gain` tokens to the system prompt snapshot and to what the prompt resumed from. FLM compares a prompt only with the prompt just before it, so two prompts with the same history have to come one after the other: with a request in between (a title call, another conversation), or with two sets of examples used in turn, it is not saved.
2. For a new request, FLM looks for the **longest saved snapshot whose text is exactly the beginning of the new prompt**. It restores that snapshot and reads only the rest.
3. Snapshots are matched on the exact tokens, so two different conversations that start with the same system prompt reuse the same snapshot of it. Images are matched by their content: the same picture is reused, a different picture is read again (the text before it is still reused).
4. A short request with its own system prompt (for example the title call some agents send after each turn) does not erase the snapshots of the main conversation.
@@ -199,7 +199,7 @@ In the multi-agent runs the first sub-agent reads the shared system prompt and i
- **Qwen3.6 after a tool loop.** Qwen3.6's chat template rewrites the earlier assistant messages (their reasoning blocks) as soon as a newer user message arrives. After a tool-using turn, a new user message can therefore only reuse the system prompt and the first user message, not the whole history. No prompt cache can do better with this template; without the prefix cache nothing is reused.
- **Answers are not bit-for-bit identical to a cold run.** Resuming from a snapshot gives the same quality, but with greedy decoding some answers differ in wording (for example the order of a list) from what the same prompt gives when read from scratch: about 1 in 5 on Qwen3.5 and about 1 in 3 on Qwen3.6 in our replay tests. The cache that came before it behaves the same way.
- **Hermes sub-agents.** Sub-agents reuse the parent's system-prompt snapshot only when every task's `context` field is empty. A per-task context is placed in the sub-agent's system prompt, which makes each sub-agent a different prompt that is read from scratch. Larger models (4B and up) leave it empty in practice; `qwen3.5:2b` sometimes fills it in.
-- **Qwen3.8-27B keeps the shared system prompt only.** A saved prompt of this model is large (about 150 MiB plus 84 KiB per token), so it saves the shared start of a conversation (system prompt + tools) and nothing after it, for text prompts. A conversation that keeps going is still continued from the end of its last turn with the older single-checkpoint reuse, as before; the saved system prompt is used when another conversation ran in between, so several agents that share one system prompt do not read it again each time.
+- **Qwen3.8-27B keeps the shared start only.** A saved prompt of this model is large (about 150 MiB plus 84 KiB per token), so it saves the shared start of a conversation (system prompt + tools, and the history before the last user turn) and nothing after it, for text prompts. A conversation that keeps going is still continued from the end of its last turn with the older single-checkpoint reuse, as before; the saved system prompt is used when another conversation ran in between, so several agents that share one system prompt do not read it again each time.
- **Gemma 3 has no shared system-prompt snapshot.** Its chat template puts the system prompt inside the first user turn, so two conversations that differ in their first message have no text in common to save as a shared start. Each conversation still reuses its own earlier turns.
- **Models with a sliding window or a convolution state** (Gemma 3 and 4, gpt-oss, the LFM2 family) save a state that cannot be rewound, so a saved prompt is resumed only when the new prompt starts with all of it, and a prompt that shares just the first part of a saved one resumes at the saved system-prompt start instead.
- **Pictures and audio.** The Qwen-VL models, Qwen3.5 and MiniCPM-V reuse prompts that contain pictures. The Gemma 4 models (and the `nemotron3.5-bolt` model built on them) reuse text prompts through the prefix cache; a prompt with a picture or audio keeps the older single-checkpoint reuse. `qwen3.8-mtp:27b` and `qwen3.8-dflash2:27b` are text only.
diff --git a/docs/docs/models/qwen.md b/docs/docs/models/qwen.md
index 22fd08256..16129a858 100644
--- a/docs/docs/models/qwen.md
+++ b/docs/docs/models/qwen.md
@@ -605,7 +605,7 @@ The `-r` option determines the image's height:
- **Type:** Image-Text-to-Text
- **Think:** Yes
- **Tool Calling Support:** Yes
-- **Prefix cache (server mode):** Partly: the shared system prompt of text conversations is saved; a conversation that keeps going uses the older single-checkpoint reuse (see [Prefix Cache (Prompt Reuse)](https://fastflowlm.com/docs/instructions/server/prefix_cache/))
+- **Prefix cache (server mode):** Partly: the shared start of text conversations (the system prompt, and the history before the last user turn) is saved; a conversation that keeps going uses the older single-checkpoint reuse (see [Prefix Cache (Prompt Reuse)](https://fastflowlm.com/docs/instructions/server/prefix_cache/))
- **Speculative Decoding:** Yes — built-in MTP draft head (see note below)
- **Base Model:** [Qwen/Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B)
- **Quantization:** Q4_K
diff --git a/src/common/AutoModel/automodel.cpp b/src/common/AutoModel/automodel.cpp
index 158198ab3..f8cbab15e 100644
--- a/src/common/AutoModel/automodel.cpp
+++ b/src/common/AutoModel/automodel.cpp
@@ -504,34 +504,35 @@ bool AutoModel::_prefix_insert(PrefixSlotCache& cache, chat_meta_info_t& meta_in
std::optional requested_max_new_tokens) {
bool success = true;
uint64_t head_prefill_ns = 0;
- // Save the end of system + tools while prefilling, so a prompt that shares only that part
- // (another conversation, a side request) can resume there.
- size_t boundary = 0;
- {
- const std::vector marker = this->tokenizer->encode(boundary_marker);
- for (size_t i = 1; i + marker.size() <= full_tokens.size() && !marker.empty(); i++) {
- if (std::equal(marker.begin(), marker.end(), full_tokens.begin() + i)) {
- boundary = i;
- break;
- }
- }
- if (boundary < cache.min_boundary) boundary = 0;
- }
- if (payload == nullptr && boundary > match_len && boundary < full_tokens.size()) {
- std::vector head(full_tokens.begin(), full_tokens.begin() + boundary);
+ // Save up to two shared heads while prefilling, each where a user turn starts:
+ // - the end of system + tools (the first user turn), so a prompt that shares only that part
+ // (another conversation, a side request) can resume there;
+ // - the history before the last user turn, so prompts that share everything but their last
+ // message (few-shot examples, a document followed by different questions) can resume there.
+ // A prompt with pictures still to read is not split.
+ const PrefixSlotCache::heads_t heads = cache.plan_heads(
+ full_tokens, PrefixSlotCache::find_user_turns(full_tokens, this->tokenizer->encode(boundary_marker)), match_len, payload == nullptr);
+ auto save_head = [&](size_t length) {
+ std::vector head(full_tokens.begin(), full_tokens.begin() + length);
chat_meta_info_t head_meta;
head_meta.max_prefill_len = meta_info.max_prefill_len;
- success = this->_shared_insert(head_meta, head, is_cancelled, nullptr, 0, std::nullopt, false);
- if (success) {
- head_prefill_ns = head_meta.prefill_duration;
- const std::vector head_tokens(full_tokens.begin(), full_tokens.begin() + boundary);
- cache.set_live(head_tokens);
- cache.save(head_tokens, image_hashes, true, 0); // keeps the hashes of the pictures inside the head
- } else {
+ if (!this->_shared_insert(head_meta, head, is_cancelled, nullptr, 0, std::nullopt, false)) {
meta_info.stop_reason = head_meta.stop_reason;
meta_info.error_message = head_meta.error_message;
meta_info.error_code = head_meta.error_code;
+ return false;
}
+ head_prefill_ns += head_meta.prefill_duration;
+ const std::vector head_tokens(full_tokens.begin(), full_tokens.begin() + length);
+ cache.set_live(head_tokens);
+ cache.save(head_tokens, image_hashes, true, 0); // keeps the hashes of the pictures inside the head
+ return true;
+ };
+ if (heads.save_boundary) {
+ success = save_head(heads.boundary);
+ }
+ if (success && heads.save_history) {
+ success = save_head(heads.history);
}
if (success) {
success = payload != nullptr
@@ -546,9 +547,10 @@ bool AutoModel::_prefix_insert(PrefixSlotCache& cache, chat_meta_info_t& meta_in
meta_info.cached_prompt_tokens = static_cast(match_len);
meta_info.prefill_duration += head_prefill_ns;
cache.set_live(full_tokens);
- // the end of this prompt keeps only what follows the shared head, when a slot holds that head
+ cache.set_last_prompt(full_tokens);
+ // the end of this prompt keeps only what follows the longest shared head a slot holds
if (!cache.boundary_only) {
- cache.save(full_tokens, image_hashes, false, cache.end_kv_from(full_tokens, boundary));
+ cache.save(full_tokens, image_hashes, false, cache.end_kv_from(full_tokens, heads));
}
meta_info.prefix_cache = cache.report();
return true;
diff --git a/src/common/prefix_slot_cache.cpp b/src/common/prefix_slot_cache.cpp
index b6a85dd91..837741743 100644
--- a/src/common/prefix_slot_cache.cpp
+++ b/src/common/prefix_slot_cache.cpp
@@ -92,13 +92,71 @@ void PrefixSlotCache::attach(void* engine, const flm_state_api* api) {
void PrefixSlotCache::forget_all() {
slots_table_.clear(); // the states are ours: their memory goes with them
live_tokens_.clear();
+ last_prompt_.clear();
}
-int PrefixSlotCache::end_kv_from(const std::vector& tokens, size_t boundary) const {
- if (boundary == 0) return 0;
- for (const auto& slot : slots_table_) {
- if (slot.kv_from() == 0 &&slot.tokens.size() == boundary && has_prefix(tokens, slot.tokens)) {
- return static_cast(boundary);
+bool PrefixSlotCache::forked(const std::vector& tokens, size_t length) const {
+ return length <= tokens.size() && last_prompt_.size() > length && lcp_len(last_prompt_, tokens) >= length &&
+ !has_prefix(tokens, last_prompt_);
+}
+
+PrefixSlotCache::user_turns_t PrefixSlotCache::find_user_turns(const std::vector& tokens, const std::vector& marker) {
+ user_turns_t turns;
+ for (size_t i = 1; i + marker.size() <= tokens.size() && !marker.empty(); i++) {
+ if (std::equal(marker.begin(), marker.end(), tokens.begin() + i)) {
+ if (turns.first == 0) turns.first = i;
+ turns.last = i;
+ }
+ }
+ return turns;
+}
+
+PrefixSlotCache::heads_t PrefixSlotCache::plan_heads(const std::vector& full_tokens, const user_turns_t& turns, size_t match_len, bool split) {
+ heads_t heads;
+ heads.boundary = turns.first >= min_boundary ? turns.first : 0;
+ heads.history = turns.last != turns.first && turns.last >= min_boundary ? turns.last : 0;
+ // A head is saved after a prefill pass of its own, which has a cost of its own whatever its length, so it is
+ // saved only when its slot is kept.
+ heads.save_boundary = split && heads.boundary > match_len && heads.boundary < full_tokens.size() && fits(heads.boundary);
+ // The history is saved only when the prompt before this one shared it and went on with another last message, as
+ // prompts with the same few-shot examples do. A chat turn only continues the turn before, and would pay for the
+ // pass every turn. It also has to add enough over the boundary slot and over the slot this prompt resumed from to
+ // be worth a slot.
+ heads.save_history = split && heads.history > 0 && heads.history < full_tokens.size() && heads.history >= heads.boundary + min_end_gain &&
+ heads.history >= match_len + min_end_gain && forked(full_tokens, heads.history) && fits(heads.history);
+ return heads;
+}
+
+bool PrefixSlotCache::fits(size_t length) {
+ if (!engine_ || slot_limit() == 0 || length == 0) return false;
+ flm_state* raw = api_->state_new(engine_);
+ if (!raw) return false; // the engine cannot save its context
+ const saved_state state(api_, raw);
+ return within_budget(state.estimate_bytes(static_cast(length), 0), length);
+}
+
+bool PrefixSlotCache::within_budget(size_t cost, size_t length) {
+ const size_t budget = budget_bytes();
+ if (cost <= budget) return true;
+ // nothing this long would ever be reused, so it is said once
+ if (!warned_too_big_) {
+ warned_too_big_ = true;
+ header_print("WARNING", "Prefix cache: a " << length << "-token prompt needs " << (cost >> 20) << " MiB, more than --prefix-cache-mb ("
+ << (budget >> 20) << " MiB); it is not saved. Raise --prefix-cache-mb to reuse prompts this long.");
+ }
+ return false;
+}
+
+int PrefixSlotCache::end_kv_from(const std::vector& tokens, const heads_t& heads) const {
+ for (const size_t head : {heads.history, heads.boundary}) {
+ // resume() puts the rows before kv_from back from the engine's live context or from a self-contained slot
+ // which starts with the same tokens, and matches both by tokens only. With pictures in the head the same
+ // tokens can hold another picture's rows, so the end slot keeps the rows of such a head itself.
+ if (head == 0 || count_image_runs(tokens, head) > 0) continue;
+ for (const auto& slot : slots_table_) {
+ if (slot.kv_from() == 0 && slot.tokens.size() == head && has_prefix(tokens, slot.tokens)) {
+ return static_cast(head);
+ }
}
}
return 0;
@@ -251,13 +309,7 @@ void PrefixSlotCache::save(const std::vector& tokens, const std::vector(length), from); };
const size_t new_cost = cost(*state, tokens.size(), kv_from);
- if (new_cost > budget) {
- // this prompt alone does not fit; say so once, since nothing would ever be reused
- if (!warned_too_big_) {
- warned_too_big_ = true;
- header_print("WARNING", "Prefix cache: a " << tokens.size() << "-token prompt needs " << (new_cost >> 20) << " MiB, more than --prefix-cache-mb ("
- << (budget >> 20) << " MiB); it is not saved. Raise --prefix-cache-mb to reuse prompts this long.");
- }
+ if (!within_budget(new_cost, tokens.size())) {
return;
}
diff --git a/src/include/AutoModel/automodel.hpp b/src/include/AutoModel/automodel.hpp
index 6a01f8a3d..ec7586d7f 100644
--- a/src/include/AutoModel/automodel.hpp
+++ b/src/include/AutoModel/automodel.hpp
@@ -352,9 +352,10 @@ class AutoModel {
/// \param tokens the prompt without its last generation-prompt tokens (what is prefilled)
/// \param full_tokens the same tokens, kept intact: _shared_insert erases the part the engine already holds from `tokens`
/// \param match_len what _prefix_resume returned
- /// \param boundary_marker the text that opens the first user turn, e.g. "<|im_start|>user": everything before it is
- /// the shared head (system + tools), saved as its own slot while prefilling when it is long enough
- /// \param payload image payload or nullptr; a prompt with images is not split at the boundary
+ /// \param boundary_marker the text that opens a user turn, e.g. "<|im_start|>user": everything before the first one is
+ /// the shared head (system + tools), saved as its own slot while prefilling when it is long enough, and everything
+ /// before the last one the history, saved as well when the prompt before this one shared it
+ /// \param payload image payload or nullptr; a prompt with images is not split at the boundary or the history
/// \param last_image_token_index as _shared_insert's first_len_run
bool _prefix_insert(PrefixSlotCache& cache, chat_meta_info_t& meta_info, std::vector& tokens, const std::vector& full_tokens,
const std::vector& image_hashes, size_t match_len, const std::string& boundary_marker,
@@ -382,7 +383,7 @@ class AutoModel {
/// \brief insert a text-only prompt through the slots (use when _prefix_slot_mode() said yes)
/// \param tokens the whole rendered prompt; its last `trim` tokens are left out of the prefill
- /// \param boundary_marker the text that opens the first user turn (see _prefix_insert)
+ /// \param boundary_marker the text that opens a user turn (see _prefix_insert)
bool _prefix_text_insert(chat_meta_info_t& meta_info, std::vector& tokens, size_t trim, const std::string& boundary_marker,
std::function is_cancelled, std::optional requested_max_new_tokens = std::nullopt);
diff --git a/src/include/prefix_slot_cache.hpp b/src/include/prefix_slot_cache.hpp
index c1fc2dbda..8a746d3ac 100644
--- a/src/include/prefix_slot_cache.hpp
+++ b/src/include/prefix_slot_cache.hpp
@@ -62,7 +62,7 @@ struct prefix_cache_report_t {
bool hit = false; ///< the request resumed from a slot
std::string miss_reason; ///< why not, when it did not
int slot = -1; ///< id of the slot resumed from (ids are never reused)
- bool slot_boundary = false; ///< that slot is a boundary slot (system + tools head) rather than an end slot
+ bool slot_boundary = false; ///< that slot is a boundary slot (a shared head) rather than an end slot
int matched_tokens = 0; ///< tokens of the prompt it covered
int prompt_tokens = 0; ///< tokens the cache considered (the prompt without its generation prompt)
struct saved_t {
@@ -95,9 +95,10 @@ class PrefixSlotCache {
/// 28% / 44% fewer snapshots. 0 saves every end snapshot.
static constexpr size_t kDefaultMinEndGain = 128;
size_t min_end_gain = kDefaultMinEndGain;
- /// \brief save boundary slots (the shared system + tools head) only, no end-of-prompt snapshots
+ /// \brief save the shared heads only (the system + tools head, and the history before the last user turn), no
+ /// end-of-prompt snapshots
/// \note For a model whose snapshot is too big to keep one per conversation turn (qwen3.8-mtp: ~160 MB of recurrent state
- /// and 64 KB per token): it keeps its own checkpoint for a conversation that continues and uses the head slot
+ /// and 64 KB per token): it keeps its own checkpoint for a conversation that continues and uses a head slot
/// when another conversation ran in between.
bool boundary_only = false;
/// \brief limits while --prefix-cache-mb / --prefix-slots stay at their defaults (0 = the global defaults)
@@ -129,17 +130,55 @@ class PrefixSlotCache {
/// \note On a restore failure every slot is forgotten and resumed is false.
resume_t resume(const std::vector& full_tokens, const std::vector& image_hashes, std::vector& matched_tokens);
+ /// \brief where the user turns of a prompt start: the first and the last marker at position 1 or later (0 = none)
+ struct user_turns_t {
+ size_t first = 0;
+ size_t last = 0;
+ };
+ /// \param marker the tokens which open a user turn
+ static user_turns_t find_user_turns(const std::vector& tokens, const std::vector& marker);
+
+ /// \brief the shared heads of a prompt, and which of them to save in prefill passes of their own (plan_heads)
+ struct heads_t {
+ size_t boundary = 0; ///< end of system + tools (the first user turn), 0 when it is before min_boundary
+ size_t history = 0; ///< start of the last user turn, 0 when it is the first one or before min_boundary
+ bool save_boundary = false; ///< prefill up to boundary first and save a boundary slot there
+ bool save_history = false; ///< prefill up to history next and save a boundary slot there too
+ };
+ /// \brief find the heads of a prompt and decide which of them to save while prefilling it
+ /// \param turns where its user turns start (find_user_turns)
+ /// \param match_len length of the slot the prompt resumed from (0 = none)
+ /// \param split whether the prompt may be prefilled in parts (false while it has pictures still to read)
+ /// \note A head is saved only when the prompt still has to read it and fits() says its slot is kept. The history is
+ /// saved only when the prompt before forked there (forked()) and it is at least min_end_gain tokens past the
+ /// boundary and past match_len.
+ heads_t plan_heads(const std::vector& full_tokens, const user_turns_t& turns, size_t match_len, bool split);
+
+ /// \brief whether save() keeps a self-contained slot of the given number of tokens
+ /// \note save() evicts any other slot to make room for one, so it refuses one only when the cache is off or the slot
+ /// alone is bigger than --prefix-cache-mb, which is logged once.
+ bool fits(size_t length);
+
/// \brief read the engine's current context into a new slot; `tokens` is what the engine holds
- /// \param boundary true for the end of system + tools (kv_from 0, evicted last)
+ /// \param boundary true for a shared head: the end of system + tools, or the history before the last user turn (kv_from 0,
+ /// evicted last)
/// \param kv_from first position whose K/V rows the slot saves (0 = self-contained)
void save(const std::vector& tokens, const std::vector& image_hashes, bool boundary, int kv_from);
- /// \brief the kv_from an end-of-prompt slot should use: `boundary` when a self-contained slot holds the first
- /// `boundary` tokens of `tokens`, else 0
- int end_kv_from(const std::vector& tokens, size_t boundary) const;
+ /// \brief the kv_from an end-of-prompt slot should use: the longer of the prompt's heads which a self-contained slot
+ /// holds with no pictures in it, else 0
+ int end_kv_from(const std::vector& tokens, const heads_t& heads) const;
/// \brief tokens whose K/V rows the engine's cache holds now (what the last request left in it)
void set_live(const std::vector& tokens) { live_tokens_ = tokens; }
+ /// \brief remember the whole prompt of a request, for forked()
+ void set_last_prompt(const std::vector& tokens) { last_prompt_ = tokens; }
+ /// \brief whether the prompt before this one holds the first length tokens of tokens and more, and tokens is not that
+ /// prompt again nor a continuation of it
+ /// \note The next turn of a chat continues the prompt before, so it is no fork. An earlier turn sent again ends inside
+ /// the prompt before, so it is one: the conversation branches there.
+ /// \note It only decides whether a head is worth a prefill pass of its own, never which rows a prompt reuses.
+ bool forked(const std::vector& tokens, size_t length) const;
/// \param announce log that the engine's context was dropped while the slots were kept (a clear or a cancel, not a cold start)
void clear_live(bool announce = false);
@@ -159,7 +198,7 @@ class PrefixSlotCache {
std::vector image_hashes; // content of the images inside `tokens`
uint64_t last_used = 0;
int id = 0; // told apart in logs and usage; never reused
- bool boundary = false; // end of system + tools; evicted last
+ bool boundary = false; // a shared head; evicted last
/// first position whose K/V rows the slot holds
int kv_from() const { return state->kv_from(); }
};
@@ -168,11 +207,14 @@ class PrefixSlotCache {
size_t budget_bytes() const;
size_t slot_limit() const;
size_t count_image_runs(const std::vector& tokens, size_t len) const;
+ /// \brief whether a slot of the given cost in bytes fits --prefix-cache-mb; warns once when it does not
+ bool within_budget(size_t cost, size_t length);
void* engine_ = nullptr; // the engine (causal_lm*), opaque to the cache
const flm_state_api* api_ = nullptr;
std::vector slots_table_;
std::vector live_tokens_;
+ std::vector last_prompt_;
uint64_t clock_ = 0;
int cache_mb_ = -1;
int slots_ = -1;
diff --git a/src/test/prefix_slot_cache/test_prefix_slot_cache.cpp b/src/test/prefix_slot_cache/test_prefix_slot_cache.cpp
index c219fa3a9..26ad61130 100644
--- a/src/test/prefix_slot_cache/test_prefix_slot_cache.cpp
+++ b/src/test/prefix_slot_cache/test_prefix_slot_cache.cpp
@@ -39,6 +39,7 @@ class fake_state final {
class fake_engine {
public:
std::vector calls;
+ std::vector kv_written; // context length of each state write_state_kv put back
int length = 0;
size_t row_bytes = 1024; // 1 KiB per row
size_t state_bytes = 1u << 20; // 1 MiB per snapshot
@@ -60,6 +61,7 @@ class fake_engine {
}
int write_state_kv(const fake_state& state) {
calls.push_back("write_kv");
+ kv_written.push_back(state.context_length);
return state.filled ? state.context_length : -1;
}
};
@@ -90,17 +92,28 @@ std::vector cat(std::vector a, const std::vector& b) {
return a;
}
-/// \brief what AutoModel::_prefix_insert does after a prefill: boundary snapshot at `head`, end snapshot at the end
-void prefill(PrefixSlotCache& cache, fake_engine& e, const std::vector& prompt, size_t head) {
- if (head > 0) {
- std::vector h(prompt.begin(), prompt.begin() + head);
- e.length = static_cast(head);
+/// \brief the calls AutoModel::_prefix_insert makes on the cache around a prefill, with the fake engine in place of the
+/// model: the heads plan_heads() picks are saved after passes of their own, then the end of the prompt
+/// \param first where the first user turn starts (0 = none)
+/// \param last where the last user turn starts (0 = none)
+/// \param match length of the slot the prompt resumed from (0 = none)
+/// \param images content hashes of the pictures of the prompt
+/// \param split false while the prompt has pictures still to read
+void prefill(PrefixSlotCache& cache, fake_engine& e, const std::vector& prompt, size_t first, size_t last = 0, size_t match = 0,
+ const std::vector& images = {}, bool split = true) {
+ const PrefixSlotCache::heads_t heads = cache.plan_heads(prompt, {first, last}, match, split);
+ auto save_head = [&](size_t length) {
+ const std::vector h(prompt.begin(), prompt.begin() + length);
+ e.length = static_cast(length);
cache.set_live(h);
- cache.save(h, {}, true, 0);
- }
+ cache.save(h, images, true, 0);
+ };
+ if (heads.save_boundary) save_head(heads.boundary);
+ if (heads.save_history) save_head(heads.history);
e.length = static_cast(prompt.size());
cache.set_live(prompt);
- cache.save(prompt, {}, false, cache.end_kv_from(prompt, head));
+ cache.set_last_prompt(prompt);
+ if (!cache.boundary_only) cache.save(prompt, images, false, cache.end_kv_from(prompt, heads));
}
size_t resume(PrefixSlotCache& cache, const std::vector& prompt, const std::vector& images = {}) {
@@ -212,6 +225,169 @@ void test_boundary_kept_for_dependents() {
CHECK(resume(cache, cat(sys, seq(8000, 5))) == sys.size());
}
+void test_shared_history() {
+ std::printf("prompts sharing everything before their last user turn resume there from the second one on, and that slot outlives the end slots\n");
+ fake_engine e;
+ PrefixSlotCache cache = make(e, 100000, 4);
+ // a system prompt too short for a boundary slot, followed by few-shot examples
+ const auto history = seq(1, 1500);
+ prefill(cache, e, cat(history, seq(5000, 100)), 0, history.size()); // no prompt before it: only E1
+ CHECK(cache.slot_count() == 1);
+ const auto q2 = cat(history, seq(6000, 100));
+ CHECK(resume(cache, q2) == 0);
+ prefill(cache, e, q2, 0, history.size()); // forked from the first: H, E2 (kv_from 1500)
+ CHECK(cache.slot_count() == 3);
+ for (int i = 0; i < 6; i++) {
+ const auto q = cat(history, seq(7000 + 1000 * i, 100));
+ CHECK(resume(cache, q) == history.size());
+ prefill(cache, e, q, 0, history.size(), history.size()); // resumed at H: only an end slot is added
+ }
+ // the end slots were evicted, least recently used first, and H, which they need, stayed
+ CHECK(cache.slot_count() == 4);
+ cache.clear_live();
+ CHECK(resume(cache, cat(history, seq(20000, 100))) == history.size());
+}
+
+void test_chat_saves_no_history() {
+ std::printf("a chat turn, which only continues the turn before, saves no slot before its last user turn\n");
+ fake_engine e;
+ PrefixSlotCache cache = make(e, 100000, 8);
+ const auto sys = seq(1, 600);
+ const auto turn1 = cat(sys, seq(5000, 200));
+ prefill(cache, e, turn1, 600); // one user turn: B, E1
+ const auto history2 = cat(turn1, seq(6000, 300)); // turn 1 with its reply, and the start of turn 2
+ const auto turn2 = cat(history2, seq(7000, 200));
+ CHECK(resume(cache, turn2) == turn1.size());
+ prefill(cache, e, turn2, 600, history2.size(), turn1.size()); // continues turn 1: E2 only
+ CHECK(cache.slot_count() == 3);
+ CHECK(resume(cache, cat(history2, seq(8000, 30))) == turn1.size());
+ // a prompt which shares the history of turn 2 but asks something else is a fork: it saves the history slot
+ const auto other = cat(history2, seq(9000, 200));
+ CHECK(resume(cache, other) == turn1.size());
+ prefill(cache, e, other, 600, history2.size(), turn1.size());
+ CHECK(resume(cache, cat(history2, seq(10000, 30))) == history2.size());
+}
+
+void test_find_user_turns() {
+ std::printf("user turns are found by all of their marker tokens: the first and the last one, none at position 0\n");
+ const std::vector marker = {50000, 50001};
+ const auto turn = [&](int from) { return cat(marker, seq(from, 10)); };
+ const auto prompt = cat(cat(cat(seq(1, 5), turn(100)), turn(200)), turn(300)); // turns at 5, 17 and 29
+ auto t = PrefixSlotCache::find_user_turns(prompt, marker);
+ CHECK(t.first == 5 && t.last == 29);
+ t = PrefixSlotCache::find_user_turns(cat(turn(100), turn(200)), marker);
+ CHECK(t.first == 12 && t.last == 12);
+ t = PrefixSlotCache::find_user_turns(cat(seq(1, 5), {50000, 7, 50001}), marker);
+ CHECK(t.first == 0 && t.last == 0);
+ t = PrefixSlotCache::find_user_turns(prompt, {});
+ CHECK(t.first == 0 && t.last == 0);
+}
+
+void test_forked() {
+ std::printf("a prompt forks from the prompt before when that one holds the history and more, and the prompt does not continue it\n");
+ fake_engine e;
+ PrefixSlotCache cache = make(e);
+ const auto history = seq(1, 1000);
+ const auto p1 = cat(history, seq(5000, 100));
+ CHECK(!cache.forked(p1, 1000)); // no prompt before it
+ cache.set_last_prompt(p1);
+ CHECK(cache.forked(cat(history, seq(6000, 100)), 1000)); // another last message
+ CHECK(cache.forked(cat(history, seq(6000, 10)), 1000)); // a shorter one
+ CHECK(cache.forked(cat(history, seq(5000, 50)), 1000)); // it ends inside the prompt before (an earlier turn again)
+ CHECK(!cache.forked(p1, 1000)); // the same prompt again (a retry)
+ CHECK(!cache.forked(cat(p1, seq(7000, 50)), 1000)); // it continues the prompt before (a chat turn)
+ CHECK(!cache.forked(cat(seq(1, 999), seq(6000, 101)), 1000)); // it differs before the history ends
+ CHECK(!cache.forked(cat(history, seq(6000, 100)), 1200)); // the history is longer than the prompt
+ cache.forget_all();
+ CHECK(!cache.forked(cat(history, seq(6000, 100)), 1000));
+}
+
+void test_plan_heads() {
+ std::printf("plan_heads: which heads a prompt saves in prefill passes of their own\n");
+ fake_engine e;
+ PrefixSlotCache cache = make(e, 100000, 8);
+ const auto prompt = cat(seq(1, 2000), seq(5000, 100));
+ const PrefixSlotCache::user_turns_t turns{600, 2000};
+ cache.set_last_prompt(cat(seq(1, 2000), seq(6000, 100))); // the prompt before forked at 2000
+ auto h = cache.plan_heads(prompt, turns, 0, true);
+ CHECK(h.boundary == 600 && h.history == 2000 && h.save_boundary && h.save_history);
+ // pictures still to read: the prompt is not split
+ h = cache.plan_heads(prompt, turns, 0, false);
+ CHECK(h.boundary == 600 && h.history == 2000 && !h.save_boundary && !h.save_history);
+ // resumed at the boundary: only the history is left to save
+ h = cache.plan_heads(prompt, turns, 600, true);
+ CHECK(!h.save_boundary && h.save_history);
+ // resumed less than --prefix-min-gain (64 here) before the history, or the history that close to the boundary
+ h = cache.plan_heads(prompt, turns, 1950, true);
+ CHECK(!h.save_boundary && !h.save_history);
+ h = cache.plan_heads(prompt, {1950, 2000}, 0, true);
+ CHECK(h.save_boundary && !h.save_history);
+ // a head before min_boundary (512) is none, and a single user turn has no history
+ h = cache.plan_heads(prompt, {500, 2000}, 0, true);
+ CHECK(h.boundary == 0 && h.history == 2000 && !h.save_boundary && h.save_history);
+ h = cache.plan_heads(prompt, {600, 600}, 0, true);
+ CHECK(h.boundary == 600 && h.history == 0 && h.save_boundary && !h.save_history);
+ h = cache.plan_heads(prompt, {100, 400}, 0, true);
+ CHECK(h.boundary == 0 && h.history == 0 && !h.save_boundary && !h.save_history);
+ // a prompt which continues the prompt before (a chat turn) is no fork
+ cache.set_last_prompt(seq(1, 1500));
+ h = cache.plan_heads(prompt, turns, 0, true);
+ CHECK(h.save_boundary && !h.save_history);
+}
+
+void test_head_not_kept_not_split() {
+ std::printf("a head whose slot would not be kept costs no prefill pass\n");
+ const auto prompt = cat(seq(1, 3000), seq(5000, 100));
+ const auto before = cat(seq(1, 3000), seq(6000, 100));
+ // 1 MiB state + 1 KiB per row: 3 MiB holds a 1000-row slot, not a 3000-row one
+ fake_engine e;
+ PrefixSlotCache cache = make(e, 3, 8);
+ cache.set_last_prompt(before);
+ auto h = cache.plan_heads(prompt, {1000, 3000}, 0, true);
+ CHECK(h.save_boundary && !h.save_history);
+ fake_engine off_e;
+ PrefixSlotCache off = make(off_e, -1, 0);
+ off.set_last_prompt(before);
+ h = off.plan_heads(prompt, {1000, 3000}, 0, true);
+ CHECK(!h.save_boundary && !h.save_history);
+}
+
+void test_history_with_pictures() {
+ std::printf("an end slot keeps the rows of a head with pictures itself, so another picture's rows never go under it\n");
+ fake_engine e;
+ PrefixSlotCache cache = make(e, 100000, 8);
+ cache.image_token_id = 99999; // not a token of seq()
+ const auto sys = seq(1, 600);
+ prefill(cache, e, cat(sys, seq(3000, 100)), 600); // a text conversation: B
+ // a chat with picture A in its first turn, then an edited second turn: a history slot with picture A
+ const auto c1 = cat(cat(sys, std::vector(16, 99999)), seq(2000, 100));
+ CHECK(resume(cache, c1, {111}) == sys.size());
+ prefill(cache, e, c1, 600, 600, sys.size(), {111}, false); // E1 from row 600, picture A read
+ const auto history = cat(c1, seq(2500, 300)); // the reply, up to the second user turn
+ const auto c2 = cat(history, seq(4000, 100));
+ CHECK(resume(cache, c2, {111}) == c1.size());
+ prefill(cache, e, c2, 600, history.size(), c1.size(), {111});
+ const auto c3 = cat(history, seq(4500, 100));
+ CHECK(resume(cache, c3, {111}) == c1.size());
+ cache.begin_report();
+ prefill(cache, e, c3, 600, history.size(), c1.size(), {111}); // a fork of c2: H with picture A
+ auto rep = cache.report();
+ CHECK(rep.saved.size() == 2 && rep.saved[0].boundary && rep.saved[0].tokens == static_cast(history.size()));
+ CHECK(rep.saved[1].kv_from == static_cast(sys.size())); // the end slot keeps the picture's rows
+ // the same tokens with picture B: H does not serve it, and its end slot keeps the rows from the boundary on
+ const auto p4 = cat(history, seq(8000, 100));
+ CHECK(resume(cache, p4, {222}) == sys.size());
+ cache.begin_report();
+ prefill(cache, e, p4, 600, history.size(), sys.size(), {222}, false);
+ rep = cache.report();
+ CHECK(rep.saved.size() == 1 && rep.saved[0].kv_from == static_cast(sys.size()));
+ // once the live context is gone, its head rows come from B, not from H with picture A
+ cache.clear_live();
+ e.kv_written.clear();
+ CHECK(resume(cache, cat(p4, seq(9000, 5)), {222}) == p4.size());
+ CHECK(e.kv_written == std::vector{600});
+}
+
void test_small_tail_not_saved() {
std::printf("a side call a few tokens past the shared head is not saved, so it cannot push out the main conversation\n");
fake_engine e;
@@ -349,9 +525,11 @@ void test_picture_replaced_keeps_others() {
CHECK(resume(cache, y, {111}) == sys.size());
e.length = static_cast(y.size());
cache.set_live(y);
- cache.save(y, {111}, false, cache.end_kv_from(y, 600)); // EY
+ PrefixSlotCache::heads_t at_sys;
+ at_sys.boundary = 600;
+ cache.save(y, {111}, false, cache.end_kv_from(y, at_sys)); // EY
CHECK(cache.slot_count() == 3);
- cache.save(y, {222}, false, cache.end_kv_from(y, 600)); // the same question about another picture
+ cache.save(y, {222}, false, cache.end_kv_from(y, at_sys)); // the same question about another picture
CHECK(cache.slot_count() == 3);
CHECK(resume(cache, cat(y, seq(7000, 5)), {222}) == y.size());
CHECK(resume(cache, cat(y, seq(7000, 5)), {111}) == sys.size());
@@ -429,6 +607,13 @@ int main() {
test_head_restored_after_cold_request();
test_eviction_order();
test_boundary_kept_for_dependents();
+ test_shared_history();
+ test_chat_saves_no_history();
+ test_find_user_turns();
+ test_forked();
+ test_plan_heads();
+ test_head_not_kept_not_split();
+ test_history_with_pictures();
test_small_tail_not_saved();
test_min_end_gain();
test_budget();