Skip to content
المشاريع

حول

📚 An educational, step-by-step implementation of LLM KV cache reuse — learn prefix caching, chunk keys, storage & eviction, from pure Python to GPU tensors and vLLM integration. Inspired by LMCache.

التعلّم والتعليم

كيف تُقاس هذه الأرقام

ما يمكنك فعله

  • Reuse shared prefixes - Match complete token chunks, stop at the first miss, and compute only the uncached suffix. Prefix-aware keys separate different contexts. - Prefix-cache demo
  • Keep KV beyond GPU memory and process lifetime - Store in memory or on disk; combine tiers with promotion on a slow-tier hit. Entry/byte budgets and leaf-only LRU preserve reachable prefixes. Memory, disk, and tiered backends support shared-thread access. - Disk demo, tiered demo
  • Choose an eviction policy - Prefix-safe LRU is the default; LFU is also available with frequency, recency, and stable-key tie breakers. Memory, disk, and CPU-offload tiers share the same leaf-only mechanism. - Eviction policy experiment
  • Reuse real model tensors - Run Hugging Face models on CPU or CUDA, offload KV to pinned CPU memory, and serialize tensors losslessly or with optional lossy INT8 compression. - Real-model demo, INT8 experiment

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
+١
خلال 15 يومًا
+٣
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

nano-lmcache logo

English | 简体中文

nano-lmcache

Reuse prompt KV, restore it after restart, and see where every cache hit comes from.

nano-lmcache implements the core ideas behind LMCache in small, readable Python modules. It runs from a dependency-free prefix-cache demo to real Hugging Face tensors and an external KV cache for nano-vLLM. The goal is to explain each principle with as little code as practical, backed by runnable examples, correctness tests, and measured trade-offs.

Learning path · Documentation · GPU validation · Benchmarks

What you can do

Capability What works today Try it
Reuse shared prefixes Match complete token chunks, stop at the first miss, and compute only the uncached suffix. Prefix-aware keys separate different contexts. Prefix-cache demo
Keep KV beyond GPU memory and process lifetime Store in memory or on disk; combine tiers with promotion on a slow-tier hit. Entry/byte budgets and leaf-only LRU preserve reachable prefixes. Memory, disk, and tiered backends support shared-thread access. Disk demo, tiered demo
Choose an eviction policy Prefix-safe LRU is the default; LFU is also available with frequency, recency, and stable-key tie breakers. Memory, disk, and CPU-offload tiers share the same leaf-only mechanism. Eviction policy experiment
Reuse real model tensors Run Hugging Face models on CPU or CUDA, offload KV to pinned CPU memory, and serialize tensors losslessly or with optional lossy INT8 compression. Real-model demo, INT8 experiment
Restore a real inference engine Save complete nano-vLLM KV blocks to external L2, load them back into GPU blocks after restart, and reuse resident GPU L1 blocks on later requests. Engine tutorial
Inspect the entire cache path View prefix trees, hit/miss decisions, eviction, promotion, and copy events in standalone HTML. Stream sorted workload JSONL with bounded cache/detail budgets and exact summary statistics; also import trace JSON from other sources. Viewer tutorial, streaming replay, engine trace notes
Explore prefill/decode disaggregation Transfer checksummed KV between two toy-model roles, verify identical tokens without prompt recomputation, and simulate the scheduling trade-off. PD demo — core package only

The engine integration follows this path: local GPU KV first, external KV second, then computation for the remaining prompt. Complete blocks from new computation are saved for future requests.

flowchart LR
    P[Prompt] --> L1{GPU L1}
    L1 -->|hit| G[Compute remaining prompt<br/>and generate]
    L1 -->|miss| L2{nano-lmcache L2<br/>CPU memory / disk}
    L2 -->|hit: restore GPU blocks| G
    L2 -->|miss| G
    G -->|save newly computed KV blocks| L2

Demonstrated results

These are recorded experiments, with their model, hardware, and workload specified below. Each report includes the setup and reproduction commands.

Experiment Result Evidence
Real-engine TTFT — Qwen3-0.6B, RTX 4090, 8,224-token prompt, 8,192 reused tokens 125.0 → 52.4 ms with pinned CPU-memory L2 and empty GPU L1; median of five rounds. TTFT report
Restart recovery — Qwen3-0.6B, RTX 4090 A fresh nano-vLLM process restored five KV blocks from disk with empty L1; both questions produced identical answers across cold and restarted processes. GPU validation record
INT8 storage — first 16-token Qwen3-0.6B KV chunk, Intel Core i7-12700F CPU For both FP16 and BF16, 1,835,008 raw bytes became 1,148,376 serialized bytes including scales and container overhead. 1.598× compression, 37.4% less space. Compression report
Historical heap experiment — 1,024-chunk chains, capacity 8,192, Apple arm64 The earlier heap reduced churn 788 → 208 ms. Current teaching code deliberately uses an O(n) leaf scan instead; these are not current timings. Eviction trade-off
Historical LRU versus LFU comparison — 5,000 shared-prefix requests, capacity 48 In the fixed 2026 seed run, LFU reached 56.16% / 85.21% hit rate on uniform / Zipf versus LRU's 52.70% / 80.68%, with fewer evictions in both cases. Policy comparison

The same TTFT experiment found disk L2 slower than recomputation at every tested size, and short-chain eviction workloads paid extra bookkeeping cost. The reports show where each approach helps and where it costs more.

Start here

Requirements: Python 3.11+ and uv. Run these commands from the repository root:

git clone https://github.com/Dami-wq-k03/nano-lmcache.git
cd nano-lmcache
uv sync --locked
uv run python examples/demo_prefix_cache.py

The demo shows cold misses, shared-prefix hits, and eviction under entry and byte limits. It uses small string payloads, so no model download, PyTorch, or GPU is needed.

The core API is a lookup/store loop. In a uv run python session:

from nano_lmcache.core.prefix_cache import ChunkedPrefixCache

cache = ChunkedPrefixCache(chunk_size=2, namespace="demo-model")
cache.store([10, 20, 30, 40, 50, 60], ["kv-0", "kv-1", "kv-2"])
hit = cache.lookup([10, 20, 30, 40, 70, 80])
print(hit.matched_tokens, hit.values)
# 4 ('kv-0', 'kv-1')

The second prompt reuses its first four tokens; only [70, 80] needs new KV. Strings stand in for computed KV here; the tensor and engine adapters store real tensors through the same storage interface.

Watch reuse survive a restart

Run twice with the same fresh cache directory. Each command starts a new Python process:

uv run python examples/demo_disk_cache.py --dir /tmp/nano-lmcache-readme-kv
uv run python examples/demo_disk_cache.py --dir /tmp/nano-lmcache-readme-kv

The first run reports Reused 0/3 chunks; the second reports Reused 3/3 chunks, recovered from disk.

See each decision in the viewer

uv run python -m nano_lmcache.visualize --scenario partial_prefix_hit \
  --output /tmp/nano-lmcache-trace.html

Open /tmp/nano-lmcache-trace.html in a browser. The HTML includes a prefix tree and event timeline with Next/Previous and playback controls. It needs no server or CDN. It also renders trace JSON from other sources; see engine trace notes.

Move to a real model or engine

Hugging Face KV reuse runs on CPU with the optional hf dependencies:

uv run --extra hf python examples/demo_kv_reuse.py --model Qwen/Qwen3-0.6B

This downloads model weights unless --model points to a local directory. The demo reports reused/computed tokens and compares suffix logits with a full recomputation. Add --device cuda --offload to keep cached KV in pinned CPU memory while the model runs on CUDA.

For nano-vLLM, follow the engine tutorial to run the engine demo: the first question fills the CPU-memory L2, and the second one restores the shared prefix from L2 after a simulated restart with an empty GPU L1. It needs Linux, an NVIDIA GPU, local model weights, and the nanovllm dependency group.

Choose your next step

Goal Guide Requirements
Learn from chunk keys through engine restoration Guided learning path First five steps: core package only
Find a concept, command, or experiment Documentation index Varies by topic
Understand terminology and design Glossary and FAQ, architecture Core package only
Understand the engine adapter nano-vLLM integration design GPU to run; source readable independently
Explore the full vLLM connector API vLLM connector guide vLLM 0.33.0; shared external KV lookup, save/load, and restart reuse
Study prefill/decode handoff PD guide Toy model; core package only

The core package has no runtime dependencies. PyTorch and inference-engine dependencies are optional; installation and test commands live in CONTRIBUTING.md.

Scope and contributing

This is a teaching implementation for understanding LMCache-style systems. External KV reuse works with nano-vLLM and the vLLM 0.33.0 connector. The vLLM path supports shared external lookup, synchronous save/load, and restart reuse; correctness is validated, but a serving speedup is not established. PD disaggregation uses a deterministic toy model and a simulated timeline. Production performance and LMCache API compatibility are outside the project's current goals.

Task status, prerequisites, and follow-ups are maintained in ROADMAP.md. To contribute, choose an open task and follow CONTRIBUTING.md.

Released under the MIT License.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…