All my work / AI infrastructure · by Ravindra Sawant
KVPager
Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style).
Verified 2026-11-28; CI re-runs the acceptance tests on every push.
The problem
Autoregressive decoding keeps reading the key/value tensors of every previous token. Contiguous per-sequence allocation over-reserves memory; fixed-size pages with a logical-to-physical table (the idea behind vLLM's PagedAttention) let sequences grow incrementally and share prefixes.
What I found
- Under the same byte budget, paging admitted 506 sequences versus 346 for max-length contiguous reservation, with tail waste always below one page.
- Copy-on-write only triggers when a forked sequence writes into a shared, partially filled page - full pages stay shared.
- All appends are planned and reserved up front, so an out-of-memory error leaves lengths, page tables and refcounts byte-for-byte unchanged.
Architecture
KVCache (sequence manager) ── Seq{id, namespace, length, page_ids[]} ← logical page table
│ plan + reserve all pages first (atomic), then write
▼
PagePool: K,V float arrays [pages, page_tokens, heads, dim] · refs[] · min-heap free list
▲
PrefixCache: OrderedDict[(namespace, chained sha256)] → page (own pin, LRU unpin only)
│
gather(seq) → contiguous [length, heads, dim] → attention(q, K, V) (max-subtracted softmax)
- Position
t→ logical paget // page_tokens, slott % page_tokens. - Append: compute new pages + (1 if the partial last page is shared → COW); reserve all at once; copy valid slots into the COW page; write tokens; commit table/length; decref the original shared page. A
CapacityErroris raised before any mutation. - Fork: child copies the page table and increments every page's refcount.
- Release: decrement each page once; pages reaching zero are zeroed and returned to the free list.
- Prefix reuse: only complete pages, keyed by
(namespace, sha256(prev_digest ‖ namespace ‖ K ‖ V)), verified byte-for-byte on hit (collision check). Never shared across namespaces. - Invariants (
check_invariants): refs[p] = #sequences referencing p + prefix pins; refs==0 ⇔ page in free list; free list unique; page count = ceil(length / page_tokens). - Memory accounting: allocated bytes = used pages × page_bytes (Python overhead excluded); internal waste counts unused slots of allocated pages (shared pages counted once) separately from unused pool capacity.
Requirements → tests
| Req | Pri | Requirement | Proven by | Status |
|---|---|---|---|---|
| FR-01 | P0 | Configurable bounded zeroed K/V pool; reject invalid shapes and oversize pools | T02, T04 | pass |
| FR-02 | P0 | Sequences: append on demand, gather in logical order, capacity error without corruption | T01, T04 | pass |
| FR-03 | P0 | Release/reuse pages; expose page table, free pages, bytes and internal waste | T02, T03 | pass |
| FR-04 | P0 | Scaled dot-product attention parity vs contiguous NumPy reference | T05 | pass |
| FR-05 | P1 | Fork with refcounted shared pages + copy-on-write; exact prefix cache with LRU unpin | T03, T02 | pass |
| Test | What it proves | Result |
|---|---|---|
| T01 | Append across page boundaries (15/16/17 tokens) vs contiguous arrays | pass |
| T02 | Release/reallocate zeroes pages; free-list unique; refs = live owners + cache pins | pass |
| T03 | Fork with partial last page, COW on child append, parent byte-identical, both release orders | pass |
| T04 | Exhaustion mid planned append leaves length/table/refs untouched; retry after release | pass |
| T05 | Paged vs contiguous attention over random sequences, extreme scores, page sizes 1-64 | pass |
Benchmark
| Target (hypothesis from the spec) | Goal | Actual | |
|---|---|---|---|
| paging admits more sequences than max-length contiguous reservation (same byte budget) | > contiguous | 506 vs 346 | met |
| tail waste per unshared sequence < page_tokens | < 16 tokens | max 15 | met |
paged_admitted= 506contiguous_admitted= 346.5paged_mean_tail_waste_tokens= 7.3contiguous_mean_waste_tokens= 839.03
quick run · 2026-11-28T23:56:59+00:00
Design questions
Why cache K and V, not just the output?
Each new query attends to all prior tokens' keys and values; caching them avoids recomputing those projections every decode step. Memory grows with retained context.
Why fixed pages?
Non-contiguous physical allocation and incremental growth reduce over-reservation; only the last page of a sequence can waste slots (< page_tokens).
What does copy-on-write solve?
Forked beams/requests share unchanged prefix pages; only a write into a shared partial page needs a private copy. Refcounts prevent premature reuse.
How do you calculate KV memory?
2 x layers x KV heads x head_dim x tokens x bytes per element, plus allocator padding and metadata. GQA reduces the KV head count.
What changes on GPUs?
Kernels traverse physical pages without materializing a gather, care about layout/coalescing, synchronize allocation and shard across devices. CPU timings do not predict GPU latency.
Limitations
- CPU NumPy only; gather materializes a contiguous copy
- Single layer, single-threaded
Run it
git clone https://github.com/ravirs/kvpager.git && cd kvpager
pip install -r requirements.txt
PYTHONPATH=src python -m pagedkv kv-demo --pages 16 --page-tokens 16 --seed 42 # demo
PYTHONPATH=src python -m pytest -q # test
PYTHONPATH=src python benchmarks/bench.py --quick # benchMore systems I've built from scratch
Storage & data systems
- Strata LSM-tree key-value storage engine: WAL, SSTables with Bloom filters, atomic manifest, compaction
- Tidelog Kafka-style durable partitioned log broker: CRC'd records, offsets, generation-fenced consumer groups
- Floe Iceberg-style table format: immutable Parquet, manifests, snapshots, time travel, compare-and-swap commits
- Flint Spark-style batch engine: lazy lineage, stage planning, shuffles, broadcast and salted skew joins
- Watermark Event-time stream processor: windows, watermarks, lateness, exactly-once checkpoints
- Warden Data governance catalog: explainable grants, row filters, column masks, lineage impact
- SnapshotDB MVCC transaction engine: snapshot isolation, the write-skew anomaly, a serializable mode
AI infrastructure
- Nearline HNSW-style vector search index from scratch, measured against exact search
- Batchwise LLM inference scheduler simulator: static vs continuous vs chunked-prefill batching
- Steadyhand Durable AI agent runtime: allowlisted tools, approvals, budgets, crash recovery, replay
- Toolgate Model Context Protocol gateway: curated tools, signed identity, tenant policy, approvals, audit