Zero Labs
Industry News / AI

Shrinking the KV Cache: An End-to-End Guide to KV Compression, with Deep Dives into TurboQuant and…

Source · Towards AI By Aadishagrawal

From the publisher’s feed, collected in the ZeroLabs newsroom.

Shrinking the KV Cache: An End-to-End Guide to KV Compression, with Deep Dives into TurboQuant and TriAttentionWhy long-context LLMs run out of memory, the six families of fixes, and the math behind two of the most interesting new techniques, explained step by step.1. Motivation: the memory wall behind long contextSuppose you load Llama-3.1–8B in BF16 onto a 24 GB GPU. The weights take about 16 GB, so there seems to be plenty of room. Then a user pastes a long document, or a reasoning model thinks for 30,000 tokens, and the server crashes with an out-of-memory error.The culprit usually isn’t the model. It’s the KV cache.What the KV cache isTo generate each new token, attention compares the new token’s query with the keys of every previous token, then mixes their values:Generating token t new token ──► compute q_t, k_t, v_t │ ├──► append k_t, v_t to the cache ▼ attention = softmax( q_t · [k_1, k_2, …, k_t] / √d ) · [v_1, v_2, …, v_t] ▲ ▲ └──── every past key and value, at every stepRecomputing all past keys and values at every step would be wasteful, so models store them. That store is the KV cache. It trades compute for memory, and the memory grows with every token.How big it getsKV cache bytes = 2 × L × H_kv × d_head × T × B × bytes_per_element 2 keys and values L number of layers H_kv number of KV heads d_head dimension per head T sequence length (tokens) B batch size (sequences)For Llama-3.1–8B (32 layers, 8 KV heads, head dimension 128, BF16 = 2 bytes):2 × 32 × 8 × 128 × 2 = 131,072 bytes = 128 KiB per tokenContext KV cache 4K tokens 0.5 GiB 32K tokens 4 GiB 128K tokens 16 GiB ← as large as the model weights 32K tokens × 8 seqs 32 GiB ← more than the GPUWhy this matters in practiceLong reasoning. Reasoning models produce chains of thought tens of thousands of tokens long, and the cache grows during generation, not only at the prompt.Agents and multi-turn chat. Context accumulates across tool calls and turns. In one deployment described in the TriAttention paper, an agent’s first prompt alone exceeded 15K tokens.Long documents and RAG. Retrieved passages and pasted files go straight into the cache.Serving cost. The number of requests a GPU can serve at once is often limited by KV memory, not by compute. A smaller cache means larger batches and a lower cost per token.Speed. Decoding is usually limited by memory bandwidth: each new token must read the entire cache. A smaller cache is a faster cache. That’s why compression papers report throughput gains, not just memory savings.2. KV compression at a glanceEvery factor in the size formula is a lever, and each family of techniques pulls a different one:KV bytes = 2 × L × H_kv × d_head × T × B × bytes_per_element │ │ │ │ │ │ │ │ │ └─ Quantization: fewer bits per number │ │ │ └─ Eviction: fewer tokens kept │ │ └─ Low-rank: fewer dimensions per token │ └─ Architecture: fewer KV heads (MQA, GQA, MLA) └─ Cross-layer: fewer layers with their own cacheQuery-aware loading: same bytes stored, fewer bytes read per stepThree questions help classify any method:What does it throw away? Whole tokens, precision, dimensions, heads, or layers.Does it need training? Architectural changes must be built into the model. Most other methods work on an existing model, sometimes with a small offline calibration step.Is the loss permanent? An evicted token is gone. A quantized token is still there, just blurrier.The families also stack. A GQA model can evict unimportant tokens and quantize the ones it keeps. The savings multiply, and so can the errors.3. The landscape: six buckets of KV compressionBucket 1: Architectural changes (shrink H_kv or the per-token size)These change the attention design itself, so they must be introduced during pretraining or with additional training.Multi-Query Attention (MQA): all query heads share a single key head and a single value head.Grouped-Query Attention (GQA): query heads are split into groups, and each group shares one KV head. Llama-3.1–8B has 32 query heads but only 8 KV heads, a 4x smaller cache than standard multi-head attention. GQA is the default in many current open models.Multi-head Latent Attention (MLA): introduced in DeepSeek-V2. Each token is compressed into a small latent vector, and only that latent (plus a small key part that carries position information) is cached. Full keys and values are reconstructed from it, and the reconstruction can be folded into the attention projections at inference. DeepSeek-V2 reports a 93.3% smaller KV cache than DeepSeek 67B.Sliding-window attention: some layers only look at the last W tokens, so their cache never exceeds W entries. Many models mix local and global layers.Trade-off: large, permanent savings, but you can’t apply them to a model that’s already trained.Bucket 2: Token eviction and selection (shrink T)Keep a fixed budget of tokens and delete the rest. No retraining is needed. The hard part is predicting which cached tokens future queries will need, because eviction is usually permanent.StreamingLLM: keep a few initial tokens plus a sliding window of recent ones. The initial tokens act as attention sinks, receiving large attention regardless of content, and removing them destabilizes the model.H2O (Heavy-Hitter Oracle): add up the attention each token receives over time and keep the “heavy hitters” plus recent tokens.Scissorhands: tokens that were important in the past tend to stay important (the persistence-of-importance hypothesis).SnapKV: queries at the end of the prompt vote for important prompt positions in each head. It mainly compresses the prompt.PyramidKV: gives lower layers larger budgets and deeper layers smaller ones, since attention becomes more focused with depth.Ada-KV: gives different heads different budgets.R-KV: built for reasoning models. It combines attention-based importance with redundancy detection, since long chains of thought repeat themselves.TriAttention: scores tokens using stable pre-RoPE query and key centers instead of recent attention. Deep dive in section 5.Trade-off: big savings on long sequences, but a token evicted by mistake can’t come back.Bucket 3: Quantization (shrink bytes per element)Keep every token, but store each number with fewer bits. Going from 16 bits to 4 bits is a nominal 4x reduction, minus metadata such as scales.The enemy is outliers: a few huge values force the quantizer to stretch its levels, crushing the small values. Keys in LLMs tend to have outlier channels (the same dimensions are large across tokens).KIVI: tuning-free 2-bit quantization. Keys are quantized per channel and values per token, matching their outlier patterns. The most recent tokens stay in full precision.KVQuant: quantizes keys per channel and before RoPE, uses non-uniform levels learned from calibration data, and keeps a few outliers in higher precision.QJL: randomly projects each key and stores only the sign of each projected coordinate (1 bit), which gives an unbiased estimate of query-key dot products.PolarQuant: randomly preconditions vectors, converts them to polar coordinates, and quantizes the angles, which follow a predictable distribution.TurboQuant: random rotation, a precomputed optimal codebook, and an optional 1-bit QJL correction for unbiased dot products. Deep dive in section 4.Trade-off: no token is lost, but quality drops at very low bit widths, and the quantize/dequantize steps cost compute.Bucket 4: Low-rank projection (shrink d_head)Keys and values often live close to a lower-dimensional subspace.Palu: factorizes the key and value projection weights into low-rank pieces, caches the smaller intermediate vector, and reconstructs full keys and values on the fly. MLA can be seen as the trained, architectural version of this idea.Trade-off: fewer stored dimensions, more compute during attention, and accuracy drops with aggressive rank reduction.Bucket 5: Cross-layer sharing and merging (shrink L)Neighboring layers often produce similar keys and values.Cross-Layer Attention (CLA): adjacent layers share one KV cache by design (requires training).MiniCache: training-free. Merges the caches of adjacent layers by interpolating their directions and storing magnitudes separately, while keeping tokens that differ too much to merge.Trade-off: layer-specific details are lost where layers aren’t truly similar.Bucket 6: Query-aware loading and system techniques (shrink bytes read)Keep the full cache, but avoid reading all of it at each step.Quest: splits the cache into pages, estimates which pages can hold high-attention keys for the current query, and loads only those. Nothing is deleted, so tokens can come back into use.Offloading: keeps part of the cache in CPU memory and moves it to the GPU on demand. Bandwidth becomes the bottleneck.PagedAttention (vLLM): stores the cache in fixed-size blocks to avoid fragmentation and share prefixes across requests. It’s memory management, not compression, but it’s the base most compression methods plug into.Trade-off: saves bandwidth and time, not capacity (unless combined with offloading).Cheat sheetBucket What shrinks Training? Examples───────────── ─────────────── ──────────────── ────────────────────────────────Architectural KV heads / size Yes MQA, GQA, MLA, sliding windowEviction Tokens (T) No StreamingLLM, H2O, SnapKV, PyramidKV, R-KV, TriAttentionQuantization Bits per number No (some calib.) KIVI, KVQuant, QJL, PolarQuant, TurboQuantLow-rank Dims per token Post-training PaluCross-layer Layers (L) CLA yes, MC no CLA, MiniCacheQuery-aware Bytes read No Quest, offloadingNow for the two deep dives: TurboQuant (how to store each kept number in very few bits) and TriAttention (how to decide which tokens to keep).4. Deep dive: TurboQuantTurboQuant (Zandieh, Daliri, Hadian, and Mirrokni, 2025) is a vector quantization method. Applied to LLMs, it quantizes the KV cache, not the model weights. Its standout property is that it’s data-oblivious: no calibration, no per-model tuning, and almost no setup time, so it can quantize each new token as it’s generated.4.1 The problem: outliers ruin quantizationQuantizing with b bits means snapping each number to one of 2^b levels. Try 2 bits (4 levels) on a spiky vector:x = [8.0, 0.1, -0.1]Uniform 2-bit levels covering [-8, 8]: -6 -2 +2 +6 8.0 → +6 0.1 → +2 (20x too large)-0.1 → -2 (20x too large)The single outlier forces wide spacing, so the small values are destroyed. Real key vectors have exactly this kind of spike.TurboQuant’s fix has three ideas:Rotate randomly, so that any input, spiky or not, ends up with coordinates of a predictable size and distribution.Use one precomputed optimal codebook for that known distribution, so no per-vector scales or calibration are needed.Correct the dot-product bias with a 1-bit QJL sketch of the leftover error, because attention depends on dot products.4.2 The full pipelineOFFLINE (once per head dimension d and bit width b) ├─ 1. Draw a random rotation Π (d × d) QR decomposition of a Gaussian matrix ├─ 2. Build the codebook c_1 … c_(2^b) Lloyd-Max on the coordinate distribution └─ 3. Draw a Gaussian matrix S (d × d) inner-product variant onlyONLINE (every new key or value vector x) x │ 1. n = ‖x‖, u = x / n store the norm n ▼ u │ 2. y = Π · u spread the energy ▼ y │ 3. idx_j = index of nearest centroid to y_j ▼ idx ──► store (idx, n) ◄── TurboQuant-MSE stops here │ │ Inner-product variant (idx uses b − 1 bits): │ 4. û = Πᵀ · c[idx] reconstruct │ 5. r = u − û, γ = ‖r‖ residual and its length │ 6. z = sign(S · r) 1 bit per coordinate ▼ store (idx, z, γ, n) ◄── TurboQuant-prodATTENTION (a query q arrives) q′ = Π · q, q″ = S · q once per query, reused for every key q·x ≈ n · ( ⟨q′, c[idx]⟩ + γ · √(π/2) / d · ⟨q″, z⟩ )The rest of this section explains each step with an example.4.3 Part A: minimizing reconstruction error (TurboQuant-MSE)Step 1: NormalizeTake an illustrative key vector, say for the token “caleb” (a made-up example, not a real embedding):x = [8.0, 0.1, -0.1]‖x‖ = √(8.0² + 0.1² + 0.1²) = 8.00125u = x / ‖x‖ = [0.99984, 0.01250, -0.01250] ← unit length, still spikyThe norm 8.00125 is stored separately (one 16-bit number per vector) so the vector can be rescaled later.Step 2: Rotate to spread the energyMultiply by an orthogonal (rotation) matrix. Here is a fixed 3×3 one for illustration; TurboQuant draws a random one: ┌ 0.577 0.577 0.577 ┐ rows are 1/√3, 1/√2, and 1/√6 multiplesΠ = │ 0.707 -0.707 0.000 │ └ 0.408 0.408 -0.816 ┘y = Π · u = [0.57726, 0.69816, 0.42349]The energy that was piled into one coordinate is now spread across all three.Doesn’t this just turn numbers we understand into numbers we don’t? No:Nothing is lost. Rotations preserve length (‖y‖ = ‖u‖ = 1) and are perfectly reversible (u = Πᵀ · y). Only the later rounding step loses information.We go from unknown to known. Before rotation, coordinates can be anything: spikes, flat, anything in between. After a random rotation, the statistics of each coordinate are known in advance, whatever the input was.Why the rotated coordinates are predictableEach rotated coordinate is a weighted sum of all input coordinates, with random weights:y_i = Π_i1·u_1 + Π_i2·u_2 + … + Π_id·u_dA sum of many small random contributions tends toward a bell curve. That’s the intuition behind the central limit theorem, and here it’s made exact by geometry: a randomly rotated unit vector is a uniformly random point on the sphere, and each coordinate of such a point follows a known (scaled Beta) distribution:mean of y_i = 0variance of y_i = 1/dtypical size |y_i| ≈ 1/√d (exact RMS, since Σ y_i² = 1)d = 3 y_i ~ Uniform[-1, 1] flatd = 16 bell-shaped Beta, std 0.25d = 128 ≈ Normal(0, 1/128), std ≈ 0.088 narrow, Gaussian-likeThe 0.577 = 1/√3 in our example is the typical magnitude of a coordinate in 3 dimensions (its root-mean-square). The mean is 0, and the variance is 1/3. As d grows, the distribution gets narrower and closer to a Gaussian.This holds for any input direction, whether the text was English, code, or HTML. It’s a property of the random rotation, not of the data. That’s what makes a single precomputed codebook possible.A second, subtler benefit: in high dimensions, different rotated coordinates become nearly independent. So each coordinate can be quantized on its own with a 1-D quantizer, and that’s still close to optimal for the whole vector.Step 3: Quantize with a precomputed Lloyd-Max codebookSince the coordinate distribution is known, the best possible levels (centroids) can be computed once. Lloyd-Max is 1-D k-means on a continuous distribution:repeat until stable: 1. boundaries = midpoints between neighboring centroids 2. centroids = average of the distribution inside each cellThis runs once per (d, b) pair, and the result is stored in a lookup table. A few published high-dimensional codebooks:1 bit: ±0.798/√d d = 128 → ±0.07052 bits: ±0.453/√d, ±1.51/√d d = 128 → ±0.0400, ±0.1335For our 3-D toy, the coordinates are uniform on [-1, 1], so the optimal 2-bit codebook is evenly spaced:codebook: c_0 = -0.75 c_1 = -0.25 c_2 = 0.25 c_3 = 0.75y = [0.57726, 0.69816, 0.42349]nearest = 0.75 0.75 0.25idx = 3 3 2 → stored as bits 11 11 10Dequantize and measure the errorTo reconstruct: look up the centroids, rotate back, and rescale:ŷ = [0.75, 0.75, 0.25]û = Πᵀ · ŷ = [1.0654, 0.0047, 0.2289]x̂ = 8.00125 · û = [8.525, 0.038, 1.831] original: [8.0, 0.1, -0.1]squared error (unit vector): ‖y − ŷ‖² = 0.0626Three dimensions at 2 bits is very crude, but notice the error is spread evenly rather than wiping out the small coordinates. Mean squared error (MSE) measures this:MSE(x, x̂) = (1/d) · Σ_i (x_i − x̂_i)²The paper reports its distortion as the total squared error for a unit vector, ‖u − û‖² (d times the per-coordinate MSE). In high dimensions:bits per coordinate 1 2 3 4expected ‖u − û‖² 0.36 0.117 0.03 0.009The error drops about 4x for every extra bit. The paper proves this is within a factor of about 2.7 of the best that any quantizer can achieve at the same bit width.What it savesFor a head dimension of 128:BF16: 128 × 16 bits = 2048 bitsTurboQuant 2-bit: 128 × 2 bits + 16-bit norm = 272 bits ≈ 7.5x smallerTurboQuant 3-bit: 128 × 3 bits + 16-bit norm = 400 bits ≈ 5.1x smaller4.4 Part B: keeping attention scores unbiased (TurboQuant-prod)Attention doesn’t use keys directly. It uses dot products q·k. A quantizer can have a small MSE and still give systematically wrong dot products.Where the bias comes fromRounding to the nearest centroid shrinks or stretches vectors in a consistent direction. At 1 bit, the TurboQuant paper shows that the MSE-optimal quantizer gives, on average:E[ q · x̂ ] = (2/π) · (q · x) ≈ 0.64 · (q · x)Every attention logit shrinks by about 36% on average. That makes the softmax flatter, so the model attends less sharply. The bias fades at higher bit widths but doesn’t vanish. It comes from the deterministic rounding, not simply from the codebook being precomputed.The fix: spend one bit on the residual with QJLFor a target of b bits per coordinate:┌──────── b − 1 bits ────────┐┌─ 1 bit ─┐MSE codebook index (Part A) QJL sign of the residuale.g. b = 3: 2 bits MSE + 1 bit QJL, for each of the d coordinatesThe dimension stays d; only the bits are split. The steps are:1. Quantize u with TurboQuant-MSE at b − 1 bits → û2. Residual r = u − û (small, since MSE is small)3. γ = ‖r‖, and z = sign(S · r) (S: random Gaussian d × d matrix)4. Store idx, z, γ (one extra 16-bit number), and nWhy random signs can estimate a dot productEach row s of S defines a random hyperplane, and sign(s · r) records which side of it r falls on. Many random hyperplanes together reveal r’s direction. For a Gaussian row s and any query q:E[ (s · q) · sign(s · r) ] = √(2/π) · (q · r) / ‖r‖So averaging over all d rows and correcting the constant gives an unbiased estimate:q · r ≈ γ · √(π/2) / d · ⟨S·q, z⟩Putting it togetherq · u = q · û + q · r ≈ q · û + γ · √(π/2)/d · ⟨S·q, z⟩ └ MSE part ┘ └──── QJL correction ────┘The MSE stage makes the residual small, and QJL estimates its contribution without bias. So the combined estimate is unbiased: correct on average over the random rotation and projection. Individual estimates still have some variance, which shrinks as the bit width grows.4.5 Where TurboQuant sits in inferenceNew token: quantize its key (and value) right after it’s computed and store the compact form.Attention scores: since Π is orthogonal, ⟨q, Πᵀ·c[idx]⟩ = ⟨Π·q, c[idx]⟩. Rotate the query once instead of un-rotating every cached key. The same trick applies to S·q for the QJL term.Attention output: values can be combined in the rotated space too, since Σ a_i·n_i·Πᵀ·c[idx_i] = Πᵀ·(Σ a_i·n_i·c[idx_i]). Rotate back once at the end.Which variant where: a natural rule of thumb is the inner-product variant for keys (they feed dot products) and the MSE variant for values (they are averaged, so reconstruction matters). That’s a design heuristic, not a requirement from the paper.4.6 ResultsFrom the TurboQuant paper:Needle-in-a-haystack (Llama-3.1–8B-Instruct, 4K to 104K tokens, 4x compression): a recall score of 0.997, identical to full precision. SnapKV scored 0.858, PyramidKV 0.895, KIVI 0.981, and PolarQuant 0.995.LongBench: quality matching full precision at 3.5 bits per channel, with only marginal degradation at 2.5 bits, while compressing the cache by at least 4.5x.Fractional bits come from treating outlier channels separately. For example, 2.5 bits = 32 outlier channels at 3 bits plus 96 normal channels at 2 bits: (32·3 + 96·2) / 128 = 2.5.Vector search: higher recall than product quantization, with near-zero indexing time (about 0.001 seconds versus minutes), because there is nothing to train.4.7 TurboQuant in one tableComponent Why it's there──────────────────────── ─────────────────────────────────────────────────Normalize + store norm Quantize the direction; keep the scale exactlyRandom rotation Π Makes coordinates predictable for any inputLloyd-Max codebook Optimal levels for that known distribution, offlinePer-coordinate rounding Near-independence makes 1-D quantization near-optimal1-bit QJL on residual Removes dot-product bias at the cost of one bitRotate the query once Avoids de-rotating every cached keyLimitations: extra compute for the rotation and projection, per-vector metadata (norms), quality loss at very low bit widths, and results that are measured on specific models and benchmarks.5. Deep dive: TriAttentionTriAttention (Mao, Lin, Huang, et al., 2026, Efficient Long Reasoning with Trigonometric KV Compression) is a training-free token eviction method built for long reasoning, where the cache grows throughout generation. Where TurboQuant asks how many bits each token needs, TriAttention asks which tokens are worth keeping at all.5.1 First, what TriAttention does not changeThis is a common point of confusion, so it’s worth stating up front. RoPE and attention are not modified. Every decoding step runs exactly as usual: compute q, k, and v, apply RoPE, append to the cache, and run standard attention (FlashAttention or similar) over whatever is in the cache.TriAttention is a periodic side step that decides which cache entries to delete. Its “pre-RoPE” math is used only to rank keys; the scores are thrown away after each pruning round. NVIDIA’s TensorRT-LLM guide describes it the same way: a pure compression method, with decode running the model’s standard attention over the compacted cache.5.2 Background: RoPE as spinning clock handsRotary Position Embedding (RoPE) splits each d-dimensional query and key into d/2 pairs of numbers. Think of each pair as a clock hand (a 2-D vector, or one complex number). At position p, RoPE spins hand f by an angle ω_f·p, and every hand spins at a different speed:ω_f = θ^(−2f/d), θ = 10000 typicallyband f = 0 fastest hand (completes a turn every ~6 tokens)…band f = d/2−1 slowest hand (barely moves over thousands of tokens)The vectors before spinning are pre-RoPE; after spinning, they are post-RoPE. When a query at position p_q meets a key at position p_k, only their distance Δ = p_q − p_k matters, and the attention logit becomes:logit(q, k) = Σ_f ‖q_f‖ · ‖k_f‖ · cos(ω_f·Δ + φ_f)q_f, k_f pre-RoPE components in band f (complex numbers)φ_f arg(q_f) − arg(k_f), their angle difference5.3 The problem: post-RoPE queries keep spinningMost eviction methods (H2O, SnapKV, R-KV) score keys by the attention they get from recent post-RoPE queries. But post-RoPE queries keep rotating as positions advance, so only the very latest queries reflect where future queries will point. Older queries are effectively pointing in stale directions.The usable observation window is tiny. The TriAttention paper cites prior work in which accuracy peaked with a window of about 25 queries and got worse with larger windows. With so few observers, a key that’s quiet during the window but crucial later (common for retrieval-style heads, and fatal in long reasoning) gets evicted forever.Post-RoPE view (what other methods observe)position: 1 ──────────────────────────────── t−25 ── t queries: rotated far away (stale) │ usable │ └─ ~25 ──┘5.4 The discovery: pre-RoPE queries and keys clusterLook before RoPE and something striking appears: in most heads, query vectors (and key vectors) cluster tightly around a fixed, non-zero center, and that center barely changes across positions or input content.The paper measures this with the Mean Resultant Length:R = ‖E[q]‖ / E[‖q‖] (length of the average ÷ average length)Tight cluster: q = [1, 0], [0.9, 0.1], [1, −0.1] ‖mean‖ = 0.9667, mean ‖q‖ = 0.9702 → R = 0.996Spread out: q = [1, 0], [−1, 0], [0, 1], [0, −1] ‖mean‖ = 0, mean ‖q‖ = 1 → R = 0R near 1 means all vectors point roughly the same way. In Qwen3–8B, roughly 90% of heads have R above 0.95, with nearly identical values on math, code, and chat data. That suggests it’s a property of the model, not the input. The paper also finds it in other architectures it tested: Qwen2.5 and Llama3 variants (GQA), and an MLA model (GLM-4.7-Flash, where 96.6% of heads exceed R = 0.95). That’s evidence across tested models, not a guarantee for every model.5.5 From centers to a trigonometric seriesIf queries and keys barely move, replace them with their centers q̄_f and k̄_f. Then everything in the logit is constant except the distance:logit(Δ) ≈ Σ_f ‖q̄_f‖ · ‖k̄_f‖ · cos(ω_f·Δ + φ̄_f) = Σ_f [ a_f · cos(ω_f·Δ) + b_f · sin(ω_f·Δ) ]That’s a trigonometric series in Δ (hence the name). The centers set the coefficients, and the coefficients draw an attention-versus-distance curve for each head. Some heads prefer nearby tokens, others prefer far ones (such as attention sinks at the start).A one-band example: let ω = 0.1, ‖q̄‖·‖k̄‖ = 1, and φ̄ = −2.logit(Δ) ≈ cos(0.1·Δ − 2) peaks when 0.1·Δ = 2 → Δ = 20attention ▲ ╭─╮ │ ╱ ╲ │ ╱ ╲ │ ───╯ ╰───── └───────────────────► distance Δ 20This head “likes” keys about 20 tokens back. A single band repeats periodically, but real heads add up many bands with geometrically spaced speeds, giving rich, non-repeating preferences over practical context lengths.Does this prediction match reality? On Qwen3–8B the predicted curve correlates with real attention logits (Pearson r = 0.72 for the paper’s example head), and mean correlations exceed 0.5 across the Qwen3, Qwen2.5, and Llama3 models tested.5.6 Scoring a cached keyCached keys are known exactly, so TriAttention uses each key’s real pre-RoPE components. Future queries aren’t known, so it substitutes the query center, measured offline.Recovering pre-RoPE keysThe cache stores post-RoPE keys. Undoing the rotation is cheap and exact:stored: k̃_f = k_f · e^(i·ω_f·p_k)recovered: k_f = k̃_f · e^(−i·ω_f·p_k) (‖k_f‖ is unchanged)Score 1: distance preference (trigonometric score)S_trig(k, Δ) = Σ_f ‖E[q_f]‖ · ‖k_f‖ · cos(ω_f·Δ + φ_f)φ_f = arg(E[q_f]) − arg(k_f) angle between the query center and this keyA worked example with the one-band head above. Assume both keys share the angle that gives φ = −2:Key A: distance 20, ‖k‖ = 1.0 → S_trig = 1.0 · cos(0.1·20 − 2) = 1.0 · cos(0) = +1.00Key B: distance 100, ‖k‖ = 1.5 → S_trig = 1.5 · cos(0.1·100 − 2) = 1.5 · cos(8) = −0.22→ keep A, evict B, even though B has the larger normScore 2: magnitude (norm score), weighted by concentrationThe trigonometric score assumes queries sit exactly at their center. Where they wander more, a norm-based signal helps:S_norm(k) = Σ_f (1 − R_f) · E[‖q_f‖] · ‖k_f‖Tight cluster (R_f ≈ 1): 1 − R_f ≈ 0 → S_trig dominates (distance decides)Loose cluster (R_f ≪ 1): 1 − R_f large → S_norm matters more (magnitude decides)The weighting is per frequency band, so it adapts automatically. The norm term also catches keys with tiny norms, which get little attention whatever their distance.Hedging over the futureA key will be queried from many future positions, not just the current one. So the combined score S = S_trig + S_norm is averaged over geometrically spaced future offsets:S̃(k) = (1/|D|) · Σ_{δ ∈ D} S(k, Δ + δ)D = {1, 2, 4, 8, …, 2^16} (17 offsets)Geometric spacing samples near distances densely and far ones sparsely. In the paper’s ablation, it beat linear spacing by a wide margin (45.8% versus 28.7% on AIME24).GQA: several query heads per keyIn GQA, one KV head serves G query heads, each with its own calibration statistics and its own score scale. TriAttention scores each key once per query head, z-score normalizes each head’s scores, then takes the maximum:Ŝ_g(k) = ( S̃_g(k) − μ_g ) / σ_g normalize within query head gS_final(k) = max over g of Ŝ_g(k) keep if ANY head wants it5.7 The full pipelinePhase 0: The idea in one sentenceInstead of asking recent queries which keys they liked, ask which keys a typical query is predicted to like at many future distances, using centers measured once offline.Phase 1: Offline calibration (once per model)calibration text (e.g. ~50K–1M tokens) │ ▼run the model, capture pre-RoPE queries, per layer and per head │ ▼for each band f: E[q_f] query center (complex number) E[‖q_f‖] expected query norm R_f concentration = ‖E[q_f]‖ / E[‖q_f‖] │ ▼save to a calibration .pt file ──► reused for every requestCalibration is robust. The paper found stable accuracy from 50K to 960K calibration tokens, and comparable accuracy whether it calibrated on reasoning text, code, or even raw HTML from a web homepage.Phase 2: Normal inference (unchanged)prompt ──► prefill ──► KV cache (post-RoPE keys, values) │ ┌────────────▼─────────────┐ │ decode loop, per token: │ │ q,k,v → RoPE(q,k) → │ │ append k,v → standard │ │ attention over the cache │ └────────────┬─────────────┘ │ every β = 128 generated tokens ▼ TriAttention pruning roundPhase 3: A pruning roundTriggered when a 128-token window completes and the cache exceeds the budget B (2,048 tokens by default). For each layer and KV head:1. Undo RoPE on cached keys k_f = k̃_f · e^(−i·ω_f·p_k)2. Distance to the current position Δ = p_now − p_k3. Score against each query head g S_trig + S_norm, averaged over 17 offsets4. Combine across the G query heads z-normalize, then max5. Keep the top-B keys, evict the rest physically compact the cachePhase 4: Resume decodingThe model continues with the smaller cache. Kept keys still carry the RoPE rotation from their original positions, and new tokens keep counting from the true sequence position, so relative distances stay correct.Cache size over timeWith B = 2,048 and β = 128:generated: 128 256 … 2048 2176 2304 2432cache: 128 256 … 2048 2176 → 2048 2176 → 2048 2176 → 2048 ▲ prune ▲ prune ▲ prunepeak ≈ B + β = 2,176 tokens, no matter how long generation runsFor Qwen3–8B (36 layers, 8 KV heads, head dimension 128, BF16), that’s 144 KiB per token: 4.5 GiB for a 32K-token trace with full attention, versus about 288 MiB at a 2,048-token budget.Why each piece is thereComponent Role───────────────────────────── ──────────────────────────────────────────────Pre-RoPE space Removes position spin, so centers are stableCalibrated query centers Stand in for future queries; no window neededTrigonometric series Turns centers into an attention-vs-distance curveNorm term weighted by (1 − R) Covers heads and bands with looser clustersMulti-offset averaging Hedges over when a key will be neededZ-normalize then max (GQA) Keeps any key that any query head needsWindowed pruning (β = 128) Spreads the scoring cost over many tokens5.8 Running it in practicevLLM plugin (official repo): activates automatically once installed. Main settings are the KV budget (default 2,048), the trigger interval (default 128), a window of recent tokens that’s always kept (default 128), and the path to the calibration file. Prefix caching must be disabled, because cached prefixes would point at compacted entries. For chat, the authors suggest a larger budget (around 12K) and smaller prefill chunks so a long prompt can’t overshoot the budget before compression runs.SGLang is supported as well, and community ports exist for llama.cpp and Apple Silicon (MLX).TensorRT-LLM (official upstream integration): loads the calibration file produced by the official tool, preserves the prompt and scores only generated tokens, and offers eviction modes union (a shared kept set, matching the paper's base setting), per_head, and per_layer_perhead. At the time of writing it targets Blackwell-class GPUs (SM100/SM103) with the V2 KV-cache manager, and its support matrix excludes MHA and MLA models.5.9 ResultsFrom the paper (Qwen3–8B unless noted):AIME25, 32K-token generation: matches full attention accuracy (40.8% versus 40.8%) with 2.5x higher throughput at a 3,072-token budget, or 10.7x less KV memory.MATH-500: 68.4% versus 69.6% for full attention with only 1,024 cached tokens, at 6.3x the throughput.Same budget (2,048), head-to-head: 32.9% on AIME25 versus 17.5% for R-KV and 20.0% for SnapKV; 42.1% on AIME24 versus 25.4% for R-KV.Sometimes above full attention: at a 4,096-token budget on AIME25 it scored 43.3%, above full attention’s 40.8%. The authors read this as a sign that a full cache contains redundancy; it’s not a general rule that eviction beats full attention.Real deployment: Qwen3–32B (INT4) on a single 24 GB RTX 4090 running a multi-turn agent. Full attention ran out of memory, and TriAttention completed the task.Limitations: eviction is permanent, and at the deepest recursion levels of the paper’s memory benchmark, accuracy fell behind full attention. The method relies on RoPE structure and per-model calibration. Evaluation centers on math reasoning (plus LongBench and RULER), and the authors list coding, agentic tasks, and dedicated kernels as future work.6. Conclusion and further pointersTurboQuant and TriAttention side by side TurboQuant TriAttention─────────────────── ────────────────────────────── ──────────────────────────────Bucket Quantization EvictionQuestion answered How many bits per number? Which tokens to keep?What is lost Precision (every token kept) Whole tokens (permanently)Setup None (data-oblivious) One-time calibration per modelCore trick Random rotation → known Pre-RoPE Q/K centers → distribution → fixed codebook predicted distance preferenceMath tools Beta/Gaussian, Lloyd-Max, QJL RoPE, trigonometric series, RWhen it runs Every new token Every 128 generated tokensTypical gain ~4.5x+ at 2.5–3.5 bits up to 10.7x memory, 2.5x speedBest for Keeping all context, cheaply Very long generationKey takeawaysThe KV cache, not the weights, is often what limits long context. It grows with every token, and every new token has to read all of it.There are six levers. Heads (architecture), tokens (eviction), bits (quantization), dimensions (low-rank), layers (cross-layer), and bytes read (query-aware loading).TurboQuant shows the power of randomization. A random rotation turns any input into a predictable distribution, so one precomputed codebook works everywhere, and one extra bit of QJL fixes the dot-product bias.TriAttention shows the power of looking in the right space. Post-RoPE, queries spin and look unpredictable. Pre-RoPE, they sit still, so a key’s future importance can be predicted from its distance and norm.They’re complementary. One decides which tokens stay; the other decides how many bits each kept token uses. A community llama.cpp port of TriAttention reports about 6.8x KV reduction when combined with TurboQuant.How to chooseTraining a new model: build in GQA or MLA. It’s the largest permanent win.Serving an existing model with long prompts: quantization (KIVI, TurboQuant) or prompt-focused eviction (SnapKV, PyramidKV).Long reasoning or agent traces: decode-time eviction designed for growth during generation (R-KV, TriAttention).When every token might matter (retrieval, exact recall, legal or code context): prefer quantization or query-aware loading, which keep everything.Maximum savings: stack methods, such as eviction plus quantization on a GQA model.Practical checklist before shippingMeasure on your own workload. All reported numbers are for specific models, budgets, and benchmarks. Errors from stacked methods compound.Size the budget for the task. Chat and agents accumulate history and need larger budgets than single-shot math problems.Watch for interactions with serving features. For example, TriAttention’s vLLM plugin requires prefix caching to be disabled, and large prefill chunks can overshoot the budget before compression runs.Check hardware and architecture support. Integrations differ in which GPUs and attention types (GQA, MHA, MLA) they support.Track tail failures, not only averages. Eviction failures show up on the hardest, longest, most recall-heavy requests.Open questions worth watchingCan evicted tokens be recovered cheaply, for example by offloading them instead of deleting them?How do these ideas transfer to models without RoPE, or to hybrid attention and state-space models?Dedicated kernels: both methods leave speed on the table without fused, hardware-aware implementations.ReferencesTurboQuant and TriAttentionTurboQuant: Online Vector Quantization with Near-optimal Distortion RateTriAttention: Efficient Long Reasoning with Trigonometric KV CompressionTriAttention official implementationTensorRT-LLM TriAttention guideArchitecturalFast Transformer Decoding: One Write-Head is All You Need (MQA)GQA: Training Generalized Multi-Query Transformer Models from Multi-Head CheckpointsDeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (MLA)Reducing Transformer Key-Value Cache Size with Cross-Layer AttentionToken eviction and selectionEfficient Streaming Language Models with Attention Sinks (StreamingLLM)H2O: Heavy-Hitter Oracle for Efficient Generative Inference of Large Language ModelsScissorhands: Exploiting the Persistence of Importance Hypothesis for LLM KV Cache Compression at Test TimeSnapKV: LLM Knows What You are Looking for Before GenerationPyramidKV: Dynamic KV Cache Compression Based on Pyramidal Information FunnelingAda-KV: Optimizing KV Cache Eviction by Adaptive Budget Allocation for Efficient LLM InferenceR-KV: Redundancy-aware KV Cache Compression for Reasoning ModelsQuantizationKIVI: A Tuning-Free Asymmetric 2bit Quantization for KV CacheKVQuant: Towards 10 Million Context Length LLM Inference with KV Cache QuantizationQJL: 1-Bit Quantized JL Transform for KV Cache QuantizationPolarQuant: Quantizing KV Caches with Polar TransformationLow-rank, cross-layer, and system-levelPalu: Compressing KV-Cache with Low-Rank ProjectionMiniCache: KV Cache Compression in Depth Dimension for Large Language ModelsQuest: Query-Aware Sparsity for Efficient Long-Context LLM InferenceEfficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)Shrinking the KV Cache: An End-to-End Guide to KV Compression, with Deep Dives into TurboQuant and… was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.