Prefix-Sharing KV Cache for a Greedy Decoding Server
System DesignModel answerLast updated
Add exact, prefix and shared-prefix KV reuse with a token-budgeted LRU to a toy LLM server, cutting prefill cost while every greedy output stays unchanged.
Scenario
You maintain a small text-generation service. Every request re-runs the model over its whole prompt (the prefill), even though many requests begin with the same long system prompt. Your job is to build a cache of attention state so repeated prompt work is skipped, without changing a single generated token.
Provided code
class KVState:
"""Attention state for one sequence. A token list stands in for per-layer K/V tensors."""
def __init__(self, tokens=()):
self.tokens = list(tokens)
@property
def length(self):
return len(self.tokens)
def truncate(self, n):
"""Return a NEW KVState holding the first n positions; self is untouched."""
return KVState(self.tokens[:n])
def clone(self):
return KVState(self.tokens)
class Model:
def __init__(self):
self.prefill_tokens = 0 # total prompt tokens processed; tests read this
def prefill(self, tokens, past=None):
"""Process `tokens`, continuing from `past` if provided.
Requires len(tokens) >= 1. Returns (logits for the last token, new KVState).
`past` is not modified."""
def decode(self, token, kv):
"""One generation step. Appends `token` to `kv` IN PLACE; returns (logits, kv)."""
def argmax(xs):
return max(range(len(xs)), key=xs.__getitem__)
class Server:
def __init__(self, model):
self.model = model
def generate(self, prompt, max_new_tokens):
logits, kv = self.model.prefill(prompt)
out = []
for _ in range(max_new_tokens):
tok = argmax(logits)
out.append(tok)
logits, kv = self.model.decode(tok, kv)
return out
Tasks (each builds on the previous)
- Exact repeats. If a prompt has been served before, avoid prefilling it again.
- Prefix reuse. If the new prompt begins with a previously served prompt, reuse that state and prefill only the leftover tokens via
prefill(rest, past=...). - Token budget. The cache may hold at most
budget_tokenspositions in total (sum ofkv.lengthacross entries). Evict least-recently-used entries to stay within it. A prompt longer than the budget is not cached at all. - Stats and isolation. Expose
stats = {"hits": ..., "misses": ..., "tokens_saved": ...}. Serving the same prompt twice must give identical output, so decoding one request must never alter anything stored in the cache. - Shared prefixes. Prompts like
SYS + question_aandSYS + question_bshare only a partial prefix. Reuse the longest common prefix with any cached prompt, and make lookupO(len(prompt))rather than a scan over all entries. Also addgenerate_batch(prompts, max_new_tokens)that returns outputs in input order.
Constraints
- Greedy decoding; output must match the original
Servertoken for token. 1 <= len(prompt) <= 4096, up to10^4requests,1 <= budget_tokens <= 10^6.- Tests compare
model.prefill_tokensto a per-part ceiling.
What to deliver
Describe your design, explain the pitfalls hiding in the provided API, and give working code for all five parts plus complexity.
Hints
Hint 1
Read the docstrings closely: what does prefill need as input, and what does it give back that a cached KV state alone does not?
Hint 2
decode modifies its kv argument in place. Think about what happens to a cache entry if the very object you stored is later decoded into, and where copies need to be made.
Hint 3
For part 5, a trie over tokens lets you walk the new prompt once. At depth n, any cached prompt passing through that node has the first n positions you need, so keep a set of owning entry ids per node and prune nodes when an entry is evicted.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Key observations
This is mostly careful API reading plus a layered data-structure design. Three facts from the provided code drive everything:
prefill(tokens, past=kv)continues from saved state. That is the entire optimization.prefillneeds at least one token, and a storedKVStateholds no logits. If you reuse the whole prompt you have nothing to pick the first output token from.decodemutates itskvin place, so a cached object that is also being decoded into gets silently polluted with generated tokens.
Pitfall 1: missing logits
Two valid fixes:
- Cap reuse at
len(prompt) - 1. Prefill then always processes at least the final token and returns fresh logits. It costs one extra token per hit but keeps one kind of cache entry. This is what I use. - Store
(kv, last_logits)for exact matches and skip prefill entirely. It saves one more token but adds a second entry type and extra memory per entry.
Pitfall 2: aliasing
Store a clone() on insert and return a truncate(n) copy on lookup (truncate already builds a new object). The request can then decode freely. Do this from part 1, not only when part 4 reveals it.
Design by part
- Part 1: dict from
tuple(prompt)to state. - Part 2: among cached prompts that are prefixes of the new one, take the longest and prefill only the remainder.
- Part 3: an
OrderedDictgives LRU:move_to_endon use,popitem(last=False)to evict. Trackusedin tokens, not entries, and loop evicting until the new entry fits. - Part 4: counters for hits, misses and tokens saved, plus the copy discipline above.
- Part 5: a token trie. Each node keeps the set of entry ids whose prompt passes through it. Walk the new prompt down the trie; at depth
n, any id in that node's set has the firstnpositions identical to ours, sotruncate(n)from it works. This covers divergent endings, which the prefix scan cannot. Cost is one pass over the prompt.
Evicting an entry removes its id from every node on its path, then deletes nodes whose set became empty (walking back from the leaf). Because a node's owners are a subset of its parent's, an empty node implies all its descendants are empty too, so pruning stops at the first non-empty node.
Reference implementation
from collections import OrderedDict
class _Node:
__slots__ = ("kids", "owners")
def __init__(self):
self.kids = {}
self.owners = set()
class PrefixStore:
def __init__(self, budget_tokens):
self.budget = budget_tokens
self.used = 0
self.root = _Node()
self.entries = OrderedDict() # eid -> (key tuple, KVState), least recent first
self.by_key = {} # key tuple -> eid
self.counter = 0
def longest_shared(self, prompt, cap):
node, depth = self.root, 0
while depth < cap:
nxt = node.kids.get(prompt[depth])
if nxt is None:
break
node, depth = nxt, depth + 1
if depth == 0:
return 0, None
eid = next(iter(node.owners)) # pruning guarantees non-empty
self.entries.move_to_end(eid)
return depth, self.entries[eid][1].truncate(depth) # copy
def put(self, prompt, kv):
key = tuple(prompt)
if len(key) > self.budget:
return
if key in self.by_key: # already stored: just refresh recency
self.entries.move_to_end(self.by_key[key])
return
while self.used + len(key) > self.budget:
self._drop_oldest()
eid = self.counter
self.counter += 1
node = self.root
for t in key:
node = node.kids.setdefault(t, _Node())
node.owners.add(eid)
self.entries[eid] = (key, kv.clone()) # detach from the live request
self.by_key[key] = eid
self.used += len(key)
def _drop_oldest(self):
eid, (key, _) = self.entries.popitem(last=False)
del self.by_key[key]
self.used -= len(key)
trail, node = [], self.root
for t in key:
child = node.kids[t]
child.owners.discard(eid)
trail.append((node, t))
node = child
for parent, t in reversed(trail):
if parent.kids[t].owners:
break
del parent.kids[t]
class CachedServer(Server):
def __init__(self, model, budget_tokens=4096):
super().__init__(model)
self.store = PrefixStore(budget_tokens)
self.stats = {"hits": 0, "misses": 0, "tokens_saved": 0}
def generate(self, prompt, max_new_tokens):
n, past = self.store.longest_shared(prompt, len(prompt) - 1)
self.stats["hits" if n else "misses"] += 1
self.stats["tokens_saved"] += n
logits, kv = self.model.prefill(prompt[n:], past=past)
self.store.put(prompt, kv) # clones before decode mutates kv
out = []
for _ in range(max_new_tokens):
tok = argmax(logits)
out.append(tok)
logits, kv = self.model.decode(tok, kv)
return out
def generate_batch(self, prompts, max_new_tokens):
results = [None] * len(prompts)
for i in sorted(range(len(prompts)), key=lambda j: -len(prompts[j])):
results[i] = self.generate(prompts[i], max_new_tokens)
return results
Serving longer prompts first in a batch is only a heuristic: shorter prompts that share their start then hit the cache. Correctness does not depend on the order, and results are written back by original index.
Complexity
- Lookup:
O(L)trie steps plusO(n)to copy the reused positions. A production system would share fixed-size blocks with reference counts instead of copying. - Insert and evict:
O(L)each. - Trie size: at most
budgetnodes, since every cached token contributes at most one node.
Trade-offs worth stating
- Copy versus share: copying is simple and safe; block sharing with copy-on-write saves memory and bandwidth.
- Eviction granularity: whole prompts are evicted here. Evicting from the tail of the least-recently-used branch would keep hot shared prefixes alive longer.
- Redundant entries: a prompt that is a strict prefix of a cached one adds no new information but still costs budget; you could skip it or fold it in.
Verification
Run the original Server as an oracle on a mix of repeats, strict prefixes, shared-prefix/different-suffix pairs and random prompts, at several budgets including tiny ones, and compare outputs token for token. Also assert model.prefill_tokens is lower and that used <= budget after every request.
Common mistakes
- Reusing the entire prompt and then calling
prefillwith an empty list or decoding from stale logits. - Storing the live
kv, so a repeat request returns different tokens. - Measuring the budget in entries rather than tokens.
- Not pruning trie nodes on eviction, causing lookups to hit dead ids (
KeyError) or the trie to grow without bound. - Re-inserting the same prompt on every hit and filling the budget with duplicates.