Unit 7 of 11 · about 6 hours · implement
Prefix hashing with collision checks and radix longest-prefix lookup
Paging chooses where KV lives; a prefix index chooses which existing state a request may reuse. Correct addressing cannot rescue a wrong prefix match.
You'll be able to
- Implement block-hash lookup with exact verification of the complete prefix identity.
- Implement trie or radix longest-prefix matching with insertion and edge splitting.
- Force hash collisions and prove they cannot return state from a different context.
Covers
Read
In this order, only the parts listed
0 of 3 done
- vLLM 0.31.0: block identity and lookupvLLM Automatic Prefix Caching Design
Automatic Prefix Caching opening hash-components list and Notes 1 to 2; Data Structure and Block Allocation
Read the full-block path. SHA-256 makes accidental collisions negligible, not impossible; including tokens in a hash input is not an exact post-hit comparison. Your educational index must verify identity explicitly.
- RadixAttention: sequence-level indexSGLang: Efficient Execution of Structured Language Model Programs
arXiv:2312.07104v2, Section 3, RadixAttention, with Figure 3
Stop before Cache-aware scheduling; policy and outcome measurement come later.
- Mini-SGLang: radix insertion and matchingMini-SGLang - Radix Cache and Cache Tests
RadixTreeNode.split_at,RadixPrefixCache.insert_prefix,_tree_walkand_get_key_fn; note page-aligned matches
Focus on
- A block key includes preceding context, current tokens and scope extras. Identical block tokens after different earlier tokens need not have identical KV.
- Hash equality selects candidates, not a proof. Retain exact immutable keys and verify the whole prefix and scope, or verify an exact parent chain plus current tokens. Comparing only the current block misses ancestor collisions.
- A radix edge holds a token sequence. A partial edge match can split it without copying the underlying KV; values and references must split at the same boundary.
- Longest-prefix matching stops at the first differing token. The paper uses token-sized pages; Mini-SGLang aligns matches to its configured page size. Neither index changes the attention algorithm's causal dependencies.
Common mistakes · 3
- Treating a strong digest as mathematically collision-free. A finite digest cannot uniquely represent all possible prefixes.
- Checking only the current block after a hash hit. Nano-vLLM's
can_allocatedoes this; it is not a complete ancestor-collision defense. - Returning a matching substring after divergence. Only a leading prefix has the same causal history under ordinary exact reuse.
Try it yourself
Closed-book, before checking anything
[[1, 2], [1, 2, 3], [4]] and requests [[1, 2, 9], [4, 5], [5]]. Match lengths are [2, 1, 0]. Rebuild it with compressed radix edges and require the same lengths. For the hash index, deliberately return a constant hash for every key; prefixes [1, 2, 7, 8] and [9, 2, 7, 8] must not share state for the final block merely because its tokens match. Keep a brute-force token-prefix oracle.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why does hashing only the current block's tokens give incorrect reuse?Answer
Its hidden states depend on earlier tokens and positions. The same block text after a different history can have different KV.
2.With a constant hash function, can an exact-key bucket index still be correct?Answer
Yes, if it compares full immutable identities inside each bucket and keeps all candidates. Performance degrades, but collisions cannot authorize a wrong match.
3.Why split a radix edge when a new request ends inside it?Answer
The split exposes the matched prefix as a node or handle boundary while preserving the old suffix. State ranges and reference protection must remain consistent.
Practice
- TensorTonic: Find Reusable Prefixes in a KV Trie
Implement
kv_prefix_trie(cached_sequences, requests); public cases cover nested/separate branches, a duplicate cached prefix and no shared first tokenThe free problem checks trie matches and insertion-order node IDs, not KV ownership. Add empty inputs, partial radix edges, forced ancestor collisions and eviction in
servelab; the section mini-project covers those extensions.
You're done when
The named trie cases pass, radix matches agree with the brute-force oracle, and constant-hash histories never return KV from a different prefix.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 11 more in the section
- SGLang: Efficient Execution of Structured Language Model ProgramsSGLang Project · required
Study RadixAttention, longest-prefix matching, eviction and cache-aware scheduling. Compare its sequence-level radix index with vLLM's block-level paging instead of treating them as competing names for one mechanism.
- Mini-SGLang - Radix Cache and Cache TestsSGLang Project · required
Read docs/structures.md, the cache allocation code and tests/core/test_cache_allocate.py. Compare exact prefix identity and lifecycle with Nano-vLLM, then add tenant and version fields to your own prefix index.
- vLLM Automatic Prefix Caching DesignvLLM Project · required
Check block hashing, extra hash keys (multimodal inputs, LoRA, cache salt), isolation and eviction against v0.31.0, the version pinned here; cache-key fields change between releases.
Also in this section
- Efficient Memory Management for Large Language Model Serving with PagedAttentionvLLM Project · primary
Read the memory-waste motivation, block-table design, sharing and copy-on-write sections, then reproduce the logical-to-physical translation on paper. Separate the paper's reported workloads from results on your engine and hardware.
- Hands-On LLM Serving and Optimization - Prefix Caching and Advanced KV CachingChi Wang and Peiheng Hu (O'Reilly) · required
Read "Prefix Caching" in Chapter 6 (RadixAttention, use cases, best practices, scaling the prefix cache) and "Advanced KV Caching" in Chapter 7 (long context, cost and latency, LMCache). Separate exact-reuse mechanisms from capacity extensions such as offload.
- AI Systems Performance Engineering - Chapter 18, tuning KV-cache utilizationChris Fregly (O'Reilly) · support
Read "Tuning KV Cache Utilization and Management" in Chapter 18 and "Prefix Caching" in Chapter 16. Leave the disaggregated pool and transfer sections for INF-7.
- Nano-vLLM - Block Manager and Sequence LifecycleGeeeekExplorer · required
Trace nanovllm/engine/block_manager.py, sequence.py, scheduler.py and attention.py. Draw allocate, append, share, preempt and free transitions, then implement randomized allocator tests in your own project before touching production-engine code.
- SGLang documentation - Radix cache eviction and HiCacheSGLang Project · support
Use the radix eviction policy and session radix cache pages to compare eviction choices with vLLM, and the HiCache design page for a GPU, host and storage hierarchy.
- AI Performance Engineering - KV Cache SystemsWafer · reference
A curated index. Use Section 4 only to find a primary KV-cache source the other entries lack.
- 100 Days of LLM Inference - Days 5, 9, 10 and 16Elizabeth Thomas · support
Use the four notebooks for KV arithmetic, paged allocation, radix reuse and prompt-layout experiments. Re-run conclusions against your own property tests and workload because these notebooks are a supplementary learning journal.
- TensorTonic Language Modeling from Scratch - Find Reusable Prefixes in a KV TrieTensorTonic · support
Solve after the prefix-index unit and add the cases its public tests leave out to your own property tests.
- LLM Inference: From scratch, one token at a time - Modules 02 and 06Tushar Amrit · support
Use The KV Cache for fragmentation and reuse and Memory Optimization for paging, prefix sharing and KV compression. Work the checkpoints before the matching units.
- LLM Inference Systems Laboratory - KV StateRoadmap-Final · support
Implement the paged allocator and prefix index with differential, randomized, cancellation, collision, fork and pressure tests. Retain one reuse workload that improves hit rate but not goodput.
- vLLM 0.31.0 - cache specifications and connector lifecyclevLLM Project · reference
Read the per-layer attention, MLA and Mamba specifications for hybrid state contracts; read the V1 connector metadata, load synchronization and deferred-free methods for transfer ownership. These fill the pool's hybrid-state and connector-contract gaps, without requiring distributed execution.