interplane.Get Omega
Read in your language

MojoLlama

Archived Mojo/MAX quantizer and serving research repository (read-only history)

Brought by drakestapleton

branch main Branches Tags History

MojoLlama / src / mojollama / prefix_cache.py

222 lines · 8464 bytes Raw Blame History
1#!/usr/bin/env python3
2"""Prefix caching for KV cache reuse across requests.
3
4Stores KV cache snapshots indexed by a hash of the first N token prefix.
5On match, the cached KV data can be copied into a new KVBlock, advancing
6the sequence length to the cached length before processing remaining tokens.
7
8Usage:
9 from mojollama.prefix_cache import PrefixCache
10 cache = PrefixCache(max_entries=64, prefix_len=8)
11
12 # Store a KV snapshot for a given token prefix
13 cache.put(tokens_tuple, kv_snapshot)
14
15 # Retrieve — returns kv_snapshot or None
16 match = cache.get(tokens_tuple)
17"""
18
19import hashlib
20from collections import OrderedDict
21from typing import Optional, Any, Tuple, List
22
23
24class PrefixCache:
25 """LRU prefix cache for KV block reuse.
26
27 The cache stores snapshots of KV cache data keyed by the first N tokens
28 of a prompt. When a new request has a matching prefix, the cached state
29 can be restored and only the remaining (non-matching) tokens need to be
30 processed.
31
32 Attributes:
33 max_entries: Maximum number of prefixes to cache (LRU eviction).
34 prefix_len: Number of leading tokens used to compute the hash key.
35 """
36
37 def __init__(self, max_entries: int = 64, prefix_len: int = 8):
38 self.max_entries = max_entries
39 self.prefix_len = prefix_len
40 # _cache: hash_key -> (full_tokens_tuple, kv_snapshot)
41 # OrderedDict gives LRU ordering (front = LRU, back = MRU).
42 self._cache: "OrderedDict[str, Tuple[Tuple[int, ...], Any]]" = OrderedDict()
43
44 # ── Public API ──────────────────────────────────────────────────────
45
46 def put(self, tokens_tuple: Tuple[int, ...], kv_snapshot: Any) -> None:
47 """Store a KV cache snapshot keyed by the prefix of *tokens_tuple*.
48
49 The first ``prefix_len`` tokens are hashed to create the cache key.
50 If the cache is full, the least recently used entry is evicted first.
51 If an entry with the same prefix already exists, it is updated and
52 promoted to MRU.
53 """
54 if not tokens_tuple:
55 return
56 prefix = tokens_tuple[: self.prefix_len]
57 key = self._hash(prefix)
58
59 if key in self._cache:
60 # Update existing entry — promote to MRU
61 self._cache.move_to_end(key)
62 self._cache[key] = (tokens_tuple, kv_snapshot)
63 return
64
65 # Evict LRU if needed, then insert
66 self._evict_if_needed()
67 self._cache[key] = (tokens_tuple, kv_snapshot)
68
69 def get(self, tokens_tuple: Tuple[int, ...]) -> Optional[Any]:
70 """Return the cached KV snapshot if the prefix matches.
71
72 Returns ``None`` on cache miss. On hit the entry is promoted to
73 MRU (most recently used) position.
74
75 Matching rules:
76 - If the query has ``prefix_len`` or more tokens, the first
77 ``prefix_len`` tokens must exactly match a cached entry (O(1)
78 hash lookup).
79 - If the query has fewer than ``prefix_len`` tokens (partial
80 prefix match), all available tokens must match the start of a
81 cached prefix (linear scan over all entries).
82 """
83 if not tokens_tuple:
84 return None
85
86 n_query = min(self.prefix_len, len(tokens_tuple))
87 query_prefix = tokens_tuple[:n_query]
88
89 if n_query == self.prefix_len:
90 # Full-length prefix — O(1) hash lookup
91 key = self._hash(query_prefix)
92 if key in self._cache:
93 stored_tokens = self._cache[key][0]
94 if stored_tokens[: self.prefix_len] == query_prefix:
95 self._cache.move_to_end(key)
96 return self._cache[key][1]
97 # Hash collision (astronomically unlikely with SHA-256) —
98 # fall through to linear scan below
99 return None
100
101 # Partial prefix match (query shorter than prefix_len) — linear scan
102 for key, (cached_tokens, snapshot) in list(self._cache.items()):
103 if cached_tokens[:n_query] == query_prefix:
104 self._cache.move_to_end(key)
105 return snapshot
106
107 return None
108
109 def evict(self) -> int:
110 """Evict the least recently used entry.
111
112 Returns the number of entries evicted (0 or 1).
113 """
114 if not self._cache:
115 return 0
116 self._cache.popitem(last=False) # LRU is at front
117 return 1
118
119 def invalidate(self, tokens_tuple: Tuple[int, ...]) -> bool:
120 """Remove the cache entry for a specific prefix.
121
122 Returns True if an entry was removed, False otherwise.
123 """
124 if not tokens_tuple:
125 return False
126 prefix = tokens_tuple[: self.prefix_len]
127 key = self._hash(prefix)
128 if key in self._cache:
129 stored_tokens, _ = self._cache[key]
130 if stored_tokens[: self.prefix_len] == prefix:
131 del self._cache[key]
132 return True
133 return False
134
135 def clear(self) -> None:
136 """Remove all entries from the cache."""
137 self._cache.clear()
138
139 @property
140 def size(self) -> int:
141 """Number of entries currently cached."""
142 return len(self._cache)
143
144 def keys(self) -> List[Tuple[int, ...]]:
145 """Return the stored token prefixes (for inspection/debug)."""
146 return list(t for t, _ in self._cache.values())
147
148 # ── Internal helpers ────────────────────────────────────────────────
149
150 @staticmethod
151 def _hash(prefix: Tuple[int, ...]) -> str:
152 """Deterministic SHA-256 hash of a token prefix tuple."""
153 raw = b",".join(t.to_bytes(4, "little", signed=True) for t in prefix)
154 return hashlib.sha256(raw).hexdigest()
155
156 def _evict_if_needed(self) -> None:
157 """Evict one LRU entry if at capacity."""
158 if len(self._cache) >= self.max_entries:
159 self._cache.popitem(last=False)
160
161
162# ── Engine-specific helpers ──────────────────────────────────────────
163# These functions create / restore KV snapshots for the concrete KV
164# cache layouts used by TurboEngineV77 (dense) and TurboEngineV7MoE.
165
166def snapshot_dense(engine) -> dict:
167 """Create a KV snapshot from a TurboEngineV77 (dense) instance.
168
169 Returns a dict containing copies of the KV caches and position info.
170 """
171 max_pos = engine.kvk.shape[1]
172 snapshot = {
173 "kvk": engine.kvk[:, :max_pos, :].copy(),
174 "kvv": engine.kvv[:, :max_pos, :].copy(),
175 "kvl": engine.kvl.copy(),
176 "pos": int(engine.pos),
177 }
178 return snapshot
179
180
181def restore_dense(engine, snapshot: dict) -> None:
182 """Restore KV cache state on a TurboEngineV77 from a snapshot."""
183 sl = int(snapshot["kvl"].max()) if snapshot["kvl"].any() else 0
184 engine.kvk[:, :, :] = 0
185 engine.kvv[:, :, :] = 0
186 engine.kvk[:, :sl, :] = snapshot["kvk"][:, :sl, :]
187 engine.kvv[:, :sl, :] = snapshot["kvv"][:, :sl, :]
188 engine.kvl[:] = snapshot["kvl"]
189 engine.pos = snapshot["pos"]
190
191
192def snapshot_moe(engine) -> dict:
193 """Create a KV snapshot from a TurboEngineV7MoE instance."""
194 max_pos = engine.kv_k.shape[1]
195 return {
196 "kv_k": engine.kv_k[:, :max_pos, :].copy(),
197 "kv_v": engine.kv_v[:, :max_pos, :].copy(),
198 "kv_len": engine.kv_len.copy(),
199 "pos": int(engine.pos),
200 }
201
202
203def restore_moe(engine, snapshot: dict) -> None:
204 """Restore KV cache state on a TurboEngineV7MoE from a snapshot."""
205 sl = int(snapshot["kv_len"].max()) if snapshot["kv_len"].any() else 0
206 engine.kv_k[:, :, :] = 0
207 engine.kv_v[:, :, :] = 0
208 engine.kv_k[:, :sl, :] = snapshot["kv_k"][:, :sl, :]
209 engine.kv_v[:, :sl, :] = snapshot["kv_v"][:, :sl, :]
210 engine.kv_len[:] = snapshot["kv_len"]
211 engine.pos = snapshot["pos"]
212
213
214if __name__ == "__main__":
215 # Quick smoke test
216 cache = PrefixCache(max_entries=4, prefix_len=4)
217 cache.put((1, 2, 3, 4, 5, 6), "snapshot_A")
218 cache.put((1, 2, 3, 7, 8, 9), "snapshot_B")
219 assert cache.get((1, 2, 3, 4, 10, 11)) == "snapshot_A"
220 assert cache.get((1, 2, 3, 7, 42, 99)) == "snapshot_B"
221 assert cache.get((9, 9, 9, 9)) is None
222 print("PrefixCache smoke test PASSED")