A long context costs twice. It costs compute, and it costs memory. The memory cost is the subject of this post, so it needs unpacking first.
A language model reads text as tokens. A token is a word or a piece of a word, so a page of text is a few hundred tokens. The context is the run of tokens the model can see at once. Attention is the part of the model that lets the current token look back at the earlier ones.
For every token it has seen, the model keeps two short lists of numbers, a key and a value, and attention reads both on every new token. A list of numbers like that is called a vector, and the word comes up a lot below. The keys and values of every past token sit in a store called the KV cache. It grows by one key and one value per token, so at long contexts the cache, not the weights, is what fills the memory.
The standard way to shrink the cache is eviction. You pick a token budget, rank the cached tokens by some score of how much they seem to matter, and keep the top of the list. The budget is a hyperparameter, a setting the engineer chooses by hand rather than one the model learns, and it has no natural units. Nobody knows whether attention over a 32k-token context is using 32k tokens or 300. We wanted to measure that.
Attention also needs a word. An attention layer is made of several heads, and a head is one self-contained copy of the attention operation with its own keys and values and its own way of scoring them. A layer with 32 heads looks back at the context 32 separate times. Everything measured below is measured one head at a time.
One way to read an attention head is as a small network that gets built at runtime rather than learned. The network in question is a two-layer MLP, short for multilayer perceptron, the oldest kind of neural network. It is a matrix, then a nonlinear function applied to each number, which is any fixed curve that is not a straight line, then another matrix. Its hidden units are the numbers between the two matrices, and the width of the network is how many of them there are.
In the head read this way, the cached keys are the weights of the first matrix, the cached values are the weights of the second, and the context length is the width. A head over a 128k context is nominally a 128k-wide layer. The question is how wide it actually is, meaning how many real tokens in the cache you need before the head's outputs over its own queries are reconstructed to a chosen tolerance.
We define that number, estimate it with a greedy procedure, and measure it across dense transformers, hybrid models that mix attention with recurrent layers, and the attention-only SAN models from our earlier work, at contexts up to 128k. It grows with context and decelerates hard. It depends a lot on which queries you ask about. And on Qwen3-8B a cache budget calibrated from it keeps language-model loss almost intact while losing exact recall on a needle test.
These are the models that appear below. GQA is grouped-query attention, where several query heads share one set of keys and values, and we call that shared set a KV head.
| model | what it is |
|---|---|
| Qwen3-0.6B | A dense transformer from Alibaba's Qwen3 family, 0.6B parameters and 28 attention layers. Dense means every layer is an ordinary attention layer followed by a feed-forward layer. Its native context is 32k, stretched to 128k with YaRN. The model knows where each token sits through a position encoding, and YaRN rescales that encoding so the model accepts longer inputs than it was trained on. |
| Qwen3-8B | The 8.2B model from the same family, 36 attention layers, same context arrangement. |
| Qwen3.5-0.8B | A hybrid from the next Qwen generation, 0.8B parameters and 24 layers, of which only 6 are attention. The other 18 are Gated DeltaNet, a recurrent layer that keeps a fixed-size state instead of a cache. Context 262k. |
| Granite dense | IBM's Granite-4.0-Micro, a dense 3B transformer with 40 attention layers and a 128k context. |
| Granite hybrid | Granite-4.0-H-Micro, the hybrid from the same family and version. 40 layers, of which 4 are attention and 36 are Mamba-2, a state-space layer that also keeps a fixed-size state. |
| SAN | A 24M-parameter attention-only transformer from our controlled study, 20 layers with the feed-forward layers removed, 2k context. |
| FFN-isoD | The depth-matched control for SAN, 20 layers of attention plus feed-forward, 87M parameters. |
| FFN-isoP | The parameter-matched control for SAN, 4 layers of attention plus feed-forward, 24M parameters. |
A head as a runtime MLP
The maths starts here, and I am afraid there is a fair bit of it.
For a fixed cache, head computes
Read the pieces first. The query is the vector the current token uses to ask the cache a question. Each cached key is scored against it by an inner product, which multiplies the two vectors entry by entry and adds the products up. That score is large when the key and the query point the same way.
The softmax turns those scores into positive weights that sum to one, by exponentiating each score and dividing by the total. The output is the sum of the cached values weighted by those numbers. The square root in the denominator is a fixed scale that keeps the scores from growing with the size of the key vectors.
Now read it the way you would read a two-layer MLP, which computes , a weight matrix on each side of a nonlinearity. Here is , whose rows are the cached keys, so the first layer takes the query's inner product with every key and produces one hidden activation per token. The nonlinearity is the softmax across those activations. is , whose columns are the cached values, so each hidden unit writes its value into the output in proportion to its activation.
The width of this MLP is , the number of cached tokens. We call each cached token an atom, because it is one of the pieces the output is assembled from. The weights of this MLP were not learned by training. Training nudges every weight a little in the direction that lowers the error and repeats that millions of times, which is what gradient descent means. These weights were written into the cache by whatever text came before, and that is why the usual intuitions about wide networks do not carry over.
In a trained MLP the hidden units are free parameters that training can spread out to cover the input. Here the keys and values can be arbitrarily correlated, and they are coupled through the softmax, because its weights have to sum to one, so one unit's activation depends on every other unit's. Sending therefore buys no approximation guarantee by itself. The question is how many of the atoms the function actually uses, and the job of the paper is to turn that into a number.
Atomic effective width
Start with the geometry. Collect queries from positions after the prefix, so that they are drawn from the distribution of queries the head actually sees, and form
with the model's attention scale. is , one row per query and one column per cached token. Its column is a vector in that records how much each sampled query attends to token . It is the activation pattern of hidden unit , and it is the object this whole post is about.
The output matrix is , one output row per query. Every column of is a linear combination of the columns of , with coefficients taken from . So lives inside the column space of , the set of everything you can build by mixing its columns. The question of width becomes a question of how many columns of are needed to build the part of that space occupies.
Two standard tools pin this down. The first is least squares. Given a set of token columns, the best readout is the one that makes as close to as possible in Frobenius norm, which is the square root of the sum of the squares of every entry of the difference.
Geometrically is then the orthogonal projection of each column of onto the span of the chosen columns, the closest point to it inside that span. The span of a set of vectors is everything you can reach by scaling and adding them, so two arrows that are not parallel span a flat plane. The residual is whatever part of points outside the span, and it is perpendicular to it.
The second tool is the singular value decomposition, the SVD, which splits a matrix into a set of mutually perpendicular directions ranked by how much of the matrix each one carries. A subspace is a flat piece of a space that passes through the origin, a line or a plane or the higher analogue of one, and a span is a subspace. The Eckart–Young theorem says that the best subspace built from directions for approximating , over all subspaces, is the one spanned by its top such directions, its top left singular vectors. That subspace has dimension at most , because the rank of , the number of independent directions in it, is at most . But its basis vectors are mixtures of all columns of at once, and a mixture of tokens is not something a cache can hold. We insist that the basis be made of real columns, and that one constraint is why the width can be far larger than and can grow with .
The definition follows. The effective width at tolerance is the size of the smallest set of real token columns that, after refitting a readout by least squares, reproduces the outputs to within that tolerance,
The tolerance is the one hyperparameter, and it is in units a person can reason about, the fraction of the output we allow to be wrong. is a token count and not a deployable cache. It keeps the softmax normalised over the full tokens and refits , whereas an eviction method renormalises the softmax over the kept tokens and reuses their original values. The eviction experiments later use it only as a budget.
Minimising over subsets of , the set of all the token indices, is combinatorial, meaning the number of subsets doubles with every token and there is no checking them all, so we estimate it greedily. The tool is a weighted block-pivoted QR. Pivoted QR is a matrix factorisation that reorders the columns as it goes, and the order it produces is the classic way to pick a set of columns none of which is nearly a mixture of the others. At each step you look at every column not yet chosen, measure how much of it is not already explained by the columns you have, and take the largest.
Write for an orthonormal basis of the columns chosen so far, a set of unit-length directions at right angles to one another that span the same space. The matrix is the projector onto everything orthogonal to their span, so applying it to a vector removes the part the basis already covers. is therefore the new direction token would bring, and its squared length is how much new activation geometry the token adds. That is the novelty term, and the norm in the formula below is the length.
On its own novelty is the wrong score. A token that attends in a genuinely new pattern but carries a value of near-zero size contributes almost nothing to . So we weight by the squared norm of the value,
The product reads as how much new output this token could explain. It is in the spirit of Optimal Brain Surgeon, a classic method for pruning a network, which means deleting its least useful units. It scores a unit by the damage its removal does after the remaining units are refitted to compensate, and here the compensation is the least-squares readout. We take the highest-scoring tokens a block, orthogonalise their columns against and against each other, meaning we strip from each the part that lies along the directions already taken, and append the independent directions to the basis.
After atoms the fit error has a clean form. Each column of splits into the part inside the span of , which is , and the part outside. The two parts are perpendicular, so by Pythagoras the squared length of the outside part is . So
which is the relative error of the best least-squares readout without ever forming .
The sampled queries are split into two sets. The fit set is used to choose atoms. The held-out set, every fourth position, is used only to evaluate, so that the estimate is not rewarded for fitting the queries it selected on. is the first completed block size with on the held-out queries.
Because the greedy procedure builds a set that works rather than the smallest possible set, it is an upper bound on the exact empirical . Selection stops at 6,144 atoms. A head that has not reached the tolerance by then is treated as right-censored, meaning we record only that its width is above 6,144, and medians are reported only when fewer than half the heads are censored.
Whether the estimate means anything depends on how much it moves with the selection rule, so we checked. On eight Qwen3-8B KV heads at , with 2,048 sampled queries, we applied the same least-squares refit to several orderings of the token columns and counted the atoms each needed.
| selection rule | atoms at ε = 0.1 | atoms at ε = 0.2 |
|---|---|---|
| novelty × payload | 600 | 292 |
| plain QR novelty | 608 | 304 |
| block OMP | 496 | 228 |
| value-aware attention mass | 740 | 332 |
| random token order | 2,372 | 1,184 |
| SVD floor, not a token selector | 46 | 20 |
Plain QR is novelty alone. Block OMP, orthogonal matching pursuit, scores each column by how well it correlates with the part of the output not yet explained, rather than by novelty. Value-aware attention mass is the ordering an evictor in the style of OBCache would use. It ranks tokens by how much attention they receive, weighted by the size of their value, computed once and replayed through the same residual.
The three real-token rules land within 23% of ours, with OMP tighter, which is why should be read as an upper bound rather than the optimum. Random order needs about four times as many atoms, so the selection is doing real work. The SVD floor, which may use any direction in the column space of rather than real columns, is more than ten times smaller. That gap shows that matrix rank is not the quantity we are after. The head's output is low rank, but it is spread across many tokens.
The entropy-matched control
A small width could mean one of two things. The KV dictionary itself, the set of cached keys and values, might be simple, so that a few tokens span it under any queries. Or the dictionary might be rich and the head's natural queries might point at a small part of it. Those are different facts about a head, and we want to separate them.
The tool is softmax entropy. For a query the attention row is a distribution over tokens, and its entropy measures how many tokens it effectively spreads over. It is zero when all the mass is on one token and when the mass is spread evenly over all of them. Scaling the query by a factor changes only the sharpness of the distribution, and softmax entropy never increases as grows, so a larger never gives a more spread-out distribution. That monotonicity is what lets us solve for the scale by bisection.
For each real query we draw a random direction with , meaning every entry is drawn from a standard bell curve, which makes the direction a uniformly random point on the unit sphere of query space. We call it isotropic because no direction is preferred. Then we solve for such that . We use 30 steps of geometric bisection over , halving the search interval in log space each step, increasing when the attention is too spread out and decreasing it when too sharp. The entropy-matched query is .
Geometrically, we have kept how many tokens the head looks at and thrown away where it looks. A head's real queries occupy some region of the sphere that lines up with the keys it cares about, and the isotropic ones cover the sphere evenly.
Run the same estimator on the same and under the new queries and take the ratio,
A ratio near one says the dictionary itself is small and the head would be narrow under any queries. A ratio far above one says the dictionary is wide and the head's narrowness comes from where its queries point, which is to say the head is specialised to its input distribution. We call the ratio the isotropic access gap.
What we measured
We used the text of Moby Dick as the context. At with 16,384 sampled query positions and every fourth held out, every model's median width grows with context and decelerates. The local log-log slope is the change in over the change in between adjacent context lengths. It falls from 0.8 to 1.4 at short lengths to 0.23 to 0.46 over the longest intervals. A slope of one is width growing like , a slope of a half is growth like , and zero is flat, so the curves pass from near-linear to well below square root.
Two kinds of theory suggest shapes to compare against. Under a Gaussian input model, where the inputs are drawn from a bell curve, Deng et al. show that attention rows can be approximated by keeping entries, a power of the context.
A kernel is a smooth function that scores how alike two inputs are, and its eigenvalues are the sizes of its independent components. For smooth kernels those sizes fall off exponentially, each a fixed fraction of the one before, so the number of components that matter grows like , a power of the logarithm of the context. Neither is about our object, so we treat them as candidate shapes rather than predictions.
We fit both shapes, and , by least squares in . The polylogarithmic form has lower in-sample error on all five long series and is closer on every held-out final point. But both forms overpredict the final point, the polylog by 24% to 88%. With five points per series we claim curvature and not a law.
Part of the flattening may be an artefact of sampling. On the twelve KV heads of Qwen3.5-0.8B at , the fitted width keeps rising as the fit set grows, from 1,188 atoms with 512 fit positions to 3,232 with 3,072, while the held-out error falls from 0.757 to 0.406. The production protocol at 131,072 tokens still has a held-out error of 0.262. So the 16,384-position budget is justified, but it does not establish that the width of every head has saturated at the longest lengths.
Across architectures the picture differs, and it shows in the plane of real width against entropy-matched width, one dot per head. Dense models have three populations of heads. The first is a narrow set described by a handful of atoms that mostly attend to the attention sinks, the first few tokens of the sequence onto which many heads dump attention they have nowhere else to put. The second is a main body whose isotropic widths cluster much more tightly than their real widths. The third is a small set that sits on the equality line, where real and isotropic widths are the same.
That last set lives almost entirely in the first layers. All eight such heads in the stratified Qwen3-8B sample, a subset of heads chosen evenly across layers, and all four in Granite dense are in layer 0. In the full Qwen3-0.6B census, where every head was measured, 11 of 12 are in layers 0 to 2.
The hybrids differ from the dense models and from each other. Qwen3.5-0.8B, which keeps six attention layers out of 24 with Gated DeltaNet elsewhere, has a small narrow-head population and a main body whose slope in the log-log plane is negative. Granite-4.0-H-Micro, with four attention layers out of 40 and Mamba-2 elsewhere, has no narrow heads at all and a main body with positive slope. Both concentrate global attention into fewer, individually wider heads.
At the median real-query width is 168 for Qwen3-0.6B, 396 for Granite dense, 1,032 for Qwen3-8B, 1,140 for the Granite hybrid and 1,892 for the Qwen3.5 hybrid. The Granite pair is the cleaner comparison, since both models are from the same family and version, while Qwen3 and Qwen3.5 differ in training as well as architecture.
YaRN, the context-extension method that rescales the position encoding, keeps the shape of the plot and shifts the main body toward larger real widths. The median ratio of a head's width with YaRN to its width without is 1.66 at 4k and 1.91 at 16k, while the same ratio for the entropy-matched width at 4k is 0.98. So the context-extension method changes which part of the fixed dictionary natural queries reach, and leaves the dictionary alone.
SAN heads at 1,536 tokens have a median width of 36 against 76 and 74 for their depth-matched and parameter-matched controls, and a larger gap to their isotropic width. In the full causal map SAN also puts 0.238 of its attention mass on the current position against 0.066 and 0.082 for the controls. That is consistent with attention taking over some of the per-token work the missing feed-forward layer used to do.
It is natural to ask whether a cheaper statistic would do instead. Attention entropy correlates with log width at 0.84 in Qwen3-0.6B, but the sign flips to −0.46 in the Granite hybrid. The covariance matrix of a set of vectors records how every pair of their coordinates varies together, and its participation ratio counts how many directions carry its variance. The participation ratios of the query covariance and of the key-projected query covariance are weak or negative predictors in the dense models.
The only comparator positive in every architecture, at 0.53 to 0.89, is a payload-weighted spectral rank, the -effective rank of with the diagonal matrix of value norms, meaning the number of directions needed to capture that matrix to within the tolerance. It is the only one that sees the activations, the payloads and the tolerance together, and even it is not in token units.
The width as a cache budget
If is a tolerance then it ought to work as a cache budget, and the test is whether a budget calibrated on some documents transfers to another. We took six long documents, Moby Dick, The Count of Monte Cristo, Middlemarch, On the Origin of Species, Kant's Critique of Pure Reason and WikiText-103, and held one out at a time. On the other five we measured the per-head width at the given , summed over heads into a whole-model budget per document, and took the geometric mean of the five budgets. That number is the prescription for the held-out document.
The evaluation uses Qwen3-8B with a 32,768-token prefix. The first 30,720 tokens are the region we are allowed to compress. The last 2,048 tokens and the four initial sink tokens are always kept. Within the budget, tokens are selected by a fixed ranking in the style of OBCache, each token scored by how much attention it receives weighted by the size of its value, estimated from 4,096 sampled query positions. We measure next-token loss on the following 2,048 tokens with teacher forcing, meaning the model predicts each token given the true tokens before it. The loss is cross-entropy, the model's average surprise at the true next token, and a nat is that surprise measured with the natural logarithm.
The budget orders the trade-off on every document. Raising lowers the prescribed budget and raises the loss, with no exceptions. At the cache is 9.1 times smaller for 0.0067 nats of extra next-token loss, and at it is 11.0 times smaller for 0.0212 nats. Both beat the baseline that keeps only a sliding window of recent tokens plus the sinks on all six documents, and the and budgets beat it on five of six. So a quantity defined through attention-output reconstruction predicts language-model loss across documents.
Then we ran a needle test. Ten statements pairing a city with a six-digit code were inserted at evenly spaced depths from 5% to 95% of a 32,768-token Moby Dick context, and the model was asked for each code and allowed ten tokens of greedy decoding, where the model picks its single most likely token at each step. Full attention finds all ten. Sliding window, random eviction, H2O, an evictor that keeps the tokens with the most accumulated attention, and every -budgeted condition find none, including conditions that keep roughly one entry per 15 to 18 original tokens per head.
To see whether the failure is simply the needle being evicted, we put the needle spans back into the selected cache as an oracle. Restoring them in all 288 KV heads recovers 100%. Ranking heads by how much attention the final question token pays to the needle digits and restoring only the top 64 recovers nothing, the top 128 recovers 40%, and only the full set recovers everything.
Exact retrieval here needs many heads to succeed at once, and average reconstruction error, which is what measures, does not see that. A compression scheme can preserve average language-modelling behaviour and lose a rare capability at the same time.
What the results mean
The reading of attention as a fast-weights MLP, a network whose weights are written at runtime, is now quantitative. The nominal width of a head grows linearly with context, and the number of atoms needed to reconstruct what the median head does grows far more slowly. So a longer context expands the runtime dictionary without a proportional increase in the complexity of the function the head implements. That is the opportunity for attention that costs less than linear in the context, stated in token units.
The opportunity is conditional. The same dictionary looks much wider once the real queries are replaced by isotropic ones at matched sharpness, so compression calibrated on natural queries can reproduce attention on similar queries and fail when the queries shift.
Architecture decides how width is allocated. Hybrids put global attention into a few wide heads whose natural queries reach a large fraction of their counterfactual width. Dense transformers spread it over many heads, including narrow heads and heads whose width depends on the query distribution. SAN pushes some per-token computation into attention and ends up with sharper, narrower heads than its controls.
What it does not say
- The estimator is an upper bound, and its 16,384 sampled queries do not provably saturate every head, since the fitted width still rises with more fit queries at 128k.
- Relative Frobenius error is an average and hides rare queries, which the needle test made concrete.
- The entropy-matched isotropic distribution is one counterfactual, and other query shifts are untested.
- One document and a handful of context lengths per model, so deceleration is shown and an asymptotic law is not.
- The architecture pairs differ in more than architecture. On RULER, a suite of long-context retrieval tests, the relation between width deceleration and retrieval is not consistent across models, with Qwen3.5 holding up at long context and the Granite hybrid degrading sharply at its longest point.
- Measuring the width is an expensive offline procedure, not a runtime algorithm.
What stands is a token-count answer to how wide a head is, evidence that it grows far more slowly than the context, and a warning that the width of a head under its natural queries is not the width it would need under a shift.
References
- Schlag, Irie and Schmidhuber, Linear transformers are secretly fast weight programmers, ICML, 2021.
- Gu et al., OBCache: optimal brain KV cache pruning for efficient long-context LLM inference, 2025.
- Hassibi and Stork, Second order derivatives for network pruning: optimal brain surgeon, NeurIPS, 1993.
- Zhang et al., H2O: heavy-hitter oracle for efficient generative inference of large language models, NeurIPS, 2023.
- Xiao et al., Efficient streaming language models with attention sinks, ICLR, 2024.
- Li et al., SnapKV: LLM knows what you are looking for before generation, NeurIPS, 2024.
- Deng et al., How sparse attention approximates exact attention? Your attention is naturally n^C-sparse, 2024.
- Belkin, Approximation beats concentration? An approximation view on inference with smooth radial kernels, COLT, 2018.
- Peng et al., YaRN: efficient context window extension of large language models, 2023.
- Hsieh et al., RULER: what's the real context size of your long-context language models?, COLM, 2024.
- Ndubuaku et al., A controlled study of attention-only transformers, 2026.