← k34ne.net

KV-CACHE LAB

CAUSAL ATTENTION · RoPE · PREFIX CACHE MECHANICS
Prefix Hit0%
Recompute0 tok
FLOPs Saved0%
RegimePREFILL
01 Prompt & Prefix KV-Cache Engine
Interactive Cache Experiments
Click any token to inspect its exact Q, K, V vectors & causal attention row
HIT (reused K,V) MISS (prefill compute) DECODE (1-token step) BUSTED (invalidated suffix)
02 Causal Attention Matrix  softmax(Q·Kᵀ / √d_k + M)
Click any cell (query i, key j) in the lower triangle to inspect the exact dot product qᵢ · kⱼ / √4 and softmax weight.
03 Live Q / K / V Vector Inspector
d_model=8 · d_k=4 · √d_k=2.0
04 KV-Cache Memory Slots & Real-World Scaling
KV Bytes = 2 · L · n_kv · d_head · S · dtype
Active Sequence KV Slots (Per Layer · Click to inspect)
05 Underlying Mechanics
Why causal masking enables prefix reuse—and why 1 early edit busts it

1. Causal Invariance → Prefix Hits

Because the causal mask sets upper-triangle logits to -∞, token i only attends to tokens 0..i. Its hidden state—and therefore its projected kᵢ, vᵢ at every layer—depends strictly on the prefix before it. Appending new tokens never alters earlier K, V entries.

2. Why 1 Early Edit Busts Everything

Change token m and its embedding changes. At Layer 1, every downstream token t > m attends to token m, changing their residual streams—which changes their K, V at Layer 2..L. Thus any edit at index m invalidates the entire cached suffix [m .. N].

3. Prefill (Compute) vs Decode (Bandwidth)

Prefill multiplies a full matrix Q ∈ ℝ^(N×d) against Kᵀ (high arithmetic intensity → compute-bound). Decode multiplies a single row vector q_t ∈ ℝ^(1×d) against the entire cached K every step—streaming gigabytes from HBM for 1 token (memory-bandwidth-bound).