All my work / AI infrastructure · by Ravindra Sawant

KVPager

Paged KV cache with copy-on-write forks and prefix reuse (PagedAttention-style).

Python 3.11+ · NumPy 461 lines of core code source on GitHub ↗ CI status

4/4 core requirements 13 tests passing 2/2 benchmark targets

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 page t // page_tokens, slot t % 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 CapacityError is 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

ReqPriRequirement Proven byStatus
FR-01P0Configurable bounded zeroed K/V pool; reject invalid shapes and oversize poolsT02, T04pass
FR-02P0Sequences: append on demand, gather in logical order, capacity error without corruptionT01, T04pass
FR-03P0Release/reuse pages; expose page table, free pages, bytes and internal wasteT02, T03pass
FR-04P0Scaled dot-product attention parity vs contiguous NumPy referenceT05pass
FR-05P1Fork with refcounted shared pages + copy-on-write; exact prefix cache with LRU unpinT03, T02pass
TestWhat it provesResult
T01Append across page boundaries (15/16/17 tokens) vs contiguous arrayspass
T02Release/reallocate zeroes pages; free-list unique; refs = live owners + cache pinspass
T03Fork with partial last page, COW on child append, parent byte-identical, both release orderspass
T04Exhaustion mid planned append leaves length/table/refs untouched; retry after releasepass
T05Paged vs contiguous attention over random sequences, extreme scores, page sizes 1-64pass

Benchmark

Target (hypothesis from the spec)GoalActual
paging admits more sequences than max-length contiguous reservation (same byte budget)> contiguous506 vs 346met
tail waste per unshared sequence < page_tokens< 16 tokensmax 15met
  • paged_admitted = 506
  • contiguous_admitted = 346.5
  • paged_mean_tail_waste_tokens = 7.3
  • contiguous_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   # bench

More 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

Distributed systems

  • Quorum Deterministic Raft consensus simulator with fault injection and an always-on invariant checker
  • Tandem Collaborative text editor on a sequence CRDT: offline edits, any delivery order, always converges
  • Burrow Minimal Linux container runtime in Go: namespaces, pivot_root, cgroup v2 limits

← See all my work: apps, ML/AI and systems