Example

Make a prefix cache miss on purpose

Look up the same token prefix under two model scopes, then change one token, and see why a prefix cache must key on history.

A prefix cache is only safe if its key identifies everything that determines the cached value. Two requests with the same token ids but different model weights must not share a KV entry. Two requests with the same model but a different token prefix must not share one either. The cache must include the scope and the exact history, not just a prompt id.

This example inserts one prefix under modelA, then performs three lookups: the same prefix under modelA (hit), the same prefix under modelB (miss), and a prefix that differs in the last token (miss). The output also reports the cache size and a deliberately simple hit-rate calculation. The latency_proxy_ms field is a fixed 0.1 versus 1.0, not a measurement; it exists to make the hit/miss distinction visible, not to claim a speedup.

Run it

From the canonical repository at commit f958967d70992d7b09d9c75000bd8c543f1644d4:

python examples/ch16/prefix_cache.py --json

Python 3.11 or later, standard library only. No model, network, GPU or credentials. It finishes immediately.

Implementation

The store key is (scope, tuple(tokens)). Lookup moves a hit to the end of an OrderedDict, and insertion evicts the least recently used entry at capacity. The demo uses capacity four, so no eviction occurs in these three lookups.

class PrefixCache:
    def __init__(self, capacity: int = 16) -> None:
        if capacity < 1:
            raise ValueError("capacity must be positive")
        self.capacity = capacity
        self.store: OrderedDict[Tuple[str, Tuple[int, ...]], CacheEntry] = OrderedDict()

    def _scoped_key(self, scope: str, tokens: List[int]) -> Tuple[str, Tuple[int, ...]]:
        return (scope, tuple(tokens))

    def lookup(self, scope: str, tokens: List[int]) -> LookupResult:
        key = self._scoped_key(scope, tokens)
        if key in self.store:
            entry = self.store[key]
            entry.hits += 1
            self.store.move_to_end(key)
            return LookupResult(hit=True, key=tuple(tokens), scope=scope, value=entry.value, latency_proxy_ms=0.1, metadata={"hits": entry.hits})
        return LookupResult(hit=False, key=tuple(tokens), scope=scope, value=None, latency_proxy_ms=1.0, metadata={})

    def insert(self, scope: str, tokens: List[int], value: str) -> None:
        key = self._scoped_key(scope, tokens)
        if key in self.store:
            self.store[key].value = value
            self.store.move_to_end(key)
            return
        if len(self.store) >= self.capacity:
            self.store.popitem(last=False)
        self.store[key] = CacheEntry(key=tuple(tokens), scope=scope, value=value)

Expected outcome

Observed with the command above (exit 0):

{
  "hit": {
    "hit": true,
    "key": [
      1,
      2,
      3,
      4
    ],
    "scope": "modelA",
    "value": "cached-prefix-A",
    "latency_proxy_ms": 0.1,
    "metadata": {
      "hits": 1
    }
  },
  "miss": {
    "hit": false,
    "key": [
      1,
      2,
      3,
      4
    ],
    "scope": "modelB",
    "value": null,
    "latency_proxy_ms": 1.0,
    "metadata": {}
  },
  "partial": {
    "hit": false,
    "key": [
      1,
      2,
      3,
      5
    ],
    "scope": "modelA",
    "value": null,
    "latency_proxy_ms": 1.0,
    "metadata": {}
  },
  "size": 1,
  "hit_rate_example": 0.5
}

The same token ids under modelB did not hit. The changed last token under modelA did not hit. The cache still held exactly one entry. The reported hit rate is 1/2 because the helper was called with two lookups and one hit; it does not include the partial lookup. That choice is part of the example, and it is a reminder that a hit-rate numerator and denominator must be defined.

Mechanism and limitations

Documented: the key includes both scope and the full token tuple. The cache rejects a non-positive capacity, updates an existing key in place, evicts the least recently used entry at capacity, and counts hits on the entry. The tests check hit, scope miss, partial-prefix miss, capacity eviction and JSON serialisation.

Observed: the command exited 0 with the hit/miss pattern above. The targeted tests.test_ch16_prefix is part of the canonical suite; no independent test count is claimed here.

Not shown: real KV tensors, block-level prefix sharing, partial-prefix reuse, copy-on-write, model revision invalidation, or provider-side caching. The latency proxy is a constant, not a timing. The cache stores a string value, not attention state, so this is a keying and policy demonstration rather than a memory-saving measurement.

Challenge this result

Insert a second prefix under modelB with the same tokens and look it up. Both entries should coexist, proving that the scope is part of the identity. Then set capacity to one, insert two prefixes, and look up the first: LRU should evict it. Finally, change the model revision while keeping the same scope string and explain why the key is still incomplete unless the revision is included.

Source and verification

Canonical source: examples/ch16/prefix_cache.py at commit f958967d70992d7b09d9c75000bd8c543f1644d4. Tests: tests/test_ch16_prefix.py . Chapter: Prefix Caching . The run above is a fresh local execution on Windows 11 with Python 3.13.15; it uses a simulated cache, not a model.

Understand this example

Copy this prompt into your AI tool. No code runs here.

Apply this example

Copy this prompt into your AI tool. No code runs here.