KatInterview

Prefix-Sharing KV Cache for a Greedy Decoding Server

System DesignModel answer
HardModel answerSystem Designkv-cachellm-inferencetrie

Last 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)

  1. Exact repeats. If a prompt has been served before, avoid prefilling it again.
  2. 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=...).
  3. Token budget. The cache may hold at most budget_tokens positions in total (sum of kv.length across entries). Evict least-recently-used entries to stay within it. A prompt longer than the budget is not cached at all.
  4. 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.
  5. Shared prefixes. Prompts like SYS + question_a and SYS + question_b share only a partial prefix. Reuse the longest common prefix with any cached prompt, and make lookup O(len(prompt)) rather than a scan over all entries. Also add generate_batch(prompts, max_new_tokens) that returns outputs in input order.

Constraints

  • Greedy decoding; output must match the original Server token for token.
  • 1 <= len(prompt) <= 4096, up to 10^4 requests, 1 <= budget_tokens <= 10^6.
  • Tests compare model.prefill_tokens to 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.