Admit a prompt
create_sequence reserves two full blocks and a partial tail for A.
- A’s prompt
- You are a guide | to the night sky | Find Mars
Work / 02 / LLM inference · Rust
Paged KV-cache memory for LLM inference, where two requests can share blocks and a hash collision can’t corrupt either.
Manage KV memory like an operating system manages pages — fixed-size refcounted blocks, copy-on-write forks, LRU eviction — and key the prefix cache on a hash chain that is always verified token by token.
492k → 72k
prompt tokens computed on simulated shared-prefix traffic, with prefix sharing on
Scheduler simulation (unit-cost steps, Llama-3-8B geometry, 2 GiB KV), mean of 3 seeds. Not end-to-end inference. source for “prompt tokens computed on simulated shared-prefix traffic, with prefix sharing on” ↗
23–65% → 0.3–3.1%
KV memory reserved but holding nothing, contiguous vs paged (workload means, simulation)
Against a contiguous allocator that reserves prompt + max tokens up front — the pessimistic baseline, and the argument the vLLM paper already made. source for “KV memory reserved but holding nothing, contiguous vs paged (workload means, simulation)” ↗
bit-identical
logits vs Candle’s native KV cache, when no prefix is reused
Candle llama2.c (stories15M, f32, CPU). With prefix hits, greedy tokens are identical and logits agree within 1e-4. source for “logits vs Candle’s native KV cache, when no prefix is reused” ↗
An LLM keeps a key and a value vector for every token it has processed, in every layer. KVCacheX is the part of an inference engine that decides where those vectors live. It handles allocating, sharing, copying and evicting them. It is not an engine itself. It is written in safe Rust with no default dependencies, and its correctness is tested harder than its speed, because a cache that shares the wrong block produces fluent, wrong text.
What it is
unsafe_code = “forbid” across the workspace. CUDA storage is an optional feature that loads the driver at run time, so building needs no CUDA toolkit.
When a request arrives, nobody knows how long its answer will be. A contiguous allocator has to reserve space for the longest possible answer up front, and most of that space is never used. Meanwhile, requests that start with the same system prompt each compute and store identical keys and values for it.
Paging fixes both. Memory is handed out in small fixed-size blocks as tokens actually arrive, and a block that holds an identical prefix can be shared by every request that needs it. This is the idea behind vLLM’s PagedAttention. KVCacheX re-implements that memory manager from first principles, to pin down exactly what has to be true for sharing to be safe.
Admit a prompt
create_sequence reserves two full blocks and a partial tail for A.
Publish the prefix
mark_computed records A’s progress through its last token and publishes only the two full blocks.
Share a prefix
create_sequence follows A’s content IDs, pins both matching blocks for B and allocates a fresh tail.
Fork the sequence
fork gives A′ a reference to every block of the fully computed A, including its partial tail.
Copy on write
append_tokens copies the shared tail before adding “tonight” to A′.
Finish the other readers
release drops B and A′ tail-first, returning their private tails to the head while A keeps its prefix pinned.
Release the last reader
release puts A’s clean tail at the head and its cached blocks at the tail, deepest prefix first.
Admit C under pressure
create_sequence revives the first prefix block, then alloc_fresh takes every clean block before evicting the oldest cached block.
Replay C’s collision
During C’s admission, lookup probed the forced hash bucket and rejected the cached block where C’s “tide” differed from “night”.
No live sequences
Empty
Fig. 1 The block pool, step by step. Every state follows the real pool and manager code.
Source crates/kvcachex/src/pool.rs
An exact prefix cache, not a trusted hash. A full block is cached under the key (namespace, parent block id, tokens). The hash of that key only picks a bucket. A hit also requires the namespace, the parent’s id and every token to match exactly. Parent ids are monotonic and never reused, so a chain cannot be spliced onto the wrong history. A colliding hash costs extra comparisons — lookup checks each candidate in the bucket until one matches exactly or the bucket ends — and can never cause a wrong share.
Decision
Trade-off: only full blocks are cached, so up to block_size − 1 tokens of a prompt are always recomputed. A radix tree would avoid that at the cost of much more complex invariants (ADR-0002).
Handles that know when they are stale. A block id carries a generation number that increases every time the block is reallocated. Releasing a block through an old handle is detected instead of silently freeing someone else’s data.
Decision
Generations are 32-bit and wrap after about 4 billion reuses of one block; the design notes say so.
Metadata separate from storage. The manager never touches tensor memory. It returns copy descriptors (“copy slots 0–2 of block 7 into block 11”), and a storage backend carries them out: a CPU buffer, or CUDA device memory, where a copy-on-write becomes a device-to-device copy.
Decision
On a Colab Tesla T4, copying one 4 MiB block device-to-device took 45.4 µs (p50). That measures storage transfer only, not inference.
One owner, one coarse lock. The manager is single-threaded by design. A mutex wrapper allows sharing it, and the benchmark shows exactly what that costs: 4.9 M operations/s on one thread falls to 0.9 M on eight. The design keeps the simple invariant and documents the limit rather than hiding it.
Decision
ADR-0004. Thread-scaling table in results/REPORT.md.
These two blocks landed in the same hash bucket. Can they share memory?
REUSE — The namespace, parent and tokens match exactly, so the request can use the stored values.
MISS — The token sequence differs, so the stored values belong to a different input.
MISS — The parent content ID differs, so the cache cannot verify the same prefix history.
MISS — The namespace differs, so sharing this block would cross a cache boundary.
KVCacheX caches only full blocks. It hashes the namespace, parent content ID and tokens to select a bucket. Lookup checks each stored candidate until all three fields match or the bucket ends.
CI reruns the KVCacheX crate’s tests with every block hash forced into one bucket.
Most cache bugs don’t crash. They hand one request another request’s memory and keep going. The tests are built to catch that.
The first question is the one paging was designed to answer: how much memory is wasted, and how much prompt work is repeated? A scheduler simulation answers it with the same requests, the same scheduler and the same byte budget for every allocator.
| Workload | Contiguous (reserve prompt + max tokens) | Paged (16-token blocks) |
|---|---|---|
| short | 64.6 % | 3.1 % |
| mixed | 37.4 % | 0.8 % |
| long | 23.3 % | 0.3 % |
| shared-prefix | 25.3 % | 0.6 % |
| parallel ×4 | 37.1 % | 1 % |
Fig. 2 Share of allocated KV memory holding nothing, by workload: contiguous reservation vs paged blocks.
Synthetic scheduler simulation: 400 requests per run, arrival rate 2/step, Llama-3-8B geometry, 2.0 GiB KV budget = 1,024 blocks × 16 tokens, seeds 1–3, Apple M1. The contiguous baseline reserves prompt + max_tokens up front (the pessimistic end). Not end-to-end inference.
Source results/REPORT.md
Fig. 3 Prompt tokens actually computed (thousands) on the two workloads where prompts share a prefix.
Source results/REPORT.md
These are simulator results in unit-cost scheduler steps, not seconds. The contiguous baseline is deliberately the pessimistic one. Paging plain workloads computes slightly more prompt tokens than contiguous allocation (68.7k vs 57.0k on short prompts), because a fuller batch means more preemption and recomputation. The simulation reproduces a published argument and checks that this implementation behaves as designed. It is not a new result.
Read with care
Prefix sharing raises waste slightly on shared workloads (0.6% → 2.2%): shared blocks stay cached after their requests finish.
To check the integration with a real model, the Candle integration re-expresses Candle’s llama2.c forward pass on top of KVCacheX’s K/V (Candle has no KV-cache hook). With no prefix hits, every logit is bit-identical to Candle’s own cache. With prefix reuse, prompt work drops sharply. Without reuse, paging is not free.
| Workload | Native tok/s | KVCacheX tok/s | Ratio | + prefix reuse tok/s |
|---|---|---|---|---|
| shared prompt, C=1 | 192.8 | 181.0 | 0.94× | 205.3 |
| shared prompt, C=4 | 160.2 | 150.1 | 0.94× | 148.0 |
| unique prompt, C=1 | 148.6 | 126.8 | 0.85× | 141.5 |
| unique prompt, C=4 | 134.9 | 138.5 | 1.03× | 120.5 |
Fig. 4 Candle llama2.c on CPU: end-to-end generated tokens per second, Candle’s native cache vs KVCacheX.
Candle 0.11.1, stories15M (6 layers, dim 288, f32), Apple M1, four Rayon threads, 16 requests × 48 generated tokens, 1 warm-up + 5 timed reps. Closed-loop interleaving, batch size 1; TTFT includes queueing. ~13% run-to-run noise.
Source results/candle/REPORT.md
On the shared-prompt workload, median prefill latency fell from 34.0 ms to 15.5 ms with one request in flight, and from 42.4 ms to 17.3 ms with four. Prompt tokens computed fell from 1,388 to 428 and 300 respectively. Throughput without prefix reuse ranges from 0.85× to 1.03× of native, comparable to the roughly 13% run-to-run noise of this laptop.
Prefill
A 15 M-parameter f32 model on CPU. It shows the integration is correct and where the overhead sits, not production performance.
The CUDA storage backend passed 9 of 9 device tests on a Tesla T4 (author-run, on Colab). On the pushed validation branch, an untuned paged-attention CUDA kernel read KV straight from blocks and ran 1.29–1.34× faster than Candle’s native path on a Kaggle T4. The validation notes attribute that mostly to kernel fusion, not paging. Both are single-session, author-run results on one GPU model, not independently reproduced.
GPU
results/gpu/README.md (main) and results/candle-gpu-paged/README.md (branch). A runbook for independent GPU validation is in the repo.
Every number on this page comes from one of these files, pinned to the commit it was read from.