Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions docs/docs/instructions/server/prefix_cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)<br>**Llama and DeepSeek:** `llama3.2:1b` / `3b`, `llama3.1:8b`, `deepseek-r1:8b`, `deepseek-r1-0528:8b`<br>**Phi and Nanbeige:** `phi4-mini-it:4b`, `nanbeige4.1:3b`<br>**LFM:** `lfm2:1.2b`, `lfm2:2.6b`, `lfm2-trans:2.6b`, `lfm2.5-it:1.2b`, `lfm2.5-tk:1.2b`<br>**gpt-oss:** `gpt-oss:20b`, `gpt-oss-sg:20b`<br>**Gemma:** `gemma3:1b`, `gemma3:4b`, `medgemma:4b`, `medgemma1.5:4b`, `translategemma:4b`, `gemma4-it:e2b` / `e4b` / `12b`, `nemotron3.5-bolt:e4b`<br>**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)<br>**Llama and DeepSeek:** `llama3.2:1b` / `3b`, `llama3.1:8b`, `deepseek-r1:8b`, `deepseek-r1-0528:8b`<br>**Phi and Nanbeige:** `phi4-mini-it:4b`, `nanbeige4.1:3b`<br>**LFM:** `lfm2:1.2b`, `lfm2:2.6b`, `lfm2-trans:2.6b`, `lfm2.5-it:1.2b`, `lfm2.5-tk:1.2b`<br>**gpt-oss:** `gpt-oss:20b`, `gpt-oss-sg:20b`<br>**Gemma:** `gemma3:1b`, `gemma3:4b`, `medgemma:4b`, `medgemma1.5:4b`, `translategemma:4b`, `gemma4-it:e2b` / `e4b` / `12b`, `nemotron3.5-bolt:e4b`<br>**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. |

Expand Down Expand Up @@ -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.

---

Expand All @@ -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.
Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/models/qwen.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 26 additions & 24 deletions src/common/AutoModel/automodel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -504,34 +504,35 @@ bool AutoModel::_prefix_insert(PrefixSlotCache& cache, chat_meta_info_t& meta_in
std::optional<int> 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<int> 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<int> 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<int> 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<int> 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<int> 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
Expand All @@ -546,9 +547,10 @@ bool AutoModel::_prefix_insert(PrefixSlotCache& cache, chat_meta_info_t& meta_in
meta_info.cached_prompt_tokens = static_cast<int>(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;
Expand Down
76 changes: 64 additions & 12 deletions src/common/prefix_slot_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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<int>& 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<int>(boundary);
bool PrefixSlotCache::forked(const std::vector<int>& 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<int>& tokens, const std::vector<int>& 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<int>& 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<int>(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<int>& 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<int>(head);
}
}
}
return 0;
Expand Down Expand Up @@ -251,13 +309,7 @@ void PrefixSlotCache::save(const std::vector<int>& tokens, const std::vector<uin
const size_t limit = slot_limit();
auto cost = [](const saved_state& s, size_t length, int from) { return s.estimate_bytes(static_cast<int>(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;
}

Expand Down
Loading