Work / 02 / LLM inference · Rust

KVCacheX

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.

  1. 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” ↗

  2. 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)” ↗

  3. 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” ↗

Status
CPU-verified · GPU validation in progress
Period
Nov 2026 – present
Context
Independent open-source project
Stack
Rust · CUDA (cudarc) · Candle · proptest
On this page
  1. The problem
  2. Design
  3. Testing it like it could be wrong
  4. Measurement
  5. Where it stops
  6. Read the implementation
  7. Evidence

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.

The problem

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.

Design

The paged block pool 12 blocks · 4 tokens per block
Step 1 / 9

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

Publish the prefix

mark_computed records A’s progress through its last token and publishes only the two full blocks.

Content ID chain
root → 1 → 2
Private tail
Find Mars

Share a prefix

create_sequence follows A’s content IDs, pins both matching blocks for B and allocates a fresh tail.

Shared by A and B
#0 → #1
B’s own tail
Find Venus

Fork the sequence

fork gives A′ a reference to every block of the fully computed A, including its partial tail.

Shared tail
A and A′ → #2

Copy on write

append_tokens copies the shared tail before adding “tonight” to A′.

A keeps
#2 · Find Mars
A′ writes
#4 · Find Mars tonight

Finish the other readers

release drops B and A′ tail-first, returning their private tails to the head while A keeps its prefix pinned.

Still owned by A
#0 → #1 → #2

Release the last reader

release puts A’s clean tail at the head and its cached blocks at the tail, deepest prefix first.

Clean head
#2
Cached tail
#1 → #0

Admit C under pressure

create_sequence revives the first prefix block, then alloc_fresh takes every clean block before evicting the oldest cached block.

Revived
#0 · generation 1
Evicted and reused
#1 · generation 1 → 2

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”.

Cached #1 at lookup
to the night sky
C requested
to the tide pools
Bucket and context
hash 0x00c0111de0000000 · namespace 0 · parent cid 1
Physical blocks Outline marks a changed block
  1. Block 0 — ref 1, in use, generation 1, tokens: You are a guide, changed this step
    Block 0 — ref 1, cached, generation 1, tokens: You are a guide, content ID 1, parent 0, changed this step
    Block 0 — ref 2, cached, generation 1, tokens: You are a guide, content ID 1, parent 0, changed this step
    Block 0 — ref 3, cached, generation 1, tokens: You are a guide, content ID 1, parent 0, changed this step
    Block 0 — ref 3, cached, generation 1, tokens: You are a guide, content ID 1, parent 0
    Block 0 — ref 0, free · cached, generation 1, tokens: You are a guide, content ID 1, parent 0, changed this step
    Block 0 — ref 1, cached, generation 1, tokens: You are a guide, content ID 1, parent 0
  2. Block 1 — ref 1, in use, generation 1, tokens: to the night sky, changed this step
    Block 1 — ref 1, cached, generation 1, tokens: to the night sky, content ID 2, parent 1, changed this step
    Block 1 — ref 2, cached, generation 1, tokens: to the night sky, content ID 2, parent 1, changed this step
    Block 1 — ref 3, cached, generation 1, tokens: to the night sky, content ID 2, parent 1, changed this step
    Block 1 — ref 3, cached, generation 1, tokens: to the night sky, content ID 2, parent 1
    Block 1 — ref 0, free · cached, generation 1, tokens: to the night sky, content ID 2, parent 1, changed this step
    Block 1 — ref 1, in use, generation 2, tokens: to shore, changed this step
    Block 1 — ref 1, in use, generation 2, tokens: to shore
  3. Block 2 — ref 1, in use, generation 1, tokens: Find Mars, changed this step
    Block 2 — ref 1, in use, generation 1, tokens: Find Mars
    Block 2 — ref 2, in use, generation 1, tokens: Find Mars, changed this step
    Block 2 — ref 0, free, generation 1, changed this step
    Block 2 — ref 1, in use, generation 2, tokens: to the tide pools, changed this step
    Block 2 — ref 1, in use, generation 2, tokens: to the tide pools
  4. Block 3 — ref 0, free, generation 0
    Block 3 — ref 1, in use, generation 1, tokens: Find Venus, changed this step
    Block 3 — ref 1, in use, generation 1, tokens: Find Venus
    Block 3 — ref 0, free, generation 1, changed this step
    Block 3 — ref 0, free, generation 1
    Block 3 — ref 1, in use, generation 2, tokens: coast where the rocks, changed this step
    Block 3 — ref 1, in use, generation 2, tokens: coast where the rocks
  5. Block 4 — ref 0, free, generation 0
    Block 4 — ref 1, in use, generation 1, tokens: Find Mars tonight, changed this step
    Block 4 — ref 0, free, generation 1, changed this step
    Block 4 — ref 0, free, generation 1
    Block 4 — ref 1, in use, generation 2, tokens: along this stretch of, changed this step
    Block 4 — ref 1, in use, generation 2, tokens: along this stretch of
  6. Block 5 — ref 0, free, generation 0
    Block 5 — ref 1, in use, generation 1, tokens: shelter small crabs and, changed this step
    Block 5 — ref 1, in use, generation 1, tokens: shelter small crabs and
  7. Block 6 — ref 0, free, generation 0
    Block 6 — ref 1, in use, generation 1, tokens: limpets until the water, changed this step
    Block 6 — ref 1, in use, generation 1, tokens: limpets until the water
  8. Block 7 — ref 0, free, generation 0
    Block 7 — ref 1, in use, generation 1, tokens: rises again walk slowly, changed this step
    Block 7 — ref 1, in use, generation 1, tokens: rises again walk slowly
  9. Block 8 — ref 0, free, generation 0
    Block 8 — ref 1, in use, generation 1, tokens: over wet stone and, changed this step
    Block 8 — ref 1, in use, generation 1, tokens: over wet stone and
  10. Block 9 — ref 0, free, generation 0
    Block 9 — ref 1, in use, generation 1, tokens: look for signs of, changed this step
    Block 9 — ref 1, in use, generation 1, tokens: look for signs of
  11. Block 10 — ref 0, free, generation 0
    Block 10 — ref 1, in use, generation 1, tokens: life beneath each ledge, changed this step
    Block 10 — ref 1, in use, generation 1, tokens: life beneath each ledge
  12. Block 11 — ref 0, free, generation 0
    Block 11 — ref 1, in use, generation 1, tokens: before the tide returns, changed this step
    Block 11 — ref 1, in use, generation 1, tokens: before the tide returns
Block tables Logical slot → physical block
  • Sequence A
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 2
  • Sequence A
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 2
  • Sequence B
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 3
  • Sequence A
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 2
  • Sequence B
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 3
  • Sequence A′
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 2
  • Sequence A
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 2
  • Sequence B
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 3
  • Sequence A′
    1. Slot 0 points to block 0
    2. Slot 1 points to block 1
    3. Slot 2 points to block 4

No live sequences

  • Sequence C
    1. Slot 0 points to block 0
    2. Slot 1 points to block 2
    3. Slot 2 points to block 4
    4. Slot 3 points to block 3
    5. Slot 4 points to block 5
    6. Slot 5 points to block 6
    7. Slot 6 points to block 7
    8. Slot 7 points to block 8
    9. Slot 8 points to block 9
    10. Slot 9 points to block 10
    11. Slot 10 points to block 11
    12. Slot 11 points to block 1
Free queueAllocate from the head
Head →
  1. #3
  2. #4
  3. #5
  4. #6
  5. #7
  6. #8
  7. #9
  8. #10
  9. #11
  1. #4
  2. #5
  3. #6
  4. #7
  5. #8
  6. #9
  7. #10
  8. #11
  1. #5
  2. #6
  3. #7
  4. #8
  5. #9
  6. #10
  7. #11
  1. #4
  2. #3
  3. #5
  4. #6
  5. #7
  6. #8
  7. #9
  8. #10
  9. #11
  1. #2
  2. #4
  3. #3
  4. #5
  5. #6
  6. #7
  7. #8
  8. #9
  9. #10
  10. #11
  11. #1 cached
  12. #0 cached

Empty

→ Tail
Read all 9 steps
  1. Admit a prompt. create_sequence reserves two full blocks and a partial tail for A. Source
  2. Publish the prefix. mark_computed records A’s progress through its last token and publishes only the two full blocks. Source
  3. Share a prefix. create_sequence follows A’s content IDs, pins both matching blocks for B and allocates a fresh tail. Source
  4. Fork the sequence. fork gives A′ a reference to every block of the fully computed A, including its partial tail. Source
  5. Copy on write. append_tokens copies the shared tail before adding “tonight” to A′. Source
  6. Finish the other readers. release drops B and A′ tail-first, returning their private tails to the head while A keeps its prefix pinned. Source
  7. Release the last reader. release puts A’s clean tail at the head and its cached blocks at the tail, deepest prefix first. Source
  8. Admit C under pressure. create_sequence revives the first prefix block, then alloc_fresh takes every clean block before evicting the oldest cached block. Source
  9. 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”. Source

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.

Collision Press Prefix-cache schematic

These two blocks landed in the same hash bucket. Can they share memory?

Stored block
Namespace
12
Parent content ID
64
Token sequence
31 · 82 · 47
Requested block
Namespace
12
Parent content ID
69
Token sequence
31 · 82 · 47
Requested block
Read all four comparisons
  • Exact match
    Namespace 12 · Parent 64 · Tokens [31, 82, 47]

    REUSE — The namespace, parent and tokens match exactly, so the request can use the stored values.

  • Change a token
    Namespace 12 · Parent 64 · Tokens [31, 85, 47]

    MISS — The token sequence differs, so the stored values belong to a different input.

  • Change the parent
    Namespace 12 · Parent 69 · Tokens [31, 82, 47]

    MISS — The parent content ID differs, so the cache cannot verify the same prefix history.

  • Change the namespace
    Namespace 18 · Parent 64 · Tokens [31, 82, 47]

    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.

Testing it like it could be wrong

Most cache bugs don’t crash. They hand one request another request’s memory and keep going. The tests are built to catch that.

  • Model-based property tests. Proptest generates random sequences of create, append, fork, release and evict operations, 512 cases per suite. Every key and value written is a function of the namespace and the entire token prefix up to that position. After every operation, every computed position of every live sequence is read back and compared. A wrong share, a missed copy-on-write or a use-after-free shows up as a value mismatch.
  • Every hash collides. CI runs the core crate’s tests a second time with a feature that makes every block hash to the same constant (the one test that checks hash values themselves is skipped in that mode). Correctness then rests entirely on exact verification.
  • Mutation checks. Deliberately breaking the code must make tests fail. Skipping the copy-on-write copy corrupts read-backs and is caught. Ignoring the parent id is caught only in forced-collision mode, which is why that mode exists. Storing K in V in the Candle integration fails 5 of 7 tests.

Measurement

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.

Memory waste by workload, contiguous vs paged
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

Prompt tokens computed, in thousands, by allocator
Condition Contiguous (k)Paged (k)Paged + prefix sharing (k)
shared-prefix 466.2 k — Contiguous 491.9 k — Paged 71.6 k — Paged + prefix sharing
parallel ×4 252.6 k — Contiguous 269.9 k — Paged 76.0 k — Paged + prefix sharing

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.

On a real model

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.

Generated tokens per second (generated tokens / wall time of the interleaved workload), Candle native cache vs KVCacheX
Workload Native tok/s KVCacheX tok/s Ratio + prefix reuse tok/s
shared prompt, C=1192.8181.00.94×205.3
shared prompt, C=4160.2150.10.94×148.0
unique prompt, C=1148.6126.80.85×141.5
unique prompt, C=4134.9138.51.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.

Where it stops

  • No paged attention on main. On the default branch, every real use gathers the blocks into contiguous memory before attention. The paged CUDA kernel exists only on the validation branch.
  • Narrow GPU support. CUDA storage is f32 only, uses pageable host buffers and a single stream, and copies whole blocks on copy-on-write.
  • Integration cost is real. On MiniInfer’s feature branch, in-place paged CPU decode is 13–27% slower than the native cache at 512–1,984 tokens (BENCHMARKS.md). An isolated per-layer microbenchmark does not reproduce the slowdown, and the cause is still unknown.
  • Cache hygiene. Cached child blocks that can no longer be reached wait for LRU eviction instead of being invalidated with their parent.

Read the implementation

  1. BlockPool::lookup Exact prefix lookup: hash picks the bucket, tokens decide
  2. CacheManager::create_sequence Admission: match prefix, pin hits, then allocate
  3. CacheManager::append_tokens Copy-on-write only for a shared partial tail
  4. tests/common/mod.rs Model-based tests with prefix-derived KV values
  5. --features degenerate-hash CI rerun of the core crate with every hash colliding

Evidence

Every number on this page comes from one of these files, pinned to the commit it was read from.

  1. results/REPORT.md main @ 3ad9f1e
  2. results/candle/REPORT.md main @ 3ad9f1e
  3. results/gpu/README.md main @ 3ad9f1e
  4. README.md main @ 3ad9f1e
  5. docs/design.md main @ 3ad9f1e
  6. results/candle-gpu-paged/README.md feature branch @ d873ebb