Skip to main content

ferrox_models/
prefix_cache.rs

1//! KV-prefix caching: when a new request's tokens share a leading
2//! subsequence with a previously processed request, skip recomputing
3//! the KV state for that shared prefix entirely, restoring it from a
4//! stored snapshot instead of running `forward_batch` over tokens
5//! that were already processed.
6//!
7//! This is the harder sibling of `ferrox-server::cache::ResponseCache`
8//! (which only helps *exact*-repeat requests): prefix caching helps
9//! any request that *starts with* something seen before, which is the
10//! common case for multi-turn chat (each turn's full prompt is the
11//! previous turn's prompt plus a little more) even when no single
12//! request repeats exactly.
13//!
14//! Deliberately scoped: this does a linear scan over a small,
15//! LRU-bounded set of stored prefixes to find the longest common
16//! prefix, not a trie/radix-tree structure (vLLM's and SGLang's
17//! RadixAttention do this properly at production scale). For the
18//! small number of concurrent conversations a demo server actually
19//! handles, a linear scan is simpler and correctness is easier to
20//! verify.
21//!
22//! "LRU-bounded" is now true. It was not: eviction dropped the oldest
23//! ARRIVAL while nothing on the hit path recorded that an entry had
24//! been used, so the policy was first-in-first-out under an LRU name.
25//! That inverted the cache's purpose, because the entry a prefix cache
26//! exists for -- the system prompt every request shares -- is the
27//! oldest one precisely because it is the most reused.
28//!
29//! What is still true of the scope: each entry CLONES its
30//! `Vec<KvCache>`, so N conversations off one system prompt hold N
31//! copies of its KV rather than sharing the pages. Fixing that is the
32//! radix cache's job (`ferrox_edge::radix`), which shares nodes and
33//! reference-counts pages, and which needs a serving path that reads
34//! paged KV before it can be wired in.
35
36use ferrox_core::cache::KvCache;
37
38/// A stored snapshot: the tokens processed so far, the resulting
39/// per-layer KV cache state, and the logits that predict the token
40/// immediately after `tokens` (needed so a request that matches this
41/// prefix *exactly* -- no new tokens at all -- doesn't need any
42/// computation to know what to generate next).
43#[derive(Clone)]
44struct StoredPrefix {
45    tokens: Vec<usize>,
46    kv_caches: Vec<KvCache>,
47    pending_logits: Vec<f32>,
48    /// Monotonic recency stamp; smallest = least recently used.
49    ///
50    /// A stamp per touch rather than reshuffling a dedicated LRU list,
51    /// the same shape `ferrox_core::expert_store` uses and for the same
52    /// reason: eviction pays an O(n) scan, which costs nothing here
53    /// because the lookup that precedes it is already O(n) over the
54    /// same vector.
55    last_used: u64,
56}
57
58/// LRU-bounded store of `StoredPrefix` snapshots, searched for the
59/// longest common prefix with an incoming token sequence.
60pub struct PrefixCache {
61    entries: Vec<StoredPrefix>,
62    max_entries: usize,
63    hits_positions_reused: u64,
64    hits_count: u64,
65    misses_count: u64,
66    /// Ticks on every hit and every store, so `last_used` orders
67    /// entries by when they were last USEFUL rather than by when they
68    /// arrived.
69    clock: u64,
70}
71
72/// What was found (or not) for an incoming token sequence.
73pub struct PrefixMatch {
74    /// How many leading tokens matched a stored prefix (0 if none).
75    pub matched_len: usize,
76    /// Restored KV cache state covering exactly `matched_len`
77    /// positions, ready to continue from. `None` if `matched_len == 0`.
78    pub kv_caches: Option<Vec<KvCache>>,
79    /// Logits predicting the token at position `matched_len`, valid
80    /// only when `matched_len > 0`.
81    pub pending_logits: Option<Vec<f32>>,
82}
83
84impl PrefixCache {
85    pub fn new(max_entries: usize) -> Self {
86        PrefixCache {
87            entries: Vec::new(),
88            max_entries,
89            hits_positions_reused: 0,
90            hits_count: 0,
91            misses_count: 0,
92            clock: 0,
93        }
94    }
95
96    /// Drops every stored prefix, keeping the capacity and the
97    /// lifetime hit/miss counters.
98    ///
99    /// For a KV-side cache rebuild. A stored prefix names positions in
100    /// an allocation that is about to stop existing, so handing one back
101    /// afterwards would restore another request's state into this one --
102    /// silently, since a KV cache carries no identity of its own. The
103    /// counters survive because they describe what this process has
104    /// served, which a re-split does not undo.
105    pub fn clear(&mut self) {
106        self.entries.clear();
107    }
108
109    /// Finds the stored prefix with the longest common leading
110    /// subsequence with `tokens`, and returns a ready-to-use clone of
111    /// its KV state truncated to exactly that common length (a stored
112    /// prefix may itself be longer than the common part, if a later,
113    /// different continuation was stored under it -- the KV cache is
114    /// truncated to the matching length before being handed back, so
115    /// the caller never sees state from a divergent continuation).
116    pub fn find_longest_prefix(&mut self, tokens: &[usize]) -> PrefixMatch {
117        let mut best: Option<(usize, usize)> = None; // (matched_len, index)
118        for (i, entry) in self.entries.iter().enumerate() {
119            let common = common_prefix_len(&entry.tokens, tokens);
120            if common > 0 && best.map(|(len, _)| common > len).unwrap_or(true) {
121                best = Some((common, i));
122            }
123        }
124
125        match best {
126            Some((matched_len, index)) => {
127                self.hits_count += 1;
128                self.hits_positions_reused += matched_len as u64;
129                // A HIT is what makes an entry worth keeping, so this
130                // is where recency has to be recorded. Without it the
131                // policy degenerates to first-in-first-out, and the one
132                // entry a prefix cache exists for -- a shared system
133                // prompt every request starts with -- is evicted as
134                // soon as `max_entries` newer prompts arrive, however
135                // often it is being reused.
136                self.clock += 1;
137                self.entries[index].last_used = self.clock;
138                let entry = &self.entries[index];
139
140                let mut kv_caches = entry.kv_caches.clone();
141                for cache in kv_caches.iter_mut() {
142                    cache.truncate(matched_len);
143                }
144
145                // The stored pending_logits predict the token
146                // immediately after entry.tokens' FULL length. They're
147                // only valid to hand back if the match covers that
148                // entire stored sequence (matched_len ==
149                // entry.tokens.len()); a partial match into the middle
150                // of a longer stored sequence means the caller is
151                // asking about position `matched_len`, not
152                // `entry.tokens.len()`, and reusing the stored logits
153                // there would silently answer the wrong question.
154                let pending_logits = if matched_len == entry.tokens.len() {
155                    Some(entry.pending_logits.clone())
156                } else {
157                    None
158                };
159
160                PrefixMatch {
161                    matched_len,
162                    kv_caches: Some(kv_caches),
163                    pending_logits,
164                }
165            }
166            None => {
167                self.misses_count += 1;
168                PrefixMatch {
169                    matched_len: 0,
170                    kv_caches: None,
171                    pending_logits: None,
172                }
173            }
174        }
175    }
176
177    /// Stores a snapshot for `tokens` (all tokens processed so far,
178    /// prompt plus any generated continuation) with the given KV cache
179    /// state and next-token logits, evicting the least recently USED
180    /// entry if already at capacity.
181    ///
182    /// Used, not stored. This used to drop `entries[0]` -- the oldest
183    /// arrival -- while the type documented itself as LRU-bounded. The
184    /// difference is the whole value of the cache: a system prompt that
185    /// every request shares is the oldest entry precisely BECAUSE it is
186    /// the most reused, so FIFO evicted the one entry worth keeping as
187    /// soon as `max_entries` newer prompts arrived, and the next
188    /// request off that system prompt recomputed all of it.
189    pub fn store(&mut self, tokens: Vec<usize>, kv_caches: Vec<KvCache>, pending_logits: Vec<f32>) {
190        if self.entries.len() >= self.max_entries {
191            // An O(n) scan, over the same vector the lookup above
192            // already scans linearly -- so this costs nothing the
193            // design was not already paying.
194            if let Some(coldest) = self
195                .entries
196                .iter()
197                .enumerate()
198                .min_by_key(|(i, e)| (e.last_used, *i))
199                .map(|(i, _)| i)
200            {
201                self.entries.remove(coldest);
202            }
203        }
204        self.clock += 1;
205        self.entries.push(StoredPrefix {
206            last_used: self.clock,
207            tokens,
208            kv_caches,
209            pending_logits,
210        });
211    }
212
213    pub fn stats(&self) -> PrefixCacheStats {
214        PrefixCacheStats {
215            hits: self.hits_count,
216            misses: self.misses_count,
217            entries: self.entries.len(),
218            total_positions_reused: self.hits_positions_reused,
219        }
220    }
221}
222
223#[derive(Debug, Clone, Copy, Default, serde::Serialize)]
224pub struct PrefixCacheStats {
225    pub hits: u64,
226    pub misses: u64,
227    pub entries: usize,
228    pub total_positions_reused: u64,
229}
230
231fn common_prefix_len(a: &[usize], b: &[usize]) -> usize {
232    a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count()
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238
239    fn dummy_cache(seq_len: usize) -> KvCache {
240        let mut cache = KvCache::new(1, 1);
241        for i in 0..seq_len {
242            cache.push(&[i as f32], &[i as f32 * 10.0]).unwrap();
243        }
244        cache
245    }
246
247    /// The bug this type was named after and did not have.
248    ///
249    /// A shared system prompt is the entry a prefix cache exists for,
250    /// and under FIFO it was the FIRST thing evicted -- it is the
251    /// oldest arrival precisely because it is the most reused. Here it
252    /// is kept hot by hits while `max_entries` newer prompts arrive,
253    /// and it must survive.
254    #[test]
255    fn a_prefix_that_keeps_being_hit_survives_newer_arrivals() {
256        let system: Vec<usize> = (0..8).collect();
257        let mut cache = PrefixCache::new(3);
258        cache.store(system.clone(), vec![dummy_cache(system.len())], vec![0.5]);
259
260        // Three unrelated prompts arrive, which is capacity twice over.
261        // Between each, the system prompt is used again.
262        for n in 0..3usize {
263            let hit = cache.find_longest_prefix(&system);
264            assert_eq!(
265                hit.matched_len,
266                system.len(),
267                "the system prompt must still be here before arrival {n}"
268            );
269            let other: Vec<usize> = (100 + n * 10..100 + n * 10 + 4).collect();
270            cache.store(other.clone(), vec![dummy_cache(other.len())], vec![0.5]);
271        }
272
273        let hit = cache.find_longest_prefix(&system);
274        assert_eq!(
275            hit.matched_len,
276            system.len(),
277            "a hot prefix was evicted while cold newer ones were kept"
278        );
279    }
280
281    /// And the converse: the entry nobody has touched is the one that
282    /// goes. Without this the first test could pass by never evicting
283    /// anything at all.
284    #[test]
285    fn the_least_recently_used_prefix_is_the_one_evicted() {
286        let mut cache = PrefixCache::new(2);
287        let cold: Vec<usize> = vec![1, 2, 3, 4];
288        let warm: Vec<usize> = vec![5, 6, 7, 8];
289        cache.store(cold.clone(), vec![dummy_cache(cold.len())], vec![0.5]);
290        cache.store(warm.clone(), vec![dummy_cache(warm.len())], vec![0.5]);
291
292        // Touch `warm` only, then push past capacity.
293        assert_eq!(cache.find_longest_prefix(&warm).matched_len, warm.len());
294        let fresh: Vec<usize> = vec![9, 10, 11, 12];
295        cache.store(fresh.clone(), vec![dummy_cache(fresh.len())], vec![0.5]);
296
297        assert_eq!(
298            cache.find_longest_prefix(&cold).matched_len,
299            0,
300            "the untouched entry should have been evicted"
301        );
302        assert_eq!(cache.find_longest_prefix(&warm).matched_len, warm.len());
303        assert_eq!(cache.find_longest_prefix(&fresh).matched_len, fresh.len());
304    }
305
306    /// With nothing ever hit, eviction still has to make progress and
307    /// has to be deterministic: equal stamps break toward the lower
308    /// index, so the oldest arrival goes, which is the FIFO behaviour
309    /// as a degenerate case rather than as the policy.
310    #[test]
311    fn untouched_entries_evict_oldest_first_and_capacity_is_never_exceeded() {
312        let mut cache = PrefixCache::new(2);
313        for n in 0..5usize {
314            let p: Vec<usize> = (n * 10..n * 10 + 4).collect();
315            cache.store(p.clone(), vec![dummy_cache(p.len())], vec![0.5]);
316        }
317        assert_eq!(cache.entries.len(), 2, "capacity must hold");
318        // The two most recent survive.
319        for n in [3usize, 4] {
320            let p: Vec<usize> = (n * 10..n * 10 + 4).collect();
321            assert_eq!(cache.find_longest_prefix(&p).matched_len, 4, "prompt {n}");
322        }
323        for n in [0usize, 1, 2] {
324            let p: Vec<usize> = (n * 10..n * 10 + 4).collect();
325            assert_eq!(cache.find_longest_prefix(&p).matched_len, 0, "prompt {n}");
326        }
327    }
328
329    #[test]
330    fn empty_cache_always_misses() {
331        let mut cache = PrefixCache::new(4);
332        let m = cache.find_longest_prefix(&[1, 2, 3]);
333        assert_eq!(m.matched_len, 0);
334        assert!(m.kv_caches.is_none());
335        assert_eq!(cache.stats().misses, 1);
336    }
337
338    #[test]
339    fn exact_prefix_match_returns_full_length_and_pending_logits() {
340        let mut cache = PrefixCache::new(4);
341        cache.store(vec![1, 2, 3], vec![dummy_cache(3)], vec![0.1, 0.2]);
342
343        let m = cache.find_longest_prefix(&[1, 2, 3]);
344        assert_eq!(m.matched_len, 3);
345        assert!(m.kv_caches.is_some());
346        assert_eq!(m.pending_logits, Some(vec![0.1, 0.2]));
347        assert_eq!(cache.stats().hits, 1);
348    }
349
350    #[test]
351    fn extended_request_matches_the_shared_prefix_length() {
352        let mut cache = PrefixCache::new(4);
353        cache.store(vec![1, 2, 3, 4, 5], vec![dummy_cache(5)], vec![9.9]);
354
355        // New request extends the stored one with two more tokens.
356        let m = cache.find_longest_prefix(&[1, 2, 3, 4, 5, 6, 7]);
357        assert_eq!(
358            m.matched_len, 5,
359            "must match the full stored prefix, not just a partial one"
360        );
361        assert_eq!(m.pending_logits, Some(vec![9.9]));
362    }
363
364    #[test]
365    fn partial_divergent_match_returns_only_the_common_length_and_no_stale_logits() {
366        let mut cache = PrefixCache::new(4);
367        cache.store(vec![1, 2, 3, 4, 5], vec![dummy_cache(5)], vec![9.9]);
368
369        // Diverges after the first 3 tokens.
370        let m = cache.find_longest_prefix(&[1, 2, 3, 9, 9]);
371        assert_eq!(m.matched_len, 3);
372        assert!(
373            m.kv_caches.is_some(),
374            "a real KV-state saving still exists for the matched prefix"
375        );
376        assert!(
377            m.pending_logits.is_none(),
378            "stored pending_logits predicted the token after the FULL stored sequence, not after the partial match point -- must not be reused here"
379        );
380    }
381
382    #[test]
383    fn no_common_prefix_at_all_is_a_clean_miss() {
384        let mut cache = PrefixCache::new(4);
385        cache.store(vec![1, 2, 3], vec![dummy_cache(3)], vec![1.0]);
386        let m = cache.find_longest_prefix(&[9, 8, 7]);
387        assert_eq!(m.matched_len, 0);
388    }
389
390    #[test]
391    fn picks_the_longest_match_among_several_stored_entries() {
392        let mut cache = PrefixCache::new(4);
393        cache.store(vec![1, 2], vec![dummy_cache(2)], vec![0.0]);
394        cache.store(vec![1, 2, 3, 4], vec![dummy_cache(4)], vec![0.0]);
395        cache.store(vec![1, 2, 3], vec![dummy_cache(3)], vec![0.0]);
396
397        let m = cache.find_longest_prefix(&[1, 2, 3, 4, 5]);
398        assert_eq!(
399            m.matched_len, 4,
400            "the longest stored prefix that's actually a prefix of the query must win"
401        );
402    }
403
404    #[test]
405    fn evicts_oldest_entry_when_at_capacity() {
406        let mut cache = PrefixCache::new(2);
407        cache.store(vec![1, 1], vec![dummy_cache(2)], vec![0.0]);
408        cache.store(vec![2, 2], vec![dummy_cache(2)], vec![0.0]);
409        cache.store(vec![3, 3], vec![dummy_cache(2)], vec![0.0]); // evicts [1,1]
410
411        assert_eq!(
412            cache.find_longest_prefix(&[1, 1]).matched_len,
413            0,
414            "oldest entry must have been evicted"
415        );
416        assert_eq!(cache.find_longest_prefix(&[2, 2]).matched_len, 2);
417        assert_eq!(cache.find_longest_prefix(&[3, 3]).matched_len, 2);
418    }
419
420    #[test]
421    fn stats_track_positions_reused_not_just_hit_count() {
422        let mut cache = PrefixCache::new(4);
423        cache.store(
424            vec![1, 2, 3, 4, 5, 6, 7, 8],
425            vec![dummy_cache(8)],
426            vec![0.0],
427        );
428        cache.find_longest_prefix(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
429        assert_eq!(
430            cache.stats().total_positions_reused,
431            8,
432            "should report exactly how many positions were reused, not just that a hit occurred"
433        );
434    }
435
436    /// The end-to-end property that matters most: using a prefix
437    /// cache's restored KV state to continue a real decoder must
438    /// produce EXACTLY the same output as processing the full token
439    /// sequence from scratch. If this fails, prefix caching is not a
440    /// safe optimization -- it would silently change model output
441    /// depending on cache state, which is far worse than no caching at
442    /// all.
443    #[test]
444    fn prefix_cached_continuation_matches_from_scratch_decode_exactly() {
445        use crate::config::glm_5_2;
446        use crate::decoder::Decoder;
447        use ferrox_core::cache::KvCache as RealKvCache;
448
449        let mut cfg = glm_5_2();
450        cfg.hidden_dim = 16;
451        cfg.n_heads = 4;
452        cfg.n_kv_heads = 2;
453        cfg.head_dim = 4;
454        cfg.moe.hidden_dim = 16;
455        cfg.moe.n_experts = 6;
456        cfg.moe.n_experts_active = 2;
457        cfg.moe.n_shared_experts = 1;
458        cfg.moe.expert_ffn_dim = 8;
459        let vocab = 16;
460
461        let shared_prefix = vec![1usize, 2, 3, 4, 5];
462        let full_sequence = vec![1usize, 2, 3, 4, 5, 6, 7];
463
464        // "Conversation A": process the shared prefix once, store it.
465        let decoder_a = Decoder::new_random_small(cfg.clone(), 2, vocab);
466        let mut caches_a: Vec<RealKvCache> = (0..2)
467            .map(|_| RealKvCache::new(decoder_a.config.n_kv_heads, decoder_a.config.head_dim))
468            .collect();
469        let prefix_logits = decoder_a.forward_batch(&shared_prefix, 0, &mut caches_a);
470        let mut prefix_cache = PrefixCache::new(4);
471        prefix_cache.store(
472            shared_prefix.clone(),
473            caches_a,
474            prefix_logits.last().unwrap().clone(),
475        );
476
477        // "Conversation B": extends the shared prefix. Using the
478        // prefix cache, only the new suffix tokens should need
479        // computing.
480        let decoder_b = Decoder::new_random_small(cfg.clone(), 2, vocab); // same seed => identical weights
481        let m = prefix_cache.find_longest_prefix(&full_sequence);
482        assert_eq!(m.matched_len, 5);
483        let mut restored_caches = m.kv_caches.unwrap();
484        let suffix = &full_sequence[m.matched_len..];
485        let via_prefix_cache_logits =
486            decoder_b.forward_batch(suffix, m.matched_len, &mut restored_caches);
487
488        // Ground truth: process the ENTIRE sequence from scratch on an
489        // identically-seeded decoder with a fresh empty cache.
490        let decoder_c = Decoder::new_random_small(cfg, 2, vocab);
491        let mut fresh_caches: Vec<RealKvCache> = (0..2)
492            .map(|_| RealKvCache::new(decoder_c.config.n_kv_heads, decoder_c.config.head_dim))
493            .collect();
494        let from_scratch_logits = decoder_c.forward_batch(&full_sequence, 0, &mut fresh_caches);
495
496        // The prefix-cache path's logits for the suffix positions must
497        // match the from-scratch path's logits for those same
498        // positions exactly.
499        let from_scratch_suffix = &from_scratch_logits[m.matched_len..];
500        assert_eq!(via_prefix_cache_logits.len(), from_scratch_suffix.len());
501        for (pos, (a, b)) in via_prefix_cache_logits
502            .iter()
503            .zip(from_scratch_suffix.iter())
504            .enumerate()
505        {
506            for (i, (x, y)) in a.iter().zip(b.iter()).enumerate() {
507                assert!(
508                    (x - y).abs() < 1e-3,
509                    "suffix position {pos}, logit {i}: via_prefix_cache={x} from_scratch={y}"
510                );
511            }
512        }
513
514        // And the KV cache state itself must match too, not just the
515        // final logits (in case a later request extends even further).
516        for (restored, fresh) in restored_caches.iter().zip(fresh_caches.iter()) {
517            assert_eq!(restored.seq_len, fresh.seq_len);
518            for (a, b) in restored.k.iter().zip(fresh.k.iter()) {
519                assert!((a - b).abs() < 1e-3);
520            }
521        }
522    }
523}