Understanding Prefix Caching in Hybrid LLMs
The whole post on one page: one real agent prompt traced through Qwen3.5-0.8B's chat template, token IDs and chained block names, why reuse is exact, what each kind of layer must keep, and the measured retries.
An agent sends its whole conversation again on every tool call: the system prompt, the tool schemas, every earlier tool result and reply, and then the one new message at the end. Prefix caching is what makes that affordable. The server keeps the keys and values it computed for the previous request and runs only the tokens it has not seen yet.
On a model where every layer is full attention, that works at almost any token. I replayed an agent retry in llama.cpp on Qwen3-0.6B: a 20-turn chat, cut back to 5, 10, 15 or 19 turns, then a different tool result. Every time, it computed only the 514 new tokens.
Then I ran the same retries on Qwen3.5-0.8B, where 18 of the 24 layers are Gated DeltaNet layers that keep one fixed-size state instead of every token's keys and values. With llama.cpp's default settings, the retries recomputed between 5 and 5,600 tokens the server had already processed, depending on how far back the last state it had saved was. Through the raw completion endpoint, where llama.cpp saves states only near the end of each prompt, a retry at token 9,000 of a 12,000-token prompt recomputed all 9,064 tokens: 2.46 s, against 52 ms on the dense model. Cold, the hybrid was the faster of the two, 3.46 s against 5.53 s for all 12,000 tokens.
This is not a llama.cpp quirk. A recurrent state cannot be rewound, and a sliding window has already dropped the tokens a resume point needs, so every serving stack has to decide where to save them and how much memory to spend on it. And these layers are spreading: of the 19 open models I compare in this article, 12 need such a saved resume point, including 9 of the 13 first listed in 2026.
More concretely, this article walks through:
- How prefix caching works for full attention, from scratch: why reusing cached keys and values is exact, and why a cache block's identity has to hash every block before it, as in Narwhal, the open inference server from Athrael's GPU inference course.
- How a fleet of engines finds a cached prefix. In a replay of an agent trace over 4 engines, cache-aware routing reused 79.3% of the prompt tokens, against 50.6% for round-robin.
- Why sliding-window and recurrent layers (Gated DeltaNet, KDA, Mamba-2) can only resume where a window or a state was saved, with a from-scratch DeltaNet recurrence resumed from a snapshot, and what vLLM, SGLang and llama.cpp save for them.
- What one resume point costs in 19 open models, from their config.json files, and measurements on an M4 Pro.
If you already know how prefix caching works for full attention, feel free to jump straight to Section 4 for the layers that break it, or to Section 7 for the architecture comparison.

Try the retry yourself: pick how many turns the agent keeps and how often llama.cpp saves a state. Every number in it is a measured run.
1. Why agents live on prefix caching
A person in a chat adds a message every so often. An agent adds one per tool call, and every call carries the whole history again. Prefill is the expensive part of each call, and almost all of it is a repeat.
To put a number on "almost all", I wrote a small agent trace (Section 3 has the details): 96 sessions, each starting from one of 4 app prompts and growing by a tool result and a reply per turn, with one turn in five a retry that drops the last tool result and sends a different one. With enough cache memory, 84.4% of its 6,652,373 prompt tokens never had to be computed again.
On a real fleet the payoff shows up as latency. In Athos Georgiou's evaluation of Narwhal, "Prefix caching lifted Narwhal's SLO-qualified share from 40.30% to 76.18% on chat/document", and median time to first token dropped from 2.290 s to 0.631 s. The model under test was Kimi-K3, a KDA hybrid, served with vLLM's hybrid KV cache manager. So that result was already measured on the kind of model this article is about.
Hosted APIs sell the same mechanism. Anthropic describes prompt caching as "letting the API resume from specific prefixes in your prompts", and OpenAI's guide says it "reuses work when requests share the same prompt prefix".
Two limits apply to every design. First, only a prefix counts. vLLM's docs put it as "APC reuses only the longest run of full blocks at the start of the prompt that is already cached", so a change in one token recomputes everything after it. On the dense Qwen3-0.6B, an edit at token 16 of a 12,000-token prompt recomputed 11,984 tokens in 5.44 s, about what the whole prompt costs cold (5.53 s). Second, prefix caching saves prefill only; it "does not reduce the time of generating new tokens".
So an agent's prompt can change in three ways, and they cost very different amounts:
- Append (the next turn): the old prompt is a prefix of the new one. Every design reuses it. On the hybrid, an append to a 12,000-token prompt computed only the 64 new tokens, in 45 ms.
- Branch (a retry, or a different tool result in place of the last one): the prompt is cut back to an earlier point and continues differently. This is the case the rest of this article is about.
- Early edit (a timestamp in the system prompt, a reordered tool list): everything after the edit is new, and no cache helps. Keep the front of an agent's prompt stable.
2. Full attention, from scratch
Why is reuse allowed at all? In a causal transformer, the keys and values of token i depend only on tokens 0 to i. Whatever comes later cannot change them. So if two prompts share their first n tokens, the keys and values of those n tokens are the same in both, in every layer, and the second prompt can start computing at token n.
Here is that claim as code: a two-layer causal attention stack in numpy, one token at a time, with an optional cache of the keys and values seen so far. (Every script is complete at the end of the post.)
def attend(tokens, cache=None, window=None):
"""Two causal attention layers, one token at a time. Layer 2's keys and values come from layer 1's output, so they
depend on every earlier token, as in a real model. cache = (per-layer K rows, per-layer V rows, next position)."""
if cache is None:
Ks, Vs, start = [[] for _ in LAYERS], [[] for _ in LAYERS], 0
else:
Ks, Vs, start = [list(k) for k in cache[0]], [list(v) for v in cache[1]], cache[2]
out = []
for i, tok in enumerate(tokens):
pos = start + i
h = E[tok]
for layer, (wq, wk, wv) in enumerate(LAYERS):
q, k, v = rope(h @ wq, pos), rope(h @ wk, pos), h @ wv
Ks[layer].append(k)
Vs[layer].append(v)
if window is not None: # a ring buffer: drop what fell out of the window
Ks[layer], Vs[layer] = Ks[layer][-window:], Vs[layer][-window:]
K, V = np.stack(Ks[layer]), np.stack(Vs[layer])
s = K @ q / np.float32(np.sqrt(D))
w = np.exp(s - s.max())
h = h + (w / w.sum()) @ V
out.append(h)
return np.stack(out), (Ks, Vs, start + len(tokens))
The check computes a prompt in one go, then again as a cached 48-token prefix plus the rest. The outputs for the new tokens are bit-identical (np.array_equal, not allclose). As a planted defect, I build the cache from the same prefix with token 3 changed, and the outputs differ, as they should. Every check in this post has such a planted defect, because a check that cannot fail proves nothing.
Blocks, and what to call them
A server does not cache prompts whole. Since PagedAttention, the KV cache lives in fixed-size blocks, and a prefix cache is a map from a block's name to the block. The name matters more than it looks. Narwhal computes it like this (prefix residency):
root = SHA-256(version, model, tokenizer, adapter, cache_salt, block_size)
identity[0] = SHA-256(root, tokens of block 0)
identity[n] = SHA-256(identity[n-1], tokens of block n)
vLLM does the same with hash_function((parent_block_hash, curr_block_token_ids_tuple, extra_keys)), where the extra keys hold the LoRA name, multimodal hashes and a cache_salt, which is "injected into the hash of the first block, ensuring that only requests with the same salt can reuse cached KV blocks". A block's keys and values depend on every token before it, so its name has to as well.

In code, the chain is the prev in one line, and dropping it is the planted defect:
def identities(tokens, block_size=4, chained=True):
"""Narwhal: identity[n] = SHA-256(identity[n-1], tokens of block n). Full blocks only; the last token is excluded,
so at least one token is always computed and produces the first output."""
usable = tokens[:-1]
ids, prev = [], root(block_size=block_size)
for b in range(len(usable) // block_size):
block = json.dumps(usable[b * block_size:(b + 1) * block_size]).encode()
prev = hashlib.sha256((prev if chained else b"") + block).digest()
ids.append(prev)
return ids
The test caches prompt A, then prompt B, whose second block holds the same tokens as A's after a different first block, then serves prompt C, which starts like A. With the chain, C reuses A's 2 blocks and its output is bit-identical to a full run. Without it, B's second block lands on A's name, C still reuses 2 blocks, and the output is wrong.
My first version of this toy had one layer, and the defect passed. Layer 1's keys and values depend only on their own token, so swapping them between contexts changes nothing; the error appears from layer 2 on. A one-layer test of a prefix cache cannot catch this bug.
Two smaller rules come with the blocks. Only full blocks are named, and the last prompt token is never a hit: vLLM caps a hit at the prompt length minus one, because "we must recompute the last token to obtain logits", which "can trigger recomputation of an entire block". Eviction is least recently used, block by block; my BlockCache is an OrderedDict.
3. Finding the cache across a fleet
A cached prefix only helps if the next request lands on the engine that holds it. Narwhal splits a serving framework into "a router and a planner" (Introduction to Narwhal), and the router is where this decision is made:
- Each engine publishes an event when it stores or removes cache blocks.
- A sidecar next to the engine keeps a residency index: the block identities the engine holds.
- For each request, the router counts the prompt tokens each engine already holds, and the scheduler lowers the prefill price on those engines.
The prefill price is "the predicted time until that engine finishes the prefill", and when the engine caches a prefix of the prompt, "the profile predicts the shorter time of a prefill that reuses the prefix" (placement). One detail from the residency page: llama.cpp engines publish no cache events, so the router "prices every prefill on them as cold". SGLang's router does the same job with a radix tree of each worker's cached prefixes, and "Routes requests to the worker with the longest cached prefix of the prompt". Preble is the paper on this kind of scheduling: it "co-optimizes KV state reuse and computation load-balancing".
Is it worth it? I replayed the agent trace from Section 1 over 4 engines, with 16-token blocks, Narwhal's chained identities and an LRU cache per engine, under three policies:
- round-robin;
- least-loaded: the engine that computed the fewest tokens in the last 10 s;
- cache-aware: the lowest price, where the price is the tokens this engine must compute for the request plus the tokens it computed in the last 10 s.
Each engine gets 4 GiB of cache. That holds 37,449 tokens of the dense Qwen3-0.6B (112 KiB per token) or 349,525 of the hybrid Qwen3.5-0.8B (12 KiB per token, before its state snapshots).
| Cache, 4 GiB per engine | round-robin | least-loaded | cache-aware |
|---|---|---|---|
| dense (Qwen3-0.6B) | 50.6% | 50.8% | 79.3% |
| hybrid, snapshot every 1,024 tokens | 61.8% | 62.7% | 82.6% |
| hybrid, snapshot every 8,192 tokens | 48.6% | 51.0% | 77.7% |
| hybrid, snapshot at each prompt's end only | 47.9% | 49.3% | 77.7% |
Share of prompt tokens served from the cache (results/route.csv).
Cache-aware routing cut the dense fleet's work from 3,287,301 computed tokens to 1,374,053. It did not pile the work onto one engine: the busiest engine computed between 25.4% and 26.5% of all tokens under every policy, against 25% for a perfect split. Least-loaded routing was no better than round-robin, because spreading the load also spreads the cache. One caveat: my trace has 4 app prompts of similar size, so the popular prefixes spread evenly; a trace with one dominant prompt would test the balance harder.
The hybrid rows already show the theme of the rest of this article. Per byte, the hybrid holds 9 times more prefix than the dense model, and yet with snapshots only at the end of each prompt it reused less than the dense fleet. Sections 4 and 5 explain why.
4. Sliding window: only the last W tokens
A sliding-window layer attends only to the last W tokens, so it only needs to keep those. Gemma 3 has 5 window layers per full-attention layer, and gpt-oss alternates them 1:1. Raschka's visual guide to attention variants has the history: "Gemma 3 pushed this further to a 5:1 ratio and reduced the window size to 1024."
For a cache, the window changes one thing. To resume at token t, a window layer needs the keys and values of the W tokens before t, not all t of them. A comment in llama.cpp's server says it exactly: "the first evaluated token attends to the positions > pos_eval - n_swa, so a SWA state starting at pos_eval - n_swa + 1 is enough". But an engine that keeps only a ring buffer of the last W tokens holds the window behind the end of the prompt, and nothing else.
The toy shows what follows, with a window of 8 and 40 cached tokens:
- Append at token 40: exact. The ring is what the next token needs, and only the 6 new tokens are computed.
- Branch at token 30, ring only: wrong. The ring holds tokens 32 to 39, and token 30 needs 22 to 29.
- Branch at token 30, with a copy of the ring taken at token 24: exact, with 12 tokens recomputed (24 to 29, plus the 6 new ones).
- Branch at token 30, with a copy taken at token 32: unusable, because the copy lies past the branch point.
So a window needs what a recurrent layer needs (Section 5): saved copies at points a later prompt may branch from. Narwhal's matcher states the window rule in blocks. A window of W needs a run of ceil((W − 1) / block size) trailing blocks, 32 blocks for a 512-token window and 16-token blocks. With all 64 blocks of a prompt in the full-attention group:
- window layers holding the last 32 blocks: all 64 blocks match;
- holding only the last 31: 0 match;
- holding everything except blocks 20 to 35: 20 match.
(I copied cached_prefix_blocks from Narwhal's engines/residency.py at e37b0e3 and ran the same cases through the installed narwhal-inference 0.53.1: same answers.)
The serving stacks avoid the ring buffer. vLLM gives each token range its own block and frees blocks "that are outside the sliding window" into the LRU, where they keep their hashes until reused; a hit "only requires the last sliding_window_size - 1 tokens being cached". SGLang keeps the tree node and its full-attention KV, evicts only the window KV and leaves a "tombstone"; a match is valid only if a full window of live tokens leads up to it. llama.cpp keeps only the recent window by default and saves context checkpoints (Section 5), or keeps every token in the window layers too with --swa-full.
On the M4, Gemma 3 270M (15 window-512 layers + 3 full) recomputed 3,650 of 3,651 shared tokens on a retry that kept 5 of 20 turns with default settings, and 0 with --swa-full. Section 8 has the full grid.
5. Recurrent layers: a state you cannot rewind
Gated DeltaNet, Kimi's KDA and Mamba-2 keep no per-token cache at all. Each such layer folds the whole prefix into one fixed-size state and updates it in place, token by token. Here is the gated delta rule in numpy, with fixed gates for clarity:
def deltanet(tokens, S=None):
"""Gated delta rule, one token at a time: S <- a * S (I - b k k^T) + b v k^T, output S q.
The state S (DV x DK) is the whole memory of the prefix; nothing per token is kept."""
S = np.zeros((DV, DK), np.float32) if S is None else S.copy()
out = []
for tok in tokens:
x = E[tok]
k = x @ PK
k = k / np.linalg.norm(k)
v, q = x @ PV, x @ PQ
a = np.float32(0.95) # decay gate (input-dependent in the real model)
b = np.float32(1.0) # write strength (also input-dependent)
S = a * (S - b * np.outer(S @ k, k)) + b * np.outer(v, k)
out.append(S @ q)
return np.stack(out), S
That fixed state is why hybrids are cheap at long context (the subject of my last post), and it is what makes them awkward to cache. A state cannot be rewound. In my toy, one update step has rank 15 of 16, so it throws information away for good, and there is no way back from the state at token 70 to the state at token 60. Marconi says it for real systems: "in-place state updates for recurrent layers precludes rolling back cache entries for partial sequence overlaps, and instead mandates only exact-match cache hits."
The way out is snapshots: copies of the state at chosen positions. A branch resumes from the newest snapshot at or before the branch point and recomputes from there. In the toy, with 96 tokens cached and a branch at token 70:
- snapshot every 16 tokens: resume at 64, recompute 14 tokens, bit-identical;
- snapshot every 40 tokens: resume at 40, recompute 38 tokens, bit-identical;
- planted defect, a snapshot one block too old used as if it were current: wrong.
def deltanet_branch(base, branch_at, suffix, every, stale=False):
"""Snapshots of S every `every` tokens while caching `base`; serve base[:branch_at] + suffix from the last
snapshot at or before branch_at. stale=True plants a defect: take the snapshot before that one, but still start
recomputing at the later position (one block of the prefix is never applied to the state)."""
snaps = {0: None}
S = None
for start in range(0, len(base), every):
_, S = deltanet(base[start:start + every], S)
snaps[min(start + every, len(base))] = S
usable = max(p for p in snaps if p <= branch_at)
state = snaps[usable]
if stale:
state = snaps[max(p for p in snaps if p < usable)]
prompt = base[:branch_at] + suffix
full, _ = deltanet(prompt)
tail, _ = deltanet(prompt[usable:], state)
return np.allclose(full[usable:], tail, rtol=0, atol=0), len(prompt) - usable
A hybrid has both kinds of layers, so a cached prefix is usable only up to a point where all of them can resume: any block for the attention layers, a snapshot for the recurrent ones. Narwhal's matcher takes exactly that intersection. With snapshots at every 16th block, a 64-block prompt matches all 64; with no snapshot, it matches 0, however many attention blocks are cached.
Where the serving stacks save states
The three stacks agree on the rule and differ on where they save. I read each in its source on December 5 (vLLM a6e87997, SGLang 4d2b0aea, llama.cpp b12365):
| vLLM | SGLang | llama.cpp | |
|---|---|---|---|
| where a hit may end | on the Mamba block grid: "a prefix-cache hit can resume only at a block boundary" | at a tree node that holds a state | at a saved context checkpoint |
| saved by default | "proven reuse points (the replay boundary and any cross-request shared-prefix junction, Marconi-style APC)", plus the latest decode state | level 2: "branching points and request ends only" | user-message boundaries at least --checkpoint-min-step (8,192) tokens apart, plus two near the end of each prompt; at most 32 per slot, oldest dropped first |
| denser option | a state at every block boundary; hybrid blocks are large ("a 1024-token hybrid-model block") | level 3: "every prefill chunk and decode tracking boundary" | a smaller --checkpoint-min-step, down to 0 |
| no usable state | the hit stops at the last block with a state | it "resumes from the nearest usable earlier checkpoint, even if more KV is cached" | "forcing full prompt re-processing" |
Notice what the defaults are built for. A next turn appends to the previous prompt, and the end-of-prompt state is exactly where it resumes. A retry cuts the prompt back, so the end-of-prompt state lies past the branch point and is useless. The junction states in vLLM and SGLang appear once two requests have diverged at a point, so the first retry at a new point pays for the recompute, and later prompts that diverge there can reuse the state it left.
What a snapshot costs
Snapshots are not free. For Qwen3.5-0.8B, one snapshot of its 18 DeltaNet layers is 18 MiB, as much memory as 1,536 tokens of its attention cache. A snapshot every 1,024 tokens therefore costs 1.5 times the cache it sits on. Back to the routing replay, now sweeping the cache memory per engine:

With 1 GiB per engine, the dense fleet reused 24.3% of the prompt tokens and the hybrid 72.1% to 77.1%: 9 times more prefix per byte wins. In that range, frequent snapshots hurt, because they eat the memory the prefixes need (72.1% with a snapshot every 1,024 tokens, 77.1% with end-of-prompt snapshots only). From 2 GiB, frequent snapshots win (81.0% against 77.7%). From 8 GiB, the dense fleet passes every hybrid, 84.3% against 82.6%, because it can resume at any block.
Where to put snapshots, and which to keep, is now its own research topic. I have read only the abstracts of these:
- Marconi (MLSys 2025) decides which states to admit and evict, and reports "up to 34.4× higher token hit rates" than earlier prefix caches.
- Sparse Prefix Caching treats placement "as checkpoint placement under a distribution over overlap depths, yielding an exact O(NM) dynamic program".
- HiState keeps "historical checkpoints on SSD while prioritizing fast memory for KV entries", with "up to 5.73x and 5.44x speedups in p99 TTFT over vLLM-Marconi and SGLang-HiCache".
- FrontierReplay "logs a short window of recurrent-layer inputs" and replays them to build exact states, without cutting the prefill.
- Tail-Replay drops recurrent checkpoints entirely: "On a cache hit, it reconstructs the linear-attention states by replaying a short, recent suffix of the matched prefix." That state is an approximation; the authors report that "With only a 5--10% replay budget, it retains 92.8--99.9% of full-prefill quality".
- HybridCache (NeurIPS 2026) "selectively caches head states with significant changes" and quantizes the states.
6. MLA, compressed and sparse attention
Three other designs of the past two years, briefly, because the cache rule follows from what each keeps per token:
- MLA (DeepSeek V3, Mistral Large 4, GLM-5.3, LongCat-2.5) keeps one compressed latent per token instead of keys and values; in vLLM's words, "MLA stores a single latent vector per state; there is no separate V." That is still a per-token cache, so any block can be a resume point, and vLLM manages MLA layers with its full-attention manager.
- Sparse reads (MiniMax M3, GLM-5.3, LongCat-2.5) keep every token and add an indexer key per token. In vLLM's code, the DSA indexer's key cache is declared as a full-attention-managed layer, so a hit reuses both. One exception sits in the code: ring-buffer indexer tails, such as GLM-5.3-Flash's, "are scratch and excluded."
- Compressed attention (DeepSeek V4) keeps compressed entries for older tokens and a short window of full ones, which puts it with the sliding-window models: one resume point is 5.4 MiB for V4 Flash and 7.6 MiB for V4 Pro. vLLM's source even has a group that opts out: "DeepSeek-V4.1: replay the window instead of prefix caching it."
7. The architecture comparison
Now the 19 open models from Understanding LLM Inference, through the same per-layer arithmetic from their config.json files. For each model: what one cached token costs, whether a cached prefix can resume at any block or needs a saved resume point, and what one resume point costs, in MiB and in tokens of that model's own cache.
| Model | First listed | Layer design | Resume at | KV per token | One resume point | = tokens of its cache | Snapshots every 1,024 tokens |
|---|---|---|---|---|---|---|---|
| Llama 3.1 70B | 2024-07 | GQA | any block | 320.0 KiB | none | ||
| DeepSeek V3 | 2024-12 | MLA | any block | 68.6 KiB | none | ||
| Gemma 3 27B | 2025-03 | window 5:1 + GQA | window tail | 80.0 KiB | 416.0 MiB | 5,325 | 5.20x the cache |
| Qwen3-4B | 2025-04 | GQA | any block | 144.0 KiB | none | ||
| gpt-oss-120b | 2025-08 | window 1:1 + GQA | window tail | 36.0 KiB | 4.5 MiB | 128 | 0.12x the cache |
| Qwen3-Next 80B-A3B | 2025-09 | DeltaNet 3:1 + GQA | state snapshot | 24.0 KiB | 72.0 MiB | 3,072 | 3.00x the cache |
| DeepSeek V4 Flash | 2026-07 | compressed + sparse | window tail | 6.7 KiB | 5.4 MiB | 819 | 0.80x the cache |
| DeepSeek V4 Pro | 2026-08 | compressed + sparse | window tail | 9.6 KiB | 7.6 MiB | 812 | 0.79x the cache |
| Ling 3.1 Flash | 2026-10 | KDA 7:1 + MLA | state snapshot | 10.1 KiB | 252.0 MiB | 25,486 | 24.89x the cache |
| MiniMax M3 | 2026-10 | GQA + sparse reads | any block | 134.2 KiB | none | ||
| Mistral Large 4 | 2026-10 | MLA + sparse + shared KV | any block | 81.9 KiB | none | ||
| Muse Spark Open 816B | 2026-10 | window + GQA | window tail | 64.0 KiB | 368.0 MiB | 5,888 | 5.75x the cache |
| Nemotron 3.5 Lightning 30B | 2026-10 | Mamba-2 + GQA | state snapshot | 6.0 KiB | 46.0 MiB | 7,851 | 7.67x the cache |
| GLM-5.3 | 2026-11 | MLA + sparse reads | any block | 93.0 KiB | none | ||
| Kimi K3.1 Pro | 2026-11 | KDA + MLA sparse | state snapshot | 33.0 KiB | 414.0 MiB | 12,847 | 12.55x the cache |
| LongCat-2.5 | 2026-11 | MLA + sparse reads | any block | 52.2 KiB | none | ||
| Qwen3.8-27B | 2026-11 | DeltaNet 3:1 + GQA | state snapshot | 64.0 KiB | 144.0 MiB | 2,304 | 2.25x the cache |
| Amazon Ergo | 2026-12 | window 3:1 + GQA | window tail | 64.0 KiB | 96.0 MiB | 1,536 | 1.50x the cache |
| Qwen4 35B-A3B | 2026-12 | DeltaNet 3:1 + sparse | state snapshot | 20.6 KiB | 60.0 MiB | 2,979 | 2.91x the cache |
Three things stand out.
First, the split follows the layer map, not the model's size or age alone. Seven models resume at any block: the GQA and MLA models, with or without sparse reads. Six need a state snapshot (DeltaNet, KDA, Mamba-2), and six need a window tail (sliding-window and compressed attention). Before 2026, 3 of the 6 models in my list need a resume point; among the 13 first listed in 2026, 9 do.
Second, a resume point is cheap next to a long prompt but expensive next to a short one. Kimi K3.1 Pro's state snapshot is 414 MiB, as much as 12,847 tokens of its own cache, and Ling 3.1 Flash's 252 MiB equals 25,486 of its tokens. For those two, a snapshot every 1,024 tokens would cost 12.55 and 24.89 times the cache it protects. The Qwen DeltaNet hybrids sit at 2.25 to 3.0 times, which is why "save often" is a real option for them and not for the KDA models.
Third, windows range from trivial to huge. gpt-oss-120b's 128-token window makes a resume point 4.5 MiB, the size of 128 tokens of its own cache; Gemma 3 27B's window tails come to 416 MiB, the largest in the table.
The units match the inference post: KV in bf16, recurrent states in fp32, indexer keys counted, conv states and draft heads not counted. An FP8 cache halves the KV columns.
8. Measured on the M4
Everything so far is a toy or a simulation. To see a real engine, I ran llama.cpp (release b12365, Metal) on my MacBook (M4 Pro, 24 GB) with three small models from the same families as the big ones, all Q4_K_M GGUF files checked against their published SHA-256:
- Qwen3-0.6B, dense: 28 full-attention layers, 112 KiB of KV per token;
- Qwen3.5-0.8B, hybrid: 18 Gated DeltaNet + 6 full-attention layers, 12 KiB per token plus an 18 MiB state;
- Gemma 3 270M, sliding window: 15 window-512 layers + 3 full, 3 KiB per token plus 7.5 MiB of windows.
One slot (-np 1) and no host-memory prompt cache (--cache-ram 0), so the only cache is the slot's own. Each measurement primes the slot with the full prompt, sends the variant, and reads timings.prompt_n, the number of tokens the server actually computed. I went in two ways:
- the chat API (
/v1/chat/completions): a system prompt and 20 turns, each a 320-word tool result (pieces of Narwhal's docs) and a short reply, about 11.7K tokens in all. The retry keeps the first 5, 10, 15 or 19 turns and sends a different tool result; - the raw completion API with token arrays: a 6,000- or 12,000-token prompt, then an append, a branch at 25, 50, 75 or 90%, or an edit at token 16.

What the grid says:
- Dense: every retry computed only its 514 new tokens, in 233 to 384 ms. There is nothing to configure.
- Hybrid, default settings: 5 to 5,600 shared tokens recomputed. With the default spacing of 8,192 tokens, the usable checkpoints in this chat sat at token 761 and token 9,026. A retry that kept 15 turns (9,031 shared tokens) found one 5 tokens back; a retry that kept 10 turns (6,361 shared) went back to token 761 and recomputed 5,600.
- Hybrid, a checkpoint at every user turn (
--checkpoint-min-step 0): 5 tokens recomputed on every retry, in 152 to 196 ms, faster than the dense model on the same retries. The 20 turns stay under the default cap of 32 checkpoints per slot; a longer session needs a larger--ctx-checkpoints, because the oldest are dropped first. - Hybrid, no checkpoints: the whole shared prefix every time, 11,174 tokens in 3.36 s for the retry that kept 19 turns.
- Gemma: the same pattern, from 3,650 tokens recomputed by default to 6 with a checkpoint at every user turn, and 0 with
--swa-full.
The raw API gives the opening's numbers. A token-array prompt has no user turns, so the only checkpoints are the two near its end. A branch at token 9,000 of 12,000 recomputed all 9,064 tokens on the hybrid (2.46 s) and on Gemma (0.56 s), against 64 tokens on the dense model (52 ms) and on Gemma with --swa-full (13 ms). --checkpoint-min-step 1024 changed nothing there. An append was cheap on all three models (64 new tokens), and an edit at token 16 was expensive on all three.
What does a checkpoint cost? llama.cpp saves "the parts of the memory that cannot be rolled back": for the hybrid that is the DeltaNet state, 18 MiB by the layer-map arithmetic, and for Gemma the window layers' KV, 7.5 MiB.
9. What to take from it
- Prefix caching is the main saving for agents. With enough memory, 84.4% of my trace's prompt tokens were never recomputed.
- On full-attention and MLA models, any block is a resume point. Keep the front of the prompt stable and route each request to the engine that holds its prefix: cache-aware routing reused 79.3% of prompt tokens against 50.6% for round-robin in my replay.
- Sliding-window and recurrent layers resume only where a window or a state was saved. Twelve of the 19 open models I compared are in that group, including 9 of the 13 first listed in 2026.
- The serving defaults save states at prompt ends and at junctions they have already seen. That serves the next turn, not the first retry.
- On llama.cpp with a hybrid or sliding-window model, use the chat API and
--checkpoint-min-step 0, with enough--ctx-checkpointsfor your longest session. Retries then recomputed 5 or 6 tokens, instead of up to 5,600 on the hybrid and 6,492 on Gemma. - A resume point costs memory, from 4.5 MiB (gpt-oss-120b) to 416 MiB (Gemma 3 27B) per sequence. With little memory, save few; with plenty, save many, or rebuild states by replay as FrontierReplay and Tail-Replay do.
- Read a model's layer map twice: once for the bytes it keeps per token, and once for where its cache can be resumed.
Method and reproduction
Everything ran on an M4 Pro (24 GB). llama.cpp b12365 (commit ae93877c) with Metal and every layer on the GPU, one slot, --cache-ram 0, a 16,384-token context for the raw API and 24,576 for the chat API. Each measurement ran twice; times are medians, and the token counts were identical in both runs. The models are Q4_K_M GGUF files, SHA-256 checked: Qwen3.5-0.8B (bd258782…, the same file Narwhal pins), Qwen3-0.6B (ac2d9771…) and Gemma 3 270M instruct (b1baabd6…). The prompt text is Narwhal's docs/concepts pages at commit e37b0e3 (Apache-2.0), used as filler.
The from-scratch checks use random weights in fp32 and compare with np.array_equal. The routing replay is one seeded trace; it does not cache the replies' own KV, so the next turn recomputes them for both designs. The 19-model numbers reuse simulate.py from Understanding LLM Inference, whose full source is in that post. The serving-stack behaviour was read in source at vLLM a6e87997, SGLang 4d2b0aea and llama.cpp b12365 on December 5; where a doc and the code disagreed, I followed the code. The one-page infographic is drawn by infographic.py; its prompt, token IDs and block names come from tokens.py, which runs Qwen3.5-0.8B's own chat template and tokenizer through llama-server, and every other number in it is read from the same CSVs as the text.
Every number in this post comes from one of the scripts' CSV files or is quoted from a source listed below.
from_scratch.py: the from-scratch checks: attention reuse, block identities, sliding window, DeltaNet, Narwhal's matching rule (numpy only)
"""Prefix caching from scratch: what a server may reuse, per layer kind, checked bit for bit.
1. Full attention: reusing a cached prefix's keys and values gives bit-identical outputs.
2. Block identities: why a block's identity must chain over every token before it (Narwhal's SHA-256 chain).
3. Sliding window: a ring buffer keeps only the last W tokens, so only an append can reuse it.
4. Gated DeltaNet: a recurrent state cannot be rewound; a branch resumes from the last snapshot at or before it.
5. Narwhal's matching rule (cached_prefix_blocks), on the three layer kinds.
Every check has a planted defect that must make it fail, so a passing check means something.
Run: uv run --no-project --with numpy python3 -I from_scratch.py -> results/checks.csv, results/recompute.csv
"""
import csv
import hashlib
import json
from collections import OrderedDict
from pathlib import Path
import numpy as np
HERE = Path(__file__).parent
rng = np.random.default_rng(0)
VOCAB, D = 512, 64
E = rng.standard_normal((VOCAB, D)).astype(np.float32)
LAYERS = [tuple(rng.standard_normal((D, D)).astype(np.float32) / 8 for _ in range(3)) for _ in range(2)]
def rope(x, pos):
"""Rotary position embedding: rotate each pair of dims by an angle that grows with the position."""
half = D // 2
freq = 10000.0 ** (-np.arange(half, dtype=np.float32) / half)
a = pos * freq
c, s = np.cos(a), np.sin(a)
return np.concatenate([x[:half] * c - x[half:] * s, x[:half] * s + x[half:] * c]).astype(np.float32)
# 1. Full attention ------------------------------------------------------------------------------------------------
def attend(tokens, cache=None, window=None):
"""Two causal attention layers, one token at a time. Layer 2's keys and values come from layer 1's output, so they
depend on every earlier token, as in a real model. cache = (per-layer K rows, per-layer V rows, next position)."""
if cache is None:
Ks, Vs, start = [[] for _ in LAYERS], [[] for _ in LAYERS], 0
else:
Ks, Vs, start = [list(k) for k in cache[0]], [list(v) for v in cache[1]], cache[2]
out = []
for i, tok in enumerate(tokens):
pos = start + i
h = E[tok]
for layer, (wq, wk, wv) in enumerate(LAYERS):
q, k, v = rope(h @ wq, pos), rope(h @ wk, pos), h @ wv
Ks[layer].append(k)
Vs[layer].append(v)
if window is not None: # a ring buffer: drop what fell out of the window
Ks[layer], Vs[layer] = Ks[layer][-window:], Vs[layer][-window:]
K, V = np.stack(Ks[layer]), np.stack(Vs[layer])
s = K @ q / np.float32(np.sqrt(D))
w = np.exp(s - s.max())
h = h + (w / w.sum()) @ V
out.append(h)
return np.stack(out), (Ks, Vs, start + len(tokens))
def reuse_is_exact(prefix_used_for_cache, prompt, split):
"""Compute prompt[split:] on top of a cache built from prefix_used_for_cache; compare with the full run."""
full, _ = attend(prompt)
_, cache = attend(prefix_used_for_cache)
tail, _ = attend(prompt[split:], cache=cache)
return np.array_equal(full[split:], tail)
# 2. Block identities -----------------------------------------------------------------------------------------------
def root(model="toy", tokenizer="toy-v1", adapter="", cache_salt="", block_size=4, version=1):
return hashlib.sha256(json.dumps([version, model, tokenizer, adapter, cache_salt, block_size]).encode()).digest()
def identities(tokens, block_size=4, chained=True):
"""Narwhal: identity[n] = SHA-256(identity[n-1], tokens of block n). Full blocks only; the last token is excluded,
so at least one token is always computed and produces the first output."""
usable = tokens[:-1]
ids, prev = [], root(block_size=block_size)
for b in range(len(usable) // block_size):
block = json.dumps(usable[b * block_size:(b + 1) * block_size]).encode()
prev = hashlib.sha256((prev if chained else b"") + block).digest()
ids.append(prev)
return ids
class BlockCache:
"""A paged prefix cache: block identity -> stored keys and values, least recently used evicted first."""
def __init__(self, capacity):
self.capacity, self.blocks = capacity, OrderedDict()
def store(self, ids, cache, block_size):
Ks, Vs, _ = cache
for n, ident in enumerate(ids):
rows = slice(n * block_size, (n + 1) * block_size)
self.blocks[ident] = ([K[rows] for K in Ks], [V[rows] for V in Vs])
self.blocks.move_to_end(ident)
while len(self.blocks) > self.capacity:
self.blocks.popitem(last=False)
def match(self, ids):
"""Leading blocks found; a lookup stops at the first miss."""
n = 0
while n < len(ids) and ids[n] in self.blocks:
self.blocks.move_to_end(ids[n])
n += 1
return n
def kv(self, ids, n, block_size):
"""The cache for the first n blocks, in the shape attend() takes."""
layers = len(self.blocks[ids[0]][0]) if n else len(LAYERS)
Ks = [[r for i in ids[:n] for r in self.blocks[i][0][layer]] for layer in range(layers)]
Vs = [[r for i in ids[:n] for r in self.blocks[i][1][layer]] for layer in range(layers)]
return Ks, Vs, n * block_size
def block_reuse_is_exact(chained):
"""Cache prompt A, then prompt B. B's second block holds the same tokens as A's, after a different first block.
Then serve C, which starts exactly like A: its two blocks should come from A."""
bs = 4
A = [1, 2, 3, 4, 5, 6, 7, 8, 9]
B = [11, 12, 13, 14, 5, 6, 7, 8, 9]
C = [1, 2, 3, 4, 5, 6, 7, 8, 20, 21]
cache = BlockCache(capacity=16)
for p in (A, B):
_, kv = attend(p)
cache.store(identities(p, bs, chained), kv, bs) # unchained: B's block 1 lands on A's block 1 identity
ids = identities(C, bs, chained)
n = cache.match(ids)
tail, _ = attend(C[n * bs:], cache=cache.kv(ids, n, bs))
full, _ = attend(C)
return n, np.array_equal(full[n * bs:], tail)
# 3. Sliding window -------------------------------------------------------------------------------------------------
def window_branch_is_exact(snapshot_at, branch_at, W=8, N=40, suffix=6):
"""Cache N tokens through a W-token ring buffer, keeping a copy of the ring at `snapshot_at` (None = no copy).
Then serve base[:branch_at] + new suffix, resuming from the copy and recomputing from there."""
base = list(rng.integers(0, VOCAB, N))
new = list(rng.integers(0, VOCAB, suffix))
prompt = base[:branch_at] + new
full, _ = attend(prompt, window=W)
if snapshot_at is None: # only the ring after all N tokens: wrong unless branch_at == N
_, ring = attend(base, window=W)
resume = N
else:
_, ring = attend(base[:snapshot_at], window=W)
resume = snapshot_at
if resume > branch_at:
return False, len(prompt) # the copy is past the branch point: nothing usable
tail, _ = attend(prompt[resume:], cache=ring, window=W)
return np.array_equal(full[resume:], tail), len(prompt) - resume
# 4. Gated DeltaNet -------------------------------------------------------------------------------------------------
DK = DV = 16
PK, PV, PQ = (rng.standard_normal((D, DK)).astype(np.float32) / 8 for _ in range(3))
def deltanet(tokens, S=None):
"""Gated delta rule, one token at a time: S <- a * S (I - b k k^T) + b v k^T, output S q.
The state S (DV x DK) is the whole memory of the prefix; nothing per token is kept."""
S = np.zeros((DV, DK), np.float32) if S is None else S.copy()
out = []
for tok in tokens:
x = E[tok]
k = x @ PK
k = k / np.linalg.norm(k)
v, q = x @ PV, x @ PQ
a = np.float32(0.95) # decay gate (input-dependent in the real model)
b = np.float32(1.0) # write strength (also input-dependent)
S = a * (S - b * np.outer(S @ k, k)) + b * np.outer(v, k)
out.append(S @ q)
return np.stack(out), S
def deltanet_branch(base, branch_at, suffix, every, stale=False):
"""Snapshots of S every `every` tokens while caching `base`; serve base[:branch_at] + suffix from the last
snapshot at or before branch_at. stale=True plants a defect: take the snapshot before that one, but still start
recomputing at the later position (one block of the prefix is never applied to the state)."""
snaps = {0: None}
S = None
for start in range(0, len(base), every):
_, S = deltanet(base[start:start + every], S)
snaps[min(start + every, len(base))] = S
usable = max(p for p in snaps if p <= branch_at)
state = snaps[usable]
if stale:
state = snaps[max(p for p in snaps if p < usable)]
prompt = base[:branch_at] + suffix
full, _ = deltanet(prompt)
tail, _ = deltanet(prompt[usable:], state)
return np.allclose(full[usable:], tail, rtol=0, atol=0), len(prompt) - usable
def rewind_is_possible():
"""Can S_t be recovered from S_(t+1)? Only if a(I - b k k^T) is invertible. With b = 1 and a unit k it is a
projection: it throws away S's component along k for good."""
k = rng.standard_normal(DK).astype(np.float32)
k /= np.linalg.norm(k)
step = np.float32(0.95) * (np.eye(DK, dtype=np.float32) - np.outer(k, k))
return int(np.linalg.matrix_rank(step)), DK
# 5. Narwhal's matching rule (narwhal/engines/residency.py at e37b0e3, Apache-2.0, copied verbatim) -------------------
FULL_KINDS = frozenset({None, "full_attention", "mla_attention", "sink_full_attention"})
WINDOW_KINDS = frozenset({"sliding_window", "sliding_window_mla"})
BOUNDARY_KINDS = frozenset({"mamba"})
def cached_prefix_blocks(groups, identities, block_size):
"""Number of leading blocks of a prefix that every cache group can serve."""
groups = list(groups)
if not groups or any(
kind not in FULL_KINDS | WINDOW_KINDS | BOUNDARY_KINDS
or (kind in WINDOW_KINDS and (not window or not block_size))
for kind, window, _ in groups
):
return 0
full = [blocks for kind, _, blocks in groups if kind in FULL_KINDS]
windows = [
(blocks, -(-(window - 1) // block_size))
for kind, window, blocks in groups
if kind in WINDOW_KINDS and window and block_size
]
boundary = [blocks for kind, _, blocks in groups if kind in BOUNDARY_KINDS]
limit = len(identities)
for blocks in full:
count = 0
while count < limit and identities[count] in blocks:
count += 1
limit = count
if not windows:
for count in range(limit, 0, -1):
if all(identities[count - 1] in blocks for blocks in boundary):
return count
return 0
runs = [0] * len(windows)
best = 0
for count, identity in enumerate(identities[:limit], start=1):
for index, (blocks, _) in enumerate(windows):
runs[index] = runs[index] + 1 if identity in blocks else 0
if all(identity in blocks for blocks in boundary) and all(
run >= min(count, needed) for run, (_, needed) in zip(runs, windows, strict=True)
):
best = count
return best
def narwhal_cases(rule=None):
"""64 blocks of 16 tokens in the prompt; the engine holds all 64 in its full-attention group."""
ids = [f"b{i}".encode() for i in range(64)]
held = set(ids)
cases = {
"full attention only": [("full_attention", None, held)],
"hybrid, state snapshot at every 16th block": [("full_attention", None, held),
("mamba", None, {ids[i] for i in range(15, 64, 16)})],
"hybrid, no snapshot": [("full_attention", None, held), ("mamba", None, set())],
"window 512, last 32 blocks held": [("full_attention", None, held),
("sliding_window", 512, set(ids[32:]))],
"window 512, last 31 blocks held": [("full_attention", None, held),
("sliding_window", 512, set(ids[33:]))],
"window 512, blocks 20-35 dropped": [("full_attention", None, held),
("sliding_window", 512, set(ids[:20]) | set(ids[36:]))],
}
rule = rule or cached_prefix_blocks
return {name: rule(groups, ids, 16) for name, groups in cases.items()}
def check_against_narwhal():
"""Same cases through the installed narwhal-inference; False when it is not installed."""
try:
from narwhal.engines.residency import cached_prefix_blocks as theirs
except ImportError:
return False
assert narwhal_cases() == narwhal_cases(theirs), "the copied rule differs from narwhal's"
return True
def recompute_curves(n=12000, suffix=64):
"""Tokens a branch at t must recompute, per cache kind (the model behind the M4 measurements)."""
rows = []
for t in range(0, n + 1, 250):
for kind, every in (("full attention, any token", 1), ("state snapshot every 1,024", 1024),
("state snapshot every 8,192", 8192), ("last state only", None)):
if every is None:
resume = n if t == n else 0
else:
resume = t // every * every
rows.append({"branch_at": t, "kind": kind, "recomputed": t - resume + suffix})
return rows
def main():
P = list(rng.integers(0, VOCAB, 48))
S = list(rng.integers(0, VOCAB, 8))
edited = P.copy()
edited[3] = (edited[3] + 1) % VOCAB
checks = []
add = lambda check, case, exact, tokens="": checks.append({"check": check, "case": case, "exact": exact, "tokens": tokens})
add("full attention", "reuse a cached 48-token prefix", reuse_is_exact(P, P + S, len(P)))
add("full attention", "planted: cache built with token 3 changed", reuse_is_exact(edited, P + S, len(P)))
print("1. full attention: reuse is exact:", reuse_is_exact(P, P + S, len(P)))
print(" planted (cache built from a prompt with token 3 changed):", reuse_is_exact(edited, P + S, len(P)))
assert reuse_is_exact(P, P + S, len(P)) and not reuse_is_exact(edited, P + S, len(P))
n_ok, ok = block_reuse_is_exact(chained=True)
n_bad, bad = block_reuse_is_exact(chained=False)
print(f"2. chained identities: {n_ok} block(s) matched, exact: {ok}")
print(f" planted (identity hashes the block alone): {n_bad} block(s) matched, exact: {bad}")
assert ok and not bad and n_ok == n_bad == 2
add("block identities", "chained SHA-256 (blocks matched)", ok, n_ok)
add("block identities", "planted: unchained (blocks matched)", bad, n_bad)
for snap, at in ((None, 40), (None, 30), (24, 30), (32, 30)):
ok, rec = window_branch_is_exact(snap, at)
print(f"3. window 8, 40 cached, branch at {at}, copy of the ring at {snap}: exact {ok}, recomputed {rec}")
add("sliding window 8", f"40 cached, branch at {at}, ring copy at {snap}", ok, rec)
assert window_branch_is_exact(None, 40)[0] and window_branch_is_exact(24, 30)[0]
assert not window_branch_is_exact(None, 30)[0] and not window_branch_is_exact(32, 30)[0]
base = list(rng.integers(0, VOCAB, 96))
suf = list(rng.integers(0, VOCAB, 8))
for every in (16, 40):
ok, rec = deltanet_branch(base, 70, suf, every)
print(f"4. DeltaNet, 96 cached, branch at 70, snapshot every {every}: exact {ok}, recomputed {rec}")
add("DeltaNet", f"96 cached, branch at 70, snapshot every {every}", ok, rec)
assert ok
bad, _ = deltanet_branch(base, 70, suf, 16, stale=True)
print(" planted (a stale snapshot, one block too old):", bad)
add("DeltaNet", "planted: stale snapshot", bad)
assert not bad
rank, dim = rewind_is_possible()
print(f" one step of the state update has rank {rank} of {dim}: it cannot be undone")
assert rank < dim
add("DeltaNet", f"rank of one state-update step (of {dim})", False, rank)
for name, count in narwhal_cases().items():
print(f"5. Narwhal rule, {name}: {count} of 64 blocks match")
add("Narwhal cached_prefix_blocks", name, "", count)
got = narwhal_cases()
assert got["full attention only"] == 64 and got["hybrid, state snapshot at every 16th block"] == 64
assert got["hybrid, no snapshot"] == 0 and got["window 512, blocks 20-35 dropped"] == 20
assert got["window 512, last 32 blocks held"] == 64 and got["window 512, last 31 blocks held"] == 0
same = check_against_narwhal()
print(" same answers from the installed narwhal-inference:", same)
add("Narwhal cached_prefix_blocks", "same answers as narwhal-inference 0.53.1", same)
with (HERE / "results" / "checks.csv").open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(checks[0]))
w.writeheader()
w.writerows(checks)
rows = recompute_curves()
out = HERE / "results" / "recompute.csv"
out.parent.mkdir(exist_ok=True)
with out.open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
print("all checks passed; wrote", out.name)
if __name__ == "__main__":
main()
route.py: the routing replay over 4 engines (stdlib only)
"""Cache-aware routing, replayed: an agent-shaped trace over 4 engines, three routing policies, four cache kinds.
The trace: sessions of an agent. Each session starts from one of four app prompts (system prompt + tool schemas), then
appends a tool result or user message and the model's reply every turn. Some turns are retries: the agent drops its
last tool result and sends a different one, so the prompt branches from the start of the previous turn's chunk.
Every engine has the same cache budget in BYTES, and each cache kind pays for what it keeps, using the layer maps
measured in results/layer_maps.csv:
dense every token's KV in every layer (Qwen3-0.6B: 112 KiB per token)
hybrid + snap KV of the 6 attention layers per token, plus one 18 MiB DeltaNet state per snapshot (Qwen3.5-0.8B)
Blocks are 16 tokens and carry Narwhal's chained identities. A dense engine reuses its longest run of leading blocks. A
hybrid engine reuses up to the last block that has a state snapshot (Narwhal's cached_prefix_blocks rule for "mamba"
groups), with snapshots every N tokens and at the end of every prompt it computed. Least recently used goes first.
Policies:
round-robin request i to engine i mod 4
least-loaded the engine that computed the fewest tokens in the last 10 s
cache-aware the engine with the lowest price: tokens it must compute for this request + tokens it computed in
the last 10 s (a queue proxy), as Narwhal's placement prices a warm prefill lower
Simplification: the reply's own KV (made during decode) is not cached by either kind, so the next turn recomputes it.
Run: python3 -I route.py -> results/route.csv (4 GiB per engine), results/route_budget.csv (cache-aware, 1-32 GiB)
"""
import csv
import hashlib
import random
from collections import OrderedDict, deque
from pathlib import Path
HERE = Path(__file__).parent
BLOCK = 16
ENGINES = 4
BUDGET = 4 * 2**30 # bytes of prefix cache per engine (route_budget.csv sweeps it)
KIB = 1024
def layer_maps():
rows = {r["model"]: r for r in csv.DictReader(open(HERE / "results" / "layer_maps.csv"))}
return int(rows["Qwen3-0.6B"]["kv_bytes_per_token"]), int(rows["Qwen3.5-0.8B"]["kv_bytes_per_token"]), \
int(rows["Qwen3.5-0.8B"]["state_bytes_fixed"])
DENSE_KV, HYBRID_KV, STATE = layer_maps()
KINDS = [("dense (Qwen3-0.6B)", DENSE_KV, None), ("hybrid, snapshot every 1,024", HYBRID_KV, 1024),
("hybrid, snapshot every 8,192", HYBRID_KV, 8192), ("hybrid, end of prompt only", HYBRID_KV, 10**9)]
def trace(seed=1, sessions=96, apps=4):
"""(time, session, prompt tokens) per request, sorted by time."""
rnd = random.Random(seed)
tok = lambda n: [rnd.randrange(150_000) for _ in range(n)]
app_prompts = [tok(rnd.randrange(1500, 3500)) for _ in range(apps)]
out = []
for s in range(sessions):
ctx = list(app_prompts[rnd.randrange(apps)])
t = rnd.uniform(0, 900)
last_chunk = 0
for turn in range(rnd.randrange(6, 16)):
if turn and rnd.random() < 0.2: # retry: drop the last chunk, send a different one
ctx = ctx[:len(ctx) - last_chunk]
chunk = tok(rnd.randrange(150, 1200))
ctx = ctx + chunk
last_chunk = len(chunk)
out.append((t, s, list(ctx)))
reply = tok(rnd.randrange(60, 300))
ctx = ctx + reply # the reply becomes part of the next prompt
last_chunk += len(reply)
t += rnd.expovariate(1 / 15)
return sorted(out, key=lambda r: r[0])
def identities(tokens):
"""Narwhal's chain: identity[n] = SHA-256(identity[n-1], tokens of block n); full blocks, last token excluded."""
usable = tokens[:-1]
ids, prev = [], hashlib.sha256(b"root").digest()
for b in range(len(usable) // BLOCK):
prev = hashlib.sha256(prev + str(usable[b * BLOCK:(b + 1) * BLOCK]).encode()).digest()
ids.append(prev)
return ids
class Engine:
def __init__(self, kv_per_token, snap_every, budget=BUDGET):
self.budget = budget
self.kv_block = kv_per_token * BLOCK
self.snap_every = snap_every
self.items = OrderedDict() # ("kv" | "state", identity) -> bytes
self.used = 0
self.recent = deque() # (time, tokens computed)
def reusable_blocks(self, ids):
n = 0
while n < len(ids) and ("kv", ids[n]) in self.items:
n += 1
if self.snap_every is None:
return n
while n and ("state", ids[n - 1]) not in self.items: # back off to the last block with a state snapshot
n -= 1
return n
def load(self, now):
while self.recent and self.recent[0][0] < now - 10:
self.recent.popleft()
return sum(c for _, c in self.recent)
def _put(self, key, nbytes):
if key in self.items:
self.items.move_to_end(key)
return
self.items[key] = nbytes
self.used += nbytes
while self.used > self.budget:
_, freed = self.items.popitem(last=False)
self.used -= freed
def serve(self, now, tokens, ids):
reuse = self.reusable_blocks(ids)
for n in range(reuse): # touch what was reused
self.items.move_to_end(("kv", ids[n]))
if self.snap_every is not None and reuse:
self.items.move_to_end(("state", ids[reuse - 1]))
for n, ident in enumerate(ids):
self._put(("kv", ident), self.kv_block)
if self.snap_every is not None and ((n + 1) * BLOCK % self.snap_every == 0 or n == len(ids) - 1):
self._put(("state", ident), STATE)
computed = len(tokens) - reuse * BLOCK
self.recent.append((now, computed))
return computed
def replay(requests, kv_per_token, snap_every, policy, budget=BUDGET):
engines = [Engine(kv_per_token, snap_every, budget) for _ in range(ENGINES)]
total = computed = 0
per_engine = [0] * ENGINES
for i, (now, session, tokens) in enumerate(requests):
ids = identities(tokens)
if policy == "round-robin":
e = i % ENGINES
elif policy == "least-loaded":
e = min(range(ENGINES), key=lambda j: engines[j].load(now))
else:
e = min(range(ENGINES), key=lambda j: (len(tokens) - engines[j].reusable_blocks(ids) * BLOCK
+ engines[j].load(now)))
c = engines[e].serve(now, tokens, ids)
total += len(tokens)
computed += c
per_engine[e] += c
return {"prompt_tokens": total, "computed_tokens": computed, "reused_share": round(1 - computed / total, 4),
"busiest_engine_share": round(max(per_engine) / max(sum(per_engine), 1), 3)}
def main():
requests = trace()
print(f"{len(requests)} requests, {sum(len(r[2]) for r in requests):,} prompt tokens, "
f"cache budget {BUDGET / 2**30:.0f} GiB per engine: dense holds {BUDGET // DENSE_KV:,} tokens, "
f"hybrid {BUDGET // HYBRID_KV:,} before snapshots (one snapshot = {STATE / HYBRID_KV:,.0f} tokens of KV)")
rows = []
for kind, kv, snap in KINDS:
for policy in ("round-robin", "least-loaded", "cache-aware"):
r = {"cache": kind, "policy": policy, **replay(requests, kv, snap, policy)}
rows.append(r)
print(f"{kind:30s} {policy:13s} reused {r['reused_share']:6.1%} computed {r['computed_tokens']:>11,}"
f" busiest engine {r['busiest_engine_share']:.0%}")
write(HERE / "results" / "route.csv", rows)
sweep = []
for gib in (1, 2, 4, 8, 16, 32):
for kind, kv, snap in KINDS:
r = replay(requests, kv, snap, "cache-aware", gib * 2**30)
sweep.append({"budget_gib": gib, "cache": kind, **r})
print(f"{gib:>2} GiB {kind:30s} reused {r['reused_share']:6.1%}")
write(HERE / "results" / "route_budget.csv", sweep)
def write(path, rows):
with path.open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
if __name__ == "__main__":
main()
arch_compare.py: the 19-model resume-point comparison (needs simulate.py from Understanding LLM Inference)
"""What a prefix cache must keep to resume each of 19 open models, from their config.json layer maps.
Uses layers() / simulate() from specs/2026-12-04-inference-deep-dive/bench/simulate.py unchanged (the same per-layer model
as "Understanding LLM Inference"): bf16 KV, fp32 recurrent states, index keys of sparse layers counted.
Per model:
resume where a cached prefix can end: "any block" when every layer keeps every token (full attention, MLA,
sparse reads over stored tokens); "window tail" when sliding-window or compressed layers dropped older
tokens (the engine needs the last W tokens' KV at the resume point); "state snapshot" when recurrent
layers (DeltaNet, KDA, Mamba-2) fold the prefix into a fixed state that cannot be rewound
per_token bytes kept per cached token (KV + index keys)
resume_point bytes one resume point costs beyond the per-token cache: the recurrent states, or the window tails
overhead_1024 resume points every 1,024 tokens, as a multiple of the per-token cache they sit on
branch_16k tokens recomputed when a retry branches at 16,384 of a cached 32,768-token prompt and the only resume
point kept is the prompt's end (the default retention in vLLM and SGLang, sources/serving-stacks.md)
Run: python3 -I arch_compare.py -> results/arch_compare.csv
"""
import csv
import sys
from pathlib import Path
HERE = Path(__file__).parent
sys.path.insert(0, str(HERE.parent / "2026-12-04-inference-deep-dive" / "bench"))
import simulate # noqa: E402
N, BRANCH, EVERY = 32768, 16384, 1024
def resume_class(kinds):
if "state" in kinds:
return "state snapshot"
if kinds & {"window", "csa", "hca"}:
return "window tail"
return "any block"
def main():
rows = []
for repo, label, active, first in simulate.MODELS:
s = simulate.simulate(repo)
kinds = set(s["kinds"])
cls = resume_class(kinds)
per_tok, fixed = s["per_tok"], s["fixed"]
rows.append({
"model": label, "first_listed": first, "design": simulate.DESIGN[label], "resume": cls, "layers": s["layers"],
"state_layers": s["kinds"].count("state"),
"window_layers": sum(k in ("window", "csa", "hca") for k in s["kinds"]),
"per_token_kib": round(per_tok / 1024, 2), "resume_point_mib": round(fixed / 2**20, 2),
"resume_point_in_tokens": round(fixed / per_tok) if per_tok else "",
"prefix_32k_gib": round(s["mem"](N) / 2**30, 3),
"overhead_1024": round(fixed / (EVERY * per_tok), 2) if per_tok else "",
"branch_16k_recomputed": 0 if cls == "any block" else BRANCH,
})
out = HERE / "results" / "arch_compare.csv"
with out.open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
for r in sorted(rows, key=lambda r: (r["resume"], -r["per_token_kib"])):
print(f"{r['model']:28s} {r['resume']:15s} {r['per_token_kib']:7.2f} KiB/tok resume point "
f"{r['resume_point_mib']:8.2f} MiB (= {r['resume_point_in_tokens']} tok) every 1,024: "
f"{r['overhead_1024']}x 32K prefix {r['prefix_32k_gib']:.2f} GiB branch@16K recompute {r['branch_16k_recomputed']}")
if __name__ == "__main__":
main()
layer_maps.py: the layer maps of the three test models, from config.json (stdlib only)
"""Layer maps of the three models measured on the M4, from each model's config.json on Hugging Face.
What a prefix cache has to keep for each layer kind:
full attention every token's key and value (2 x KV heads x head_dim x 2 bytes in f16, per layer)
sliding window the last `sliding_window` tokens only (older ones are dropped, so an old prefix is gone)
Gated DeltaNet one fixed recurrent state per sequence (value heads x key dim x value dim, f32), plus a short conv state
Run: python3 -I layer_maps.py -> results/layer_maps.csv (layer_kinds: one letter per layer, in order)
"""
import csv
import json
import urllib.request
from pathlib import Path
HERE = Path(__file__).parent
MODELS = [("Qwen/Qwen3-0.6B", "Qwen3-0.6B", "dense"), ("Qwen/Qwen3.5-0.8B", "Qwen3.5-0.8B", "hybrid DeltaNet"),
("unsloth/gemma-3-270m-it", "Gemma 3 270M", "sliding window")]
F16, F32 = 2, 4
def config(repo):
url = f"https://huggingface.co/{repo}/resolve/main/config.json"
c = json.loads(urllib.request.urlopen(url, timeout=30).read())
return c.get("text_config", c)
def row(repo, label, family):
c = config(repo)
n = c["num_hidden_layers"]
types = c.get("layer_types") or ["full_attention"] * n
kv_layer = 2 * c["num_key_value_heads"] * c["head_dim"] * F16 # bytes per token per attention layer
full = types.count("full_attention")
window = types.count("sliding_attention")
linear = types.count("linear_attention")
state = 0
if linear:
# Gated DeltaNet: a (key dim x value dim) matrix per value head, kept in f32
state = linear * c["linear_num_value_heads"] * c["linear_key_head_dim"] * c["linear_value_head_dim"] * F32
win = c.get("sliding_window") or 0
kinds = "".join({"full_attention": "F", "sliding_attention": "W", "linear_attention": "D"}[k] for k in types)
return {"model": label, "repo": repo, "family": family, "layers": n, "full_attention": full,
"sliding_window_layers": window, "sliding_window": win if window else "", "deltanet_layers": linear,
"kv_bytes_per_token": full * kv_layer, "window_bytes_fixed": window * win * kv_layer,
"state_bytes_fixed": state, "kv_heads": c["num_key_value_heads"], "head_dim": c["head_dim"],
"layer_kinds": kinds} # per layer, in order: F full, W window, D DeltaNet
def main():
rows = [row(*m) for m in MODELS]
out = HERE / "results" / "layer_maps.csv"
out.parent.mkdir(exist_ok=True)
with out.open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
for r in rows:
print(f"{r['model']:14s} {r['layers']} layers: {r['full_attention']} full, {r['sliding_window_layers']} window"
f" {r['sliding_window']}, {r['deltanet_layers']} DeltaNet | KV {r['kv_bytes_per_token'] / 1024:.1f} KiB/token"
f" + window {r['window_bytes_fixed'] / 2**20:.2f} MiB + state {r['state_bytes_fixed'] / 2**20:.1f} MiB fixed")
if __name__ == "__main__":
main()
bench_llamacpp.py: the raw-API llama.cpp benchmark
"""What llama.cpp can reuse from a cached prompt, for a dense, a hybrid (Gated DeltaNet) and a sliding-window model.
One llama-server per (model, cache setting), one slot (-np 1), no host prompt cache (--cache-ram 0), Metal. Prompts
are token arrays cut from Narwhal's concept pages (corpus/), so every prefix length is exact. For each base length:
cold the base prompt on an empty slot (everything is computed)
append base + 64 new tokens (a chat turn or an agent's next tool call)
branch f the first f of the base + 64 different tokens (an agent retrying from an earlier step)
edit the base with one token changed near the start (a system prompt edit)
Before every append / branch / edit the slot is erased and primed with the base, so each request starts from the same
cache. llama.cpp reports `prompt_n` (tokens it computed) and `prompt_ms`; recomputed = prompt_n, and the tokens it
reused are the prompt length minus prompt_n. The server log lines that mention checkpoints are kept as evidence.
Run: python3 -I bench_llamacpp.py <llama-server> <models dir> -> results/llamacpp.csv, results/llamacpp-checkpoints.log
"""
import csv
import json
import subprocess
import sys
import tempfile
import time
import urllib.request
from pathlib import Path
HERE = Path(__file__).parent
SERVER, MODELS_DIR = sys.argv[1], Path(sys.argv[2])
PORT = 18301
MODELS = [("Qwen3-0.6B", "Qwen3-0.6B-Q4_K_M.gguf"), ("Qwen3.5-0.8B", "Qwen3.5-0.8B-Q4_K_M.gguf"),
("Gemma 3 270M", "gemma-3-270m-it-Q4_K_M.gguf")]
SETTINGS = [("default", []), # b12365: up to 32 checkpoints, >= 8,192 tokens apart
("checkpoint every 1,024", ["--checkpoint-min-step", "1024"]),
("no checkpoints", ["--ctx-checkpoints", "0"]),
("swa-full", ["--swa-full"])] # only changes the sliding-window model
BASES = [6000, 12000]
BRANCH = [0.25, 0.5, 0.75, 0.9]
SUFFIX = 64
REPS = 2
def post(path, body, timeout=300):
req = urllib.request.Request(f"http://127.0.0.1:{PORT}{path}", json.dumps(body).encode(),
{"Content-Type": "application/json"})
return json.loads(urllib.request.urlopen(req, timeout=timeout).read())
def wait_ready():
for _ in range(240):
try:
h = json.loads(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health", timeout=2).read())
if h.get("status") == "ok":
return
except OSError:
pass
time.sleep(0.5)
raise SystemExit("llama-server never became ready")
def complete(tokens):
r = post("/completion", {"prompt": tokens, "n_predict": 1, "id_slot": 0, "cache_prompt": True, "temperature": 0})
t = r["timings"]
return t["prompt_n"], t["prompt_ms"], t.get("cache_n")
def prime(base):
post("/slots/0?action=erase", {})
complete(base)
def run(model, gguf, setting, flags, text, rows, log):
slots = Path(tempfile.mkdtemp(prefix="slots-", dir=HERE))
err = tempfile.NamedTemporaryFile("w+", suffix=".log", delete=False)
proc = subprocess.Popen([SERVER, "--model", str(MODELS_DIR / gguf), "--host", "127.0.0.1", "--port", str(PORT),
"--ctx-size", "16384", "--parallel", "1", "--n-gpu-layers", "all", "--cache-ram", "0",
"--slot-save-path", str(slots), *flags], stdout=subprocess.DEVNULL, stderr=err)
try:
wait_ready()
tokens = post("/tokenize", {"content": text})["tokens"]
tail = tokens[-4 * SUFFIX:]
s1, s2 = tail[:SUFFIX], tail[2 * SUFFIX:3 * SUFFIX]
for n in BASES:
base = tokens[:n]
cases = [("cold", None, base), ("append", 1.0, base + s1)]
cases += [(f"branch", f, base[:int(n * f)] + s2) for f in BRANCH]
edited = list(base)
edited[16] = base[17]
cases.append(("edit", 16 / n, edited))
for kind, at, prompt in cases:
for rep in range(REPS):
if kind == "cold":
post("/slots/0?action=erase", {})
else:
prime(base)
computed, ms, cache_n = complete(prompt)
rows.append({"model": model, "setting": setting, "base_tokens": n, "case": kind,
"shared_tokens": 0 if kind == "cold" else (16 if kind == "edit" else int(n * at) if kind == "branch" else n),
"prompt_tokens": len(prompt), "computed_tokens": computed,
"reused_tokens": len(prompt) - computed, "prompt_ms": round(ms, 2),
"cache_n": cache_n, "rep": rep})
print(model, setting, n, kind, at, "computed", computed, "of", len(prompt), f"{ms:.0f} ms", flush=True)
finally:
proc.terminate()
proc.wait(timeout=60)
for f in slots.glob("*"):
f.unlink()
slots.rmdir()
err.seek(0)
lines = [l.rstrip() for l in err if "checkpoint" in l.lower()]
log.write(f"### {model} | {setting} | {len(lines)} checkpoint lines\n")
log.writelines(l + "\n" for l in lines[:40])
err.close()
Path(err.name).unlink()
def main():
text = "\n\n".join(p.read_text() for p in sorted((HERE / "corpus").glob("*.md")))
rows = []
out = HERE / "results"
out.mkdir(exist_ok=True)
with (out / "llamacpp-checkpoints.log").open("w") as log:
for model, gguf in MODELS:
for setting, flags in SETTINGS:
if setting == "swa-full" and "gemma" not in gguf:
continue
run(model, gguf, setting, flags, text, rows, log)
with (out / "llamacpp.csv").open("w", newline="") as f: # rewrite after every run: partial results survive
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
if __name__ == "__main__":
main()
bench_chat.py: the chat-API llama.cpp benchmark
"""Hybrid and sliding-window prefix reuse through llama.cpp's chat API, where its context checkpoints actually apply.
llama.cpp b12365 places checkpoints at user-message boundaries (at least --checkpoint-min-step tokens apart) and two
near the end of each prompt (tools/server/server-context.cpp:4526, 4536-4542; sources/serving-stacks.md L5-L7). A raw
token-array prompt has no user messages, so bench_llamacpp.py could only ever find the end-of-prompt pair. Here the
prompt is a real chat: a system prompt, then 20 turns of a user message (a chunk of Narwhal's docs, standing in for a
tool result) and a short assistant reply. An agent retry keeps the first k turns and sends a different user message.
Per (model, setting): prime the slot with the full chat, then send the branch; llama.cpp's `timings.prompt_n` is the
number of tokens it computed. `shared_tokens` is the common prefix of the two rendered prompts (/apply-template +
/tokenize), i.e. the most any cache could reuse.
Run: python3 -I bench_chat.py <llama-server> <models dir> -> results/chat.csv, results/chat-checkpoints.log
"""
import csv
import json
import subprocess
import sys
import tempfile
import time
import urllib.request
from pathlib import Path
HERE = Path(__file__).parent
SERVER, MODELS_DIR = sys.argv[1], Path(sys.argv[2])
PORT = 18302
MODELS = [("Qwen3-0.6B", "Qwen3-0.6B-Q4_K_M.gguf"), ("Qwen3.5-0.8B", "Qwen3.5-0.8B-Q4_K_M.gguf"),
("Gemma 3 270M", "gemma-3-270m-it-Q4_K_M.gguf")]
SETTINGS = [("default", []), ("checkpoint every 2,048", ["--checkpoint-min-step", "2048"]),
("checkpoint every user turn", ["--checkpoint-min-step", "0"]), ("no checkpoints", ["--ctx-checkpoints", "0"]),
("swa-full", ["--swa-full"])]
TURNS = 20
BRANCH_AT = [5, 10, 15, 19]
REPS = 2
def post(path, body, timeout=300):
req = urllib.request.Request(f"http://127.0.0.1:{PORT}{path}", json.dumps(body).encode(),
{"Content-Type": "application/json"})
return json.loads(urllib.request.urlopen(req, timeout=timeout).read())
def wait_ready():
for _ in range(240):
try:
if json.loads(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health", timeout=2).read()).get("status") == "ok":
return
except OSError:
pass
time.sleep(0.5)
raise SystemExit("llama-server never became ready")
def chat(messages):
r = post("/v1/chat/completions", {"messages": messages, "max_tokens": 1, "temperature": 0, "cache_prompt": True})
return r["timings"]["prompt_n"], r["timings"]["prompt_ms"]
def rendered_tokens(messages):
prompt = post("/apply-template", {"messages": messages})["prompt"]
return post("/tokenize", {"content": prompt, "add_special": True})["tokens"]
def conversation():
words = " ".join(p.read_text() for p in sorted((HERE / "corpus").glob("*.md"))).split()
take = lambda i, n: " ".join(words[i:i + n])
msgs = [{"role": "system", "content": "You are an agent that operates an inference fleet. " + take(0, 400)}]
i = 400
for _ in range(TURNS):
msgs.append({"role": "user", "content": "Tool result:\n" + take(i, 320)})
msgs.append({"role": "assistant", "content": take(i + 320, 60)})
i += 380
retry = [{"role": "user", "content": "Tool result (retried):\n" + take(i, 320)}]
return msgs, retry
def run(model, gguf, setting, flags, rows, log):
err = tempfile.NamedTemporaryFile("w+", suffix=".log", delete=False)
proc = subprocess.Popen([SERVER, "--model", str(MODELS_DIR / gguf), "--host", "127.0.0.1", "--port", str(PORT),
"--ctx-size", "24576", "--parallel", "1", "--n-gpu-layers", "all", "--cache-ram", "0",
"--jinja", *flags], stdout=subprocess.DEVNULL, stderr=err)
try:
wait_ready()
msgs, retry = conversation()
full = msgs + [{"role": "user", "content": "What next?"}]
full_tokens = rendered_tokens(full)
for k in BRANCH_AT:
branch = msgs[:1 + 2 * k] + retry
b_tokens = rendered_tokens(branch)
shared = next((i for i, (a, b) in enumerate(zip(full_tokens, b_tokens)) if a != b), min(len(full_tokens), len(b_tokens)))
for rep in range(REPS):
chat([{"role": "user", "content": "reset"}]) # evict the previous conversation from the slot
cold, cold_ms = chat(full)
computed, ms = chat(branch)
rows.append({"model": model, "setting": setting, "turns_kept": k, "prompt_tokens": len(b_tokens),
"shared_tokens": shared, "computed_tokens": computed,
"recomputed_shared": max(0, computed - (len(b_tokens) - shared)),
"prompt_ms": round(ms, 2), "full_tokens": len(full_tokens), "full_ms": round(cold_ms, 2),
"rep": rep})
print(model, setting, "keep", k, "turns: shared", shared, "of", len(b_tokens), "computed", computed,
f"{ms:.0f} ms", flush=True)
finally:
proc.terminate()
proc.wait(timeout=60)
err.seek(0)
lines = [l.rstrip() for l in err if "checkpoint" in l.lower() or "re-processing" in l.lower()]
log.write(f"### {model} | {setting} | {len(lines)} lines\n")
log.writelines(l + "\n" for l in lines[:60])
log.flush()
err.close()
Path(err.name).unlink()
def main():
rows = []
out = HERE / "results"
with (out / "chat-checkpoints.log").open("w") as log:
for model, gguf in MODELS:
for setting, flags in SETTINGS:
if setting == "swa-full" and "gemma" not in gguf:
continue
if model == "Qwen3-0.6B" and setting not in ("default",):
continue # dense: nothing to checkpoint
run(model, gguf, setting, flags, rows, log)
with (out / "chat.csv").open("w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
if __name__ == "__main__":
main()
tokens.py: the real prompt, token IDs and block names for the infographic
"""Real tokens for the infographic: one small agent chat rendered by Qwen3.5-0.8B's own chat template, tokenized by its
own tokenizer (llama-server /apply-template + /tokenize), cut into 16-token blocks and named with chained SHA-256 the way
Narwhal's formula reads (root over version, model, tokenizer, adapter, cache_salt, block_size; my JSON serialization).
Three prompts: turn 1; turn 2 (= turn 1 + the reply + the next tool result: an append); a retry (= turn 1 with a
different tool result in place of the last one: a branch).
Run: python3 -I tokens.py <llama-server> <models dir> -> results/tokens.json
"""
import hashlib
import json
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
HERE = Path(__file__).parent
SERVER, MODELS = sys.argv[1], Path(sys.argv[2])
PORT, BLOCK = 18303, 16
SYSTEM = "You are a coding agent. Tools: search(query), read(path)."
TURN1 = [{"role": "system", "content": SYSTEM},
{"role": "user", "content": "Where is the KV cache allocated?"},
{"role": "assistant", "content": "search(\"kv cache alloc\")"},
{"role": "user", "content": "Tool result: 3 files"}]
TURN2 = TURN1 + [{"role": "assistant", "content": "read(\"cache.py\")"},
{"role": "user", "content": "Tool result: def allocate(blocks):"}]
RETRY = TURN1[:3] + [{"role": "user", "content": "Tool result: timeout, retried: 5 files"}]
def post(path, body):
req = urllib.request.Request(f"http://127.0.0.1:{PORT}{path}", json.dumps(body).encode(),
{"Content-Type": "application/json"})
return json.loads(urllib.request.urlopen(req, timeout=60).read())
def identities(ids):
root = hashlib.sha256(json.dumps([1, "Qwen3.5-0.8B", "qwen35", "", "", BLOCK]).encode()).digest()
out, prev = [], root
usable = ids[:-1] # the last token is never matched
for b in range(len(usable) // BLOCK):
prev = hashlib.sha256(prev + json.dumps(usable[b * BLOCK:(b + 1) * BLOCK]).encode()).digest()
out.append(prev.hex())
return out
def main():
proc = subprocess.Popen([SERVER, "--model", str(MODELS / "Qwen3.5-0.8B-Q4_K_M.gguf"), "--host", "127.0.0.1",
"--port", str(PORT), "--ctx-size", "2048", "--jinja"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(240):
try:
if json.loads(urllib.request.urlopen(f"http://127.0.0.1:{PORT}/health", timeout=2).read()).get("status") == "ok":
break
except OSError:
pass
time.sleep(0.5)
out = {}
for name, msgs in (("turn1", TURN1), ("turn2", TURN2), ("retry", RETRY)):
text = post("/apply-template", {"messages": msgs})["prompt"]
toks = post("/tokenize", {"content": text, "add_special": True, "with_pieces": True})["tokens"]
ids = [t["id"] for t in toks]
out[name] = {"messages": msgs, "text": text, "ids": ids, "pieces": [t["piece"] for t in toks],
"blocks": identities(ids)}
shared = lambda a, b: next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b)))
hits = lambda a, b: next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b)))
for name in ("turn2", "retry"):
out[name]["shared_tokens"] = shared(out["turn1"]["ids"], out[name]["ids"])
out[name]["matched_blocks"] = hits(out["turn1"]["blocks"], out[name]["blocks"])
(HERE / "results" / "tokens.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
for name, v in out.items():
print(name, len(v["ids"]), "tokens,", len(v["blocks"]), "full blocks", {k: v[k] for k in v if k.endswith(("tokens", "blocks")) and not isinstance(v[k], list)})
print(repr(out["turn1"]["text"][:200]))
print(list(zip(out["turn1"]["pieces"][:20], out["turn1"]["ids"][:20])))
finally:
proc.terminate()
proc.wait(timeout=30)
if __name__ == "__main__":
main()
infographic.py: the one-page infographic (needs infographic.py from Understanding LLM Inference)
"""The one-page SVG infographic: what prefix caching is, in depth, from one real agent conversation.
Qwen3.5-0.8B's own chat template and tokenizer (results/tokens.json from tokens.py): the prompt, its token IDs, 16-token
blocks with chained SHA-256 names, and the lookup for an append and a retry. Then why reuse is exact, what each kind of
layer must keep to resume, one retry measured on the M4, where the serving stacks save states, the fleet, and the 19
models. Every number is read from results/*; the llama.cpp/vLLM defaults are quoted from their source (cited.csv).
Style and helpers: specs/2026-12-04-inference-deep-dive/bench/infographic.py (hand-drawn font embedded, OFL).
Run: uv run --no-project --with fonttools --with brotli python3 -I infographic.py -> figs/prefix-caching-infographic.svg
"""
import csv
import importlib.util
import json
import re
from pathlib import Path
HERE = Path(__file__).parent
RES = HERE / "results"
_spec = importlib.util.spec_from_file_location(
"inf", HERE.parent / "2026-12-04-inference-deep-dive" / "bench" / "infographic.py")
inf = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(inf)
t, m, box, rect, arrow, path_arrow, head, code = inf.t, inf.m, inf.box, inf.rect, inf.arrow, inf.path_arrow, inf.head, inf.code
INK, MID, PAPER, SOFT, GRID = inf.INK, inf.MID, inf.PAPER, inf.SOFT, inf.GRID
TEAL, BLUE, AMBER, GREEN, CRIMSON, PURPLE, GREY = inf.TEAL, inf.BLUE, inf.AMBER, inf.GREEN, inf.CRIMSON, inf.PURPLE, inf.GREY
W, H = 1800, 4270
def esc(s):
return s.replace("&", "&").replace("<", "<").replace(">", ">")
def rows(name):
with open(RES / name) as f:
return list(csv.DictReader(f))
def piece(p):
return esc(p.replace("\n", "\\n").replace(" ", "·"))
def chips(x, y, ids, pieces, w=64, col=AMBER, hi=None):
out = []
for i, (tid, p) in enumerate(zip(ids, pieces)):
xx = x + i * (w + 6)
c = hi(i) if hi else col
out.append(rect(xx, y, w, 40, c, 0.16, 6, f' stroke="{c}" stroke-width="2"'))
out.append(m(xx + w / 2, y + 26, str(tid), 13 if tid < 100000 else 11.5, INK, "middle"))
out.append(m(xx + w / 2, y - 8, piece(p)[:12], 12, MID, "middle"))
return out
def blockrow(x, y, n, filled, col, w=92, h=34, labels=None, total=None):
out = []
for i in range(n):
f = i < filled
out.append(rect(x + i * (w + 8), y, w, h, col if f else PAPER, 0.85 if f else 1, 6,
f' stroke="{col if f else GREY}" stroke-width="2"' + ('' if f else ' stroke-dasharray="5 4"')))
if labels:
out.append(m(x + i * (w + 8) + w / 2, y + 22, labels[i], 13, PAPER if f else MID, "middle"))
return out
def main():
tok = json.load(open(RES / "tokens.json"))
t1, t2, rt = tok["turn1"], tok["turn2"], tok["retry"]
lm = {r["model"]: r for r in rows("layer_maps.csv")}
ck = {r["case"]: r for r in rows("checks.csv")}
chat = {}
for r in rows("chat.csv"):
chat.setdefault((r["model"], r["setting"], int(r["turns_kept"])), []).append(r)
raw = {}
for r in rows("llamacpp.csv"):
raw.setdefault((r["model"], r["setting"], r["base_tokens"], r["case"], r["shared_tokens"]), []).append(r)
route = {(r["cache"], r["policy"]): float(r["reused_share"]) for r in rows("route.csv")}
budget = {(int(r["budget_gib"]), r["cache"]): float(r["reused_share"]) for r in rows("route_budget.csv")}
arch = sorted(rows("arch_compare.csv"), key=lambda r: (r["first_listed"], r["model"]))
med = lambda xs, k: sorted(float(x[k]) for x in xs)[len(xs) // 2 - (1 if len(xs) % 2 == 0 else 0):][0] if len(xs) % 2 else \
sum(sorted(float(x[k]) for x in xs)[len(xs) // 2 - 1:len(xs) // 2 + 1]) / 2
kib = lambda r: int(r["kv_bytes_per_token"]) / 1024
mib = lambda v: int(v) / 2**20
q35, q3, gm = lm["Qwen3.5-0.8B"], lm["Qwen3-0.6B"], lm["Gemma 3 270M"]
b = [t(70, 84, "What is prefix caching? And why the smallest KV cache is the hardest to reuse", 50),
t(70, 132, "A from-scratch walk through one agent conversation on a real model, Qwen3.5-0.8B: its chat template and "
"tokenizer IDs, 16-token blocks with chained SHA-256 names,", 22, MID),
t(70, 160, "what each kind of layer must keep to resume a cached prompt, and one agent retry measured on my MacBook "
"(M4 Pro, 24 GB) with llama.cpp.", 22, MID)]
# ================= 1. one agent turn, as the server sees it =================
y = 200
b.append(box(40, y, 1720, 890))
b += head(1, 70, y + 56, "One agent turn, as the server sees it",
f"Qwen3.5-0.8B's own chat template and tokenizer · {len(t1['ids'])} tokens · blocks of 16 · the last token is never matched")
msgs = [("system", t1["messages"][0]["content"], PURPLE), ("user", t1["messages"][1]["content"], BLUE),
("assistant", t1["messages"][2]["content"], GREEN), ("user", t1["messages"][3]["content"], BLUE)]
yy = y + 120
for i, (role, text, c) in enumerate(msgs):
b.append(rect(80, yy + i * 50, 470, 40, c, 0.12, 8, f' stroke="{c}" stroke-width="2"'))
b.append(t(94, yy + i * 50 + 27, f"{role}:", 17, c))
b.append(t(190, yy + i * 50 + 27, esc(text[:44]), 17))
b.append(t(80, yy + 222, "the agent's 4 messages; the last one is a tool result", 16, MID))
b.append(arrow(565, yy + 95, 625, yy + 95))
b.append(t(595, yy + 82, "template", 15, MID, "middle"))
wrapped, cur = [], ""
for seg in t1["text"].rstrip("\n").split("\n"):
cand = (cur + " ⏎ " + seg) if cur else seg
if len(cand) > 112:
wrapped.append(cur + " ⏎")
cur = seg
else:
cur = cand
wrapped.append(cur + " ⏎")
b.append(rect(635, yy, 1100, 34 + len(wrapped) * 25 + 34, "#fbf8f5", 1, 10, f' stroke="{GREY}" stroke-width="1.5"'))
for i, ln in enumerate(wrapped):
b.append(m(652, yy + 34 + i * 25, esc(ln), 15, CRIMSON if i == len(wrapped) - 1 else INK))
b.append(t(652, yy + 34 + len(wrapped) * 25 + 14, "the text the model actually reads (⏎ = newline): the role markers "
"are tokens too, and it ends by opening the reply (red)", 16, MID))
yy = y + 430
b.append(t(80, yy - 32, "tokenizer → token IDs, block 0 (tokens 0–15):", 19))
b += chips(80, yy, t1["ids"][:16], t1["pieces"][:16], w=96)
b.append(t(80, yy + 70, "(· = a leading space; IDs above 248,000 are the chat template's special tokens)", 16, MID))
yy = y + 550
nb = len(t1["blocks"])
rem = len(t1["ids"]) - nb * 16
b.append(t(80, yy, "the cache's view: full 16-token blocks, each named after everything before it", 19))
for i, h_ in enumerate(t1["blocks"]):
x = 80 + i * 250
b.append(rect(x, yy + 18, 230, 64, TEAL, 0.14, 8, f' stroke="{TEAL}" stroke-width="2.5"'))
b.append(t(x + 12, yy + 44, f"block {i}: tokens {i * 16}–{i * 16 + 15}", 17))
b.append(m(x + 12, yy + 70, f"id = {h_[:8]}…", 15, TEAL))
if i:
b.append(arrow(x - 20, yy + 50, x - 2, yy + 50, TEAL))
x = 80 + nb * 250
b.append(rect(x, yy + 18, 180, 64, PAPER, 1, 8, f' stroke="{GREY}" stroke-width="2" stroke-dasharray="6 5"'))
b.append(t(x + 12, yy + 44, f"{rem} tokens left", 17, MID))
b.append(t(x + 12, yy + 70, "not a full block", 16, MID))
b += [m(1060, yy + 30, "root = SHA-256(version, model, tokenizer,", 15, INK),
m(1060, yy + 52, " adapter, cache_salt, 16)", 15, INK),
m(1060, yy + 74, "id[0] = SHA-256(root, tokens of block 0)", 15, INK),
m(1060, yy + 96, "id[n] = SHA-256(id[n-1], tokens of block n)", 15, TEAL)]
b.append(t(1060, yy + 122, "Narwhal's formula; vLLM chains its block hashes the same way", 16, MID))
yy = y + 710
tail = lambda d: d["ids"][d["shared_tokens"]:]
for j, (name, d, how) in enumerate([
("turn 2 (append)", t2, f"{len(t2['ids'])} tokens: the reply + the next tool result were added"),
("retry (branch)", rt, f"{len(rt['ids'])} tokens: a different tool result in place of \"3 files\"")]):
yr = yy + j * 74
nb2 = len(d["blocks"])
b.append(t(80, yr + 24, name, 20, CRIMSON if j else TEAL))
b += blockrow(250, yr, nb2, d["matched_blocks"], TEAL, w=86, h=34, labels=[h[:6] for h in d["blocks"]])
b.append(t(250 + nb2 * 94 + 14, yr + 24,
f"{how}. Shared with turn 1: {d['shared_tokens']} tokens → {d['matched_blocks']} blocks hit, "
f"compute {len(d['ids']) - d['matched_blocks'] * 16}", 17))
b.append(t(80, yy + 168, f"Even the append loses turn 1's last {len(t1['ids']) - t2['shared_tokens']} tokens: the template "
f"opened <think> for the reply and drops it once the reply is history. The retry diverges at "
f"token {rt['shared_tokens']}, exactly on a block edge.", 17, MID))
# ================= 2a. why reuse is exact =================
y = 1120
b.append(box(40, y, 850, 600))
b += head(2, 70, y + 56, "Why reuse is exact", "causal attention: token i only looks back")
n, s, x0, y0 = 8, 30, 90, y + 140
for i in range(n):
for j in range(n):
if j <= i:
cached = i < 5
b.append(rect(x0 + j * s, y0 + i * s, s - 3, s - 3, TEAL if cached else CRIMSON, 0.75 if cached else 0.55, 3))
else:
b.append(rect(x0 + j * s, y0 + i * s, s - 3, s - 3, GRID, 1, 3))
b.append(t(x0, y0 - 14, "scores q·kᵀ, 8 tokens", 16, MID))
b.append(t(x0 + n * s + 20, y0 + 70, "rows 0–4: the cached prefix.", 17, TEAL))
b.append(t(x0 + n * s + 20, y0 + 94, "Their k, v never see a later token,", 17))
b.append(t(x0 + n * s + 20, y0 + 118, "so a new suffix cannot change them.", 17))
b.append(t(x0 + n * s + 20, y0 + 164, "rows 5–7: the new tokens, computed", 17, CRIMSON))
b.append(t(x0 + n * s + 20, y0 + 188, "against cached k, v + their own.", 17))
ok = ck["reuse a cached 48-token prefix"]["exact"] == "True"
bad = ck["planted: cache built with token 3 changed"]["exact"] == "False"
b += code(70, y + 400, 790, ["full, _ = attend(prompt)".ljust(44) + "# all tokens at once",
"_, cache = attend(prompt[:48])".ljust(44) + "# turn 1, cached",
"tail, _ = attend(prompt[48:], cache=cache)".ljust(44) + "# turn 2, from cache",
"np.array_equal(full[48:], tail)".ljust(44) + f"# {ok}, bit for bit"],
"my numpy toy, two layers (complete in the post)")
b.append(t(70, y + 582, f"Planted defect: the same cache built with token 3 changed → {'not equal' if bad else '?'}. "
"A cache must hold the exact tokens.", 16, MID))
# ================= 2b. why the name must chain =================
b.append(box(910, y, 850, 600))
b.append(t(940, y + 56, "…and why a block's name must chain", 34))
b.append(t(940, y + 86, "keys and values in layer 2+ depend on every earlier token", 19, MID))
pa = ["coding agent", "search(repo)", "3 files"]
pb = ["review agent", "search(repo)", "3 files"]
for j, (lab, p, cols) in enumerate([("prompt A, cached", pa, [TEAL] * 3), ("prompt B, cached", pb, [GREY, CRIMSON, CRIMSON])]):
yr = y + 130 + j * 64
b.append(t(940, yr + 26, lab, 17))
for i, (txt, c) in enumerate(zip(p, cols)):
b.append(rect(1110 + i * 205, yr, 190, 40, c, 0.15, 6, f' stroke="{c}" stroke-width="2"'))
b.append(t(1110 + i * 205 + 95, yr + 27, txt, 17, INK, "middle"))
b.append(t(940, y + 290, "Unchained, B's blocks 2–3 get the same names as A's", 18, CRIMSON))
b.append(t(940, y + 316, "(same words) and replace A's entries. Prompt C = A + a new", 18))
b.append(t(940, y + 342, "result then reuses keys and values computed after", 18))
b.append(t(940, y + 368, "\"review agent\": a silent wrong answer.", 18))
nb_bad = ck["planted: unchained (blocks matched)"]["tokens"]
b.append(t(940, y + 420, f"My toy: chained, {ck['chained SHA-256 (blocks matched)']['tokens']} blocks hit and the output is "
f"bit-identical; unchained,", 17, MID))
b.append(t(940, y + 444, f"{nb_bad} blocks hit and the output is wrong. With 1 layer the bug hides: layer 1's", 17, MID))
b.append(t(940, y + 468, "k, v depend only on their own token. Test a prefix cache with 2+ layers.", 17, MID))
b.append(m(940, y + 532, "id = sha256(parent_id + block_tokens) # chained", 15, TEAL))
b.append(m(940, y + 558, "id = sha256(block_tokens) # unchained", 15, CRIMSON))
# ================= 3. what each kind of layer must keep =================
y = 1750
b.append(box(40, y, 1720, 600))
b += head(3, 70, y + 56, "What each kind of layer must keep to resume a prompt",
"a hybrid resumes only where ALL of its layers can · sizes from each model's config.json, bf16 KV, fp32 state")
cols3 = [
("Full attention", TEAL, f"Qwen3-0.6B: {q3['full_attention']} full-attention layers",
f"keeps k, v of every token: {kib(q3):.0f} KiB per token",
["resume at ANY block: the keys and", "values of tokens 0…t are all there"], "full"),
("Sliding window", AMBER, f"Gemma 3 270M: {gm['sliding_window_layers']} window-{gm['sliding_window']} + "
f"{gm['full_attention']} full",
f"{kib(gm):.0f} KiB per token + {mib(gm['window_bytes_fixed']):.1f} MiB of windows",
["resume at t needs tokens t−W+1…t;", "a ring buffer holds only the last W"], "window"),
("Recurrent state", CRIMSON, f"Qwen3.5-0.8B: {q35['deltanet_layers']} Gated DeltaNet + {q35['full_attention']} full",
f"{kib(q35):.0f} KiB per token + one {mib(q35['state_bytes_fixed']):.0f} MiB state",
["S ← a·S(I − b·k·kᵀ) + b·v·kᵀ, in place:", "resume only where a copy was saved"], "state")]
for i, (title, c, model, keep, rule, kind) in enumerate(cols3):
x = 80 + i * 565
b.append(t(x, y + 140, title, 28, c))
b.append(t(x, y + 170, model, 17, MID))
b.append(t(x, y + 196, keep, 18))
bx, by, nbk, bw = x, y + 230, 12, 38
for k in range(nbk):
if kind == "full":
fill, op, dash = c, 0.85, False
elif kind == "window":
fill, op, dash = (c, 0.85, False) if k >= nbk - 3 else (PAPER, 1, True)
else:
fill, op, dash = (PAPER, 1, True)
b.append(rect(bx + k * (bw + 5), by, bw, 34, fill, op, 5,
f' stroke="{c if not dash else GREY}" stroke-width="2"' + (' stroke-dasharray="5 4"' if dash else '')))
if kind == "state":
for k in (4, 8, 12):
cx = bx + k * (bw + 5) - 3
b.append(f'<rect x="{cx - 10:.1f}" y="{by + 7}" width="20" height="20" fill="{c}" '
f'transform="rotate(45 {cx:.1f} {by + 17})"/>')
b.append(t(bx, by + 62, "◆ = a saved copy of the state (a snapshot)", 15, c))
elif kind == "window":
b.append(t(bx, by + 62, "only the last window is kept; the rest is gone", 15, c))
else:
b.append(t(bx, by + 62, "every block stays usable", 15, c))
b.append(t(x, by + 104, rule[0], 18))
b.append(t(x, by + 128, rule[1], 18))
rank = ck["rank of one state-update step (of 16)"]["tokens"]
d16 = ck["96 cached, branch at 70, snapshot every 16"]["tokens"]
d40 = ck["96 cached, branch at 70, snapshot every 40"]["tokens"]
snap_tok = int(q35["state_bytes_fixed"]) // int(q35["kv_bytes_per_token"])
b.append(t(80, y + 430, f"Why no undo: one state update has rank {rank} of 16 in my toy, so it throws information away. "
f"A retry at token 70 resumes from the last snapshot: one every 16 tokens → {d16} tokens to compute, "
f"one every 40 → {d40}.", 18))
b.append(t(80, y + 470, f"The irony: per token the hybrid keeps {kib(q3) / kib(q35):.0f}x less than the dense model "
f"({kib(q35):.0f} vs {kib(q3):.0f} KiB), but each snapshot costs "
f"{mib(q35['state_bytes_fixed']):.0f} MiB, as much as {snap_tok:,} of its tokens.", 20, CRIMSON))
b.append(t(80, y + 506, "The smallest cache per token is the hardest to resume: it can only restart where a state was "
"saved, and states are expensive to save.", 20, CRIMSON))
b.append(t(80, y + 548, "MLA (DeepSeek, GLM) keeps one latent per token: still any block. DeepSeek V4's compressed "
"attention keeps a recent window: like the window layers.", 17, MID))
# ================= 4. one retry, measured =================
y = 2380
b.append(box(40, y, 1720, 580))
keep = 10
sh = int(chat[("Qwen3.5-0.8B", "default", keep)][0]["shared_tokens"])
b += head(4, 70, y + 56, "One agent retry, measured: shared tokens llama.cpp recomputed",
f"a 20-turn agent chat; the retry keeps {keep} turns (~{sh:,} shared tokens) · M4 Pro · llama.cpp b12365 Metal · "
"chat API · median of 2")
bars = [("Qwen3-0.6B", "default", "dense, defaults", TEAL), ("Qwen3.5-0.8B", "default", "hybrid, defaults", CRIMSON),
("Qwen3.5-0.8B", "checkpoint every 2,048", "hybrid, --checkpoint-min-step 2048", CRIMSON),
("Qwen3.5-0.8B", "checkpoint every user turn", "hybrid, --checkpoint-min-step 0", CRIMSON),
("Qwen3.5-0.8B", "no checkpoints", "hybrid, --ctx-checkpoints 0", CRIMSON),
("Gemma 3 270M", "default", "window, defaults", AMBER),
("Gemma 3 270M", "checkpoint every user turn", "window, --checkpoint-min-step 0", AMBER),
("Gemma 3 270M", "swa-full", "window, --swa-full", AMBER)]
top = max(int(chat[(mm, s_, keep)][0]["recomputed_shared"]) for mm, s_, _, _ in bars)
for i, (mm, s_, lab, c) in enumerate(bars):
xs = chat[(mm, s_, keep)]
rec = int(xs[0]["recomputed_shared"])
ms = med(xs, "prompt_ms")
yr = y + 120 + i * 48
b.append(t(80, yr + 24, mm, 18, c))
b.append(m(250, yr + 22, lab.split(", ", 1)[1], 14, INK))
b.append(rect(560, yr + 4, 560, 26, GRID, 1, 4))
if rec:
b.append(rect(560, yr + 4, max(4, 560 * rec / top), 26, c, 0.85, 4))
b.append(t(1135, yr + 24, f"{rec:,} tokens · {ms:,.0f} ms", 18, c if rec > 100 else INK))
r_h = raw[("Qwen3.5-0.8B", "default", "12000", "branch", "9000")]
r_d = raw[("Qwen3-0.6B", "default", "12000", "branch", "9000")]
b.append(t(1380, y + 150, "and llama.cpp's own log line:", 17, MID))
for i, ln in enumerate(["\"forcing full prompt", "re-processing due to", "lack of cache data", "(likely due to SWA or",
"hybrid/recurrent memory\""]):
b.append(m(1380, y + 182 + i * 24, ln, 15, CRIMSON))
b.append(t(1380, y + 330, "raw token API, retry at", 17))
b.append(t(1380, y + 354, "9,000 of 12,000 tokens:", 17))
b.append(t(1380, y + 382, f"hybrid {int(r_h[0]['computed_tokens']):,} computed", 18, CRIMSON))
b.append(t(1380, y + 406, f"{med(r_h, 'prompt_ms') / 1000:.2f} s", 18, CRIMSON))
b.append(t(1380, y + 434, f"dense {int(r_d[0]['computed_tokens'])}, {med(r_d, 'prompt_ms'):.0f} ms", 18, TEAL))
b.append(t(80, y + 530, "The fix on llama.cpp is one flag: a checkpoint at every user turn (--checkpoint-min-step 0). "
"Defaults save one only every 8,192 tokens, at most 32 per slot.", 19, CRIMSON))
# ================= 5. why the defaults lost 5,600 tokens: the checkpoints in this chat =================
y = 2990
b.append(box(40, y, 1720, 690))
qd = {k: chat[("Qwen3.5-0.8B", "default", k)] for k in (5, 10, 15, 19)}
qt = {k: chat[("Qwen3.5-0.8B", "checkpoint every user turn", k)] for k in (5, 10, 15, 19)}
full_q = int(qd[5][0]["full_tokens"])
cut = {k: int(v[0]["shared_tokens"]) for k, v in qd.items()}
resume = {k: int(v[0]["shared_tokens"]) - int(v[0]["recomputed_shared"]) for k, v in qd.items()}
cps = sorted(set(resume.values()))
b += head(5, 70, y + 56, f"Why the defaults lost {max(int(v[0]['recomputed_shared']) for v in qd.values()):,} tokens: "
"where llama.cpp had saved states",
f"the same Qwen3.5-0.8B chat, {full_q:,} tokens cached · usable checkpoint = shared tokens − recomputed "
"tokens, for each retry")
X0, X1 = 120, 1690
sx = lambda v: X0 + (X1 - X0) * v / full_q
ya = y + 150
b.append(rect(X0, ya, X1 - X0, 30, GREY, 0.22, 6, f' stroke="{GREY}" stroke-width="2"'))
b.append(t(X0 + 10, ya - 12, f"the cached 20-turn chat, tokens 0 → {full_q:,}", 17, MID))
for v in cps:
b.append(f'<rect x="{sx(v) - 11:.1f}" y="{ya + 4}" width="22" height="22" fill="{CRIMSON}" '
f'transform="rotate(45 {sx(v):.1f} {ya + 15})"/>')
b.append(t(sx(v), ya + 62, f"checkpoint at {v:,}", 17, CRIMSON, "middle"))
b.append(f'<path d="M{sx(cut[19]):.1f} {ya - 8} L{sx(cut[19]):.1f} {ya - 2} L{X1} {ya - 2} L{X1} {ya - 8}" fill="none" '
f'stroke="{MID}" stroke-width="2"/>')
b.append(t(X1, ya - 14, f"its 2 end checkpoints: after {cut[19]:,}", 15, MID, "end"))
for i, k in enumerate((5, 10, 15, 19)):
yr = ya + 100 + i * 46
c0, r0 = cut[k], resume[k]
rec = int(qd[k][0]["recomputed_shared"])
b.append(f'<path d="M{sx(c0):.1f} {yr - 6} L{sx(c0):.1f} {yr + 32}" stroke="{INK}" stroke-width="3"/>')
b.append(rect(sx(r0), yr, max(3, sx(c0) - sx(r0)), 26, CRIMSON, 0.8, 4))
lab = f"retry keeping {k} turns: cut at {c0:,} → recompute {rec:,} ({med(qd[k], 'prompt_ms'):,.0f} ms)"
right = sx(c0) + 10
b.append(t(right if right < 1180 else sx(r0) - 10, yr + 20, lab, 17, INK, "start" if right < 1180 else "end"))
yb = ya + 300
lo = min(med(v, "prompt_ms") for v in qt.values())
hi = max(med(v, "prompt_ms") for v in qt.values())
b.append(t(80, yb, f"Why there: llama.cpp saves at user-message boundaries at least 8,192 tokens apart "
f"({cps[1]:,} − {cps[0]:,} = {cps[1] - cps[0]:,}), plus 2 near the end of each prompt. "
"Those 2 serve the next turn (an append),", 19))
b.append(t(80, yb + 28, "not a retry: a retry cuts the prompt BEFORE them, so it falls back to the last boundary "
"checkpoint, up to 8,192 tokens earlier.", 19))
b.append(t(80, yb + 68, f"With --checkpoint-min-step 0 (a state at every user turn) all four retries recomputed "
f"{int(qt[10][0]['recomputed_shared'])} tokens, in {lo:.0f}–{hi:.0f} ms.", 20, TEAL))
stacks = [("vLLM", "the replay boundary + shared-prefix junctions", "+ the last decode state; hits on the block grid"),
("SGLang", "level 2: branching points and request ends;", "level 3: every prefill chunk"),
("llama.cpp", "user turns ≥ 8,192 tokens apart + 2 near", "the end; ≤ 32 per slot, oldest dropped")]
b.append(t(80, yb + 118, "Where each server saves a state by default (read in its source, Dec 5):", 17, MID))
for i, (name, a1, a2) in enumerate(stacks):
x = 80 + i * 560
b.append(t(x, yb + 152, name, 20, PURPLE))
b.append(t(x + 100, yb + 152, a1, 16))
b.append(t(x + 100, yb + 174, a2, 16))
b.append(t(80, yb + 210, "All three are built for the next turn. The first retry at a new point pays for the "
"recompute; vLLM and SGLang keep a state at that junction for the retries after it.", 17, CRIMSON))
# ================= 6. across a fleet, and under memory pressure =================
y = 3710
b.append(box(40, y, 850, 470))
b += head(6, 70, y + 56, "Across 4 engines, and under memory pressure", "a replayed agent trace, cache-aware routing")
rr, ca = route[("dense (Qwen3-0.6B)", "round-robin")], route[("dense (Qwen3-0.6B)", "cache-aware")]
for i, (lab, v, c) in enumerate([("round-robin", rr, GREY), ("cache-aware", ca, TEAL)]):
yr = y + 120 + i * 44
b.append(t(80, yr + 22, lab, 18))
b.append(rect(230, yr + 4, 440 * v, 26, c, 0.85, 4))
b.append(t(240 + 440 * v, yr + 24, f"{v:.1%} reused", 17, c))
b.append(t(80, y + 230, "same cache bytes per engine, dense vs hybrid (state at prompt end):", 17, MID))
for i, gib in enumerate((1, 8)):
yr = y + 262 + i * 88
d_, h_ = budget[(gib, "dense (Qwen3-0.6B)")], budget[(gib, "hybrid, end of prompt only")]
b.append(t(80, yr + 40, f"{gib} GiB", 20))
b.append(rect(170, yr + 8, 470 * d_, 22, TEAL, 0.85, 4))
b.append(t(180 + 470 * d_, yr + 26, f"dense {d_:.1%}", 16, TEAL))
b.append(rect(170, yr + 38, 470 * h_, 22, CRIMSON, 0.85, 4))
b.append(t(180 + 470 * h_, yr + 56, f"hybrid {h_:.1%}", 16, CRIMSON))
b.append(t(80, y + 450, "tight memory: the hybrid wins; plenty: full attention does", 18, INK))
# ================= 7. 19 models =================
need = sorted([r for r in arch if r["resume"] != "any block"], key=lambda r: -int(r["resume_point_in_tokens"]))
old = [r for r in arch if r["first_listed"] < "2026"]
new = [r for r in arch if r["first_listed"] >= "2026"]
cnt = lambda xs: sum(r["resume"] != "any block" for r in xs)
b.append(box(910, y, 850, 470))
b += head(7, 940, y + 56, f"{len(need)} of {len(arch)} open models need resume points",
f"before 2026: {cnt(old)} of {len(old)} · first listed in 2026: {cnt(new)} of {len(new)}")
b.append(t(950, y + 120, "one resume point, in tokens of its own cache (crimson: state, amber: window)", 16, MID))
top_t = int(need[0]["resume_point_in_tokens"])
colr = {"window tail": AMBER, "state snapshot": CRIMSON}
for i, r in enumerate(need):
yr = y + 136 + i * 25
nm = r["model"].replace(" (my bench shape)", "").replace(" (no MoE)", "")
tk = int(r["resume_point_in_tokens"])
b.append(t(950, yr + 17, esc(nm[:22]), 15))
b.append(rect(1150, yr + 4, max(3, 430 * tk / top_t), 16, colr[r["resume"]], 0.85, 3))
b.append(t(1158 + max(3, 430 * tk / top_t), yr + 17, f"{tk:,} ({float(r['resume_point_mib']):,.1f} MiB)", 14, MID))
# ================= footer =================
b.append(t(70, H - 62, "First principles: a cached prompt resumes only where every layer can. Full attention: any block. "
"Window: where its last W tokens are kept. Recurrent: where a state was saved.", 23))
b.append(t(70, H - 30, "Code, CSVs and the full write-up: vadim.blog/understanding-prefix-caching", 23, MID))
body = "".join(b)
hand = "".join(re.findall(r'font-family="PH[^"]*">([^<]*)</text>', body))
style = inf.font_face(hand.replace("<", "<").replace(">", ">").replace("&", "&"))
mk = lambda i, col: (f'<marker id="{i}" markerUnits="userSpaceOnUse" refX="12" refY="7" markerWidth="14" '
f'markerHeight="14" orient="auto"><path d="M0 0 L14 7 L0 14 z" fill="{col}"/></marker>')
defs = ('<defs><filter id="rough"><feTurbulence type="fractalNoise" baseFrequency="0.03" numOctaves="2" seed="3"/>'
'<feDisplacementMap in="SourceGraphic" scale="4"/></filter>'
+ mk("arr", INK) + mk("arrc", CRIMSON) + mk("arrt", TEAL) + '</defs>')
out = HERE / "figs" / "prefix-caching-infographic.svg"
out.write_text(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" '
f'aria-label="What is prefix caching: one agent conversation through Qwen3.5-0.8B with real token IDs, '
f'chained block identities, why reuse is exact, what full-attention, sliding-window and recurrent layers '
f'must keep to resume, one retry measured on an M4 Pro, where vLLM, SGLang and llama.cpp save states, and '
f'19 open models">{style}{defs}<rect width="{W}" height="{H}" fill="{PAPER}"/>{body}</svg>')
print(f"{out.name}: {out.stat().st_size / 1024:.0f} KiB")
if __name__ == "__main__":
main()
References
From Athrael's Introduction to GPU Inference course, the basics this post builds on:
- From prompt to reply
- Serving multiple requests
- Measuring inference
- Inference at scale
- Serving architectures
- Inference engines
- Introduction to Narwhal
- Your first inference server
- Evaluating Narwhal: Adaptive Prefill/Decode Allocation Under Rapidly Changing Workloads, and its serving configurations
- Narwhal: the concept pages on prefix residency and placement
Papers:
- Kwon et al., Efficient Memory Management for Large Language Model Serving with PagedAttention
- Zheng et al., SGLang: Efficient Execution of Structured Language Model Programs (RadixAttention)
- Pan et al., Marconi: Prefix Caching for the Era of Hybrid LLMs, MLSys 2025
- Shirokikh and Nikolenko, Sparse Prefix Caching for Hybrid and Recurrent LLM Serving
- Pan et al., HiState: Hierarchical Prefix Cache Management for Hybrid LLM Serving in Agentic Workloads
- Wang and Wang, FrontierReplay: Split-Free Exact Prefix Caching for Hybrid Language Models
- Liu et al., Tail-Replay: Escaping the Curse of Linear Attention in Prefix Caching for Hybrid LLMs
- Wang et al., HybridCache: Enhancing Prefix Caching for Linear–Softmax Language Models, NeurIPS 2026
- Srivatsa et al., Preble: Efficient Distributed Prompt Scheduling for LLM Serving, ICLR 2025
- Zhang et al., Jenga: Effective Memory Management for Serving LLM with Heterogeneity
- Yang et al., Gated Delta Networks: Improving Mamba2 with Delta Rule
- Dao and Gu, Transformers are SSMs (Mamba-2)
- Kimi Team, Kimi Linear: An Expressive, Efficient Attention Architecture
- Gemma Team, Gemma 3 Technical Report
- NVIDIA, Nemotron-H: A Family of Accurate and Efficient Hybrid Mamba-Transformer Models
- DeepSeek-AI, DeepSeek-V3.2
Sebastian Raschka:
- A Visual Guide to Attention Variants in Modern LLMs
- Understanding and Coding the KV Cache in LLMs from Scratch
- Understanding Positional Embeddings in Modern LLMs
- The Big LLM Architecture Comparison and Beyond Standard LLMs
- LLM Architecture Gallery and its attention mechanism distribution
Serving stacks and APIs:
- vLLM: Automatic Prefix Caching design, Automatic Prefix Caching guide, Hybrid KV Cache Manager
- SGLang: RadixAttention, Unified Radix Cache: One Tree for Hybrid Model Prefix Caching, hybrid model prefix-cache checkpoints, hybrid model memory pools, router guide
- llama.cpp: server-context.cpp at b12365 (context checkpoints)
- Anthropic prompt caching and OpenAI prompt caching
