KVPark & the Arithmetic Intensity of Persistent KV Caches
Why autoregressive decoding starves on memory bandwidth, how prefix persistence shifts the bottleneck, and where quantization actually pays off.
Contents
When you run a local large language model across long coding or research sessions, the slowest part of the loop is rarely the matrix multiplication itself—it is moving key and value tensors across memory bandwidth again and again. That observation is what motivated KVPark, a lightweight layer for persisting, hashing, and restoring KV caches across sessions in llama.cpp.
1. Counting Bytes in the KV Cache
Consider a decoder-only Transformer with layers, key-value heads under Grouped-Query Attention (GQA), head dimension , context length , and bytes per stored scalar ( for FP16, for FP8, for INT4). Storing both and for a single sequence of length requires:
For a 32-layer model with , , and FP16 precision (), each additional token consumes . At tokens, the KV cache alone reaches —before counting model weights or activations.
2. Decode Is Memory-Bandwidth Bound
During single-token autoregressive decoding (batch size ), each attention layer performs roughly floating-point operations against the cached keys and values while streaming bytes from DRAM or unified memory. The resulting attention arithmetic intensity is:
Notice that cancels out! Even with GQA sharing and FP16 (), attention decoding achieves only —orders of magnitude below the ridge point of modern GPUs and Apple Silicon (~80–250 FLOP/byte).
3. Content-Addressed Prefix Hashing in KVPark
To reuse a warm prefix across restarts without silently serving stale state, KVPark hashes canonical token ID blocks together with model architecture and quantization metadata. Only an exact prefix match is restored from disk into the KV ring buffer:
from dataclasses import dataclass
import hashlib
import struct
@dataclass(frozen=True)
class CacheKey:
model_fingerprint: str
kv_dtype: str
block_size: int = 256
def compute_prefix_digests(tokens: list[int], key: CacheKey) -> list[str]:
"""Return chained SHA-256 digests for each complete token block."""
digests: list[str] = []
chain = f"{key.model_fingerprint}:{key.kv_dtype}:{key.block_size}".encode()
for start in range(0, len(tokens) - key.block_size + 1, key.block_size):
block = tokens[start : start + key.block_size]
packed = struct.pack(f"<{key.block_size}I", *block)
chain = hashlib.sha256(chain + packed).digest()
digests.append(chain.hex()[:24])
return digestsIn practice, restoring a 16k-token system prompt from NVMe takes under 400 ms compared to 6–12 seconds of fresh prefill on consumer hardware. Just as importantly, keeping explicit failure boundaries matters: whenever the tokenizer, RoPE scaling factor, or KV quantization scheme changes, the hash chain diverges immediately rather than corrupting attention logits.
4. Interactive Exploration
Use the Marimo notebook below to vary context length , layer count , GQA ratio , and KV precision, and watch how the footprint and roofline regime move in real time:
5. Visual Intuition for Self-Attention
If you want a crisp geometric refresher on how query, key, and value projections interact before diving into cache layouts, Grant Sanderson's visual walkthrough remains one of the clearest references online:
Caveats & Open Questions
Persisting KV caches is not a free lunch. Disk-backed restoration only beats recomputation when sequential read throughput exceeds effective prefill speed (), and aggressive INT4 value quantization can quietly degrade long-horizon retrieval tasks. Measuring when an optimization stops helping is half the craft.
Comments
0 commentsNo comments yet — pull up a chair and leave the first note below.
Leave a comment
Supports inline
`code`,*italic*, and**bold**.