Back to all posts

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
  1. 1. Counting Bytes in the KV Cache
  2. 2. Decode Is Memory-Bandwidth Bound
  3. 3. Content-Addressed Prefix Hashing in KVPark
  4. 4. Interactive Exploration
  5. 5. Visual Intuition for Self-Attention
  6. Caveats & Open Questions

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 NN layers, nkvn_{\text{kv}} key-value heads under Grouped-Query Attention (GQA), head dimension dhd_h, context length LL, and bb bytes per stored scalar (b=2b = 2 for FP16, b=1b = 1 for FP8, b=0.5b = 0.5 for INT4). Storing both KK and VV for a single sequence of length LL requires:

MKV(L)=2⋅N⋅nkv⋅dh⋅L⋅bM_{\text{KV}}(L) = 2 \cdot N \cdot n_{\text{kv}} \cdot d_h \cdot L \cdot b

For a 32-layer model with nkv=8n_{\text{kv}} = 8, dh=128d_h = 128, and FP16 precision (b=2b = 2), each additional token consumes 2×32×8×128×2=131,072 bytes=128 KiB2 \times 32 \times 8 \times 128 \times 2 = 131{,}072\text{ bytes} = 128\text{ KiB}. At L=32,768L = 32{,}768 tokens, the KV cache alone reaches 4.0 GiB4.0\text{ GiB}—before counting model weights or activations.

2. Decode Is Memory-Bandwidth Bound

During single-token autoregressive decoding (batch size B=1B = 1), each attention layer performs roughly 4 nq dh L4 \, n_q \, d_h \, L floating-point operations against the cached keys and values while streaming 2 nkv dh L b2 \, n_{\text{kv}} \, d_h \, L \, b bytes from DRAM or unified memory. The resulting attention arithmetic intensity is:

Iattn=FLOPsBytes≈4 nq dh L2 nkv dh L b=2 gbwhere g=nqnkvI_{\text{attn}} = \frac{\text{FLOPs}}{\text{Bytes}} \approx \frac{4 \, n_q \, d_h \, L}{2 \, n_{\text{kv}} \, d_h \, L \, b} = \frac{2 \, g}{b} \quad \text{where } g = \frac{n_q}{n_{\text{kv}}}

Notice that LL cancels out! Even with g=4g = 4 GQA sharing and FP16 (b=2b = 2), attention decoding achieves only Iattn≈4 FLOP/byteI_{\text{attn}} \approx 4\text{ FLOP/byte}—orders of magnitude below the ridge point of modern GPUs and Apple Silicon (~80–250 FLOP/byte).

Roofline diagram comparing prefill compute-bound regime against memory-bandwidth-bound KV-cache decoding across FP16, FP8, and INT4
Figure 1. Schematic roofline model for single-sequence decoding (B=1B=1). Prefill sits near the compute ceiling, whereas decode attention is pinned at Iattn=2g/bI_{\text{attn}} = 2g/b, meaning cache quantization (b:2→1→0.5b: 2 \to 1 \to 0.5) directly multiplies effective attention throughput—provided dequantization stays fused in registers.

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:

kvpark/prefix_hash.pypython
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 digests

In 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 LL, layer count NN, GQA ratio gg, and KV precision, and watch how the footprint and roofline regime move in real time:

Interactive Python · Pyodide WASMKV Cache Explorer

Runs live Python in your browser via Pyodide WebAssembly (~15–30s first load). Best on desktop or fullscreen on mobile.

Open Fullscreen ↗
Interactive KV-cache memory footprint and arithmetic intensity explorer (runs live in your browser via Pyodide WASM).

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:

Attention in Transformers, Visually Explained (3Blue1Brown)

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 (BWNVMe≫bytes/token×tok/sprefill\text{BW}_{\text{NVMe}} \gg \text{bytes/token} \times \text{tok/s}_{\text{prefill}}), and aggressive INT4 value quantization can quietly degrade long-horizon retrieval tasks. Measuring when an optimization stops helping is half the craft.

Comments

0 comments

No comments yet — pull up a chair and leave the first note below.

Leave a comment

Supports inline `code`, *italic*, and **bold**.

Figure preview
Interactive Marimo Notebook

Subscribe to uncrayon.xyz