Bhuvan Chandra Dabbara
LinkedIn

Long context is paid for in memory, and the transformer was rebuilt

Generating each token means rereading a cache that grows with the context, so the advances that mattered since 2017 move fewer bytes, not fewer multiplications.

Key figure3TBKey-value cache of PaLM 540B at batch 512 and 2,048 tokens of context

AlsoMarketsEconomics

FieldsHardwareArtificial intelligence

Bhuvan Chandra Dabbara · https://bcd-site.pages.dev/papers/long-context-is-paid-for-in-memory/

Cite

Cite this paper

Dabbara, B. C. (2026, June 12). Long context is paid for in memory, and the transformer was rebuilt [Working paper]. Bhuvan Chandra Dabbara. https://bcd-site.pages.dev/papers/long-context-is-paid-for-in-memory/

Dabbara, Bhuvan Chandra. “Long context is paid for in memory, and the transformer was rebuilt.” Working paper. Bhuvan Chandra Dabbara, June 12, 2026. https://bcd-site.pages.dev/papers/long-context-is-paid-for-in-memory/.

@misc{dabbara2026long,
  author       = {Dabbara, Bhuvan Chandra},
  title        = {{Long context is paid for in memory, and the transformer was rebuilt}},
  year         = {2026},
  month        = jun,
  day          = {12},
  howpublished = {Working paper, Bhuvan Chandra Dabbara},
  url          = {https://bcd-site.pages.dev/papers/long-context-is-paid-for-in-memory/}
}

By Bhuvan Chandra Dabbara. Working papers change as I learn more; the date is the date of writing.

The advertised context window of a large language model is a budget of memory bandwidth before it is a budget of arithmetic: during generation every new token requires the accelerator to reread a key-value cache whose size grows linearly with the context, and it is this traffic, not the quadratic count of multiplications in self-attention, that sets the cost of serving long prompts. Many of the changes to the transformer since 2017 that reached production at scale, from multi-query and grouped-query attention to FlashAttention and paged caches, are on my reading devices for moving fewer bytes, and the evidence that models recall the middle of a long context less reliably than its ends means that a longer window is not the same thing as a longer memory. The concession I owe the opposing view is substantial, since training remains governed by arithmetic and the newest designs alter both sides of the ledger; but the price schedules on which long context is now sold are consistent with a seller that prices the bytes.

The equation hides two costs

Ashish Vaswani, Noam Shazeer and their co-authors at Google defined attention as a softmax over the scaled dot products of a query with every key, used as weights on the corresponding values, and they reported its per-layer cost as growing with the square of the sequence length multiplied by the representation dimension1. That quadratic term is the famous one, and it is real during training and during the prefill of a prompt, when all positions are processed in parallel. Its weight in the total is smaller than its reputation, however. Jared Kaplan and his colleagues put the forward compute of a decoder at roughly twice its parameter count per token plus a context term proportional to the number of layers, the context length and the model dimension, and they observed that the context term remains a small fraction of the whole so long as the model dimension exceeds one twelfth of the context length2. For a model of dimension 8,192, my own arithmetic puts that threshold near 98,000 tokens (twelve times the dimension); well below it, the multiplications that attention adds are a modest surcharge on the multiplications the weights already require.

The second cost appears only at inference, and it is the one that binds. Generation is autoregressive: each token is produced by a full forward pass that must attend to the keys and values of every preceding token, so those tensors are cached rather than recomputed and are read from high-bandwidth memory once per generated token3. Reiner Pope and his co-authors, describing the serving of PaLM 540B on TPU v4, note that whereas the attention multiplications add comparatively few operations, the cache is unique to each sequence in a batch and therefore cannot be amortised as weights can; at a batch of 512 and a context of 2,048 tokens it totalled 3TB, three times the size of the model’s parameters, and while it streams in the computational core is essentially idle3. Shazeer had already formalised the asymmetry: for incremental decoding the ratio of memory access to arithmetic scales with the context length divided by the model dimension plus the reciprocal of the batch size, and when either term approaches one, bandwidth rather than compute becomes the binding constraint4.

The hardware has made this asymmetry steadily worse. Amir Gholami, Kurt Keutzer and their co-authors estimate that over twenty years peak server FLOPS rose about 60,000 times, at roughly 3.0 times every two years, while DRAM bandwidth rose about 100 times and interconnect bandwidth about 30 times5. An algorithm whose cost is dominated by bytes therefore falls further behind the arithmetic it could, in principle, perform with each successive generation of accelerator.

Key figures

Twenty years of compute against memory bandwidth

60,000x
rise in peak server hardware FLOPS
100x
rise in DRAM bandwidth over the same period

Source: Gholami et al. (2024)

The cache is the bill

The size of the cache follows from the architecture by simple multiplication. Woosuk Kwon, Ion Stoica and their co-authors at Berkeley give the case of OPT-13B: two tensors (key and value) times a hidden size of 5,120 times 40 layers times 2 bytes in 16-bit precision, or about 800KB for a single token, so that one request at the model’s 2,048-token limit can require 1.6GB6. Written generally, the cache is twice the number of layers, times the number of key-value heads, times the dimension of each head, times the bytes per stored value, times the context length, times the batch; the number of key-value heads is the term that grouped-query designs reduce7. The model below lets the reader vary each factor. At a million tokens with the OPT-13B configuration the formula gives a cache of about 760GiB for a single sequence, far beyond any one accelerator, which is why million-token windows presuppose changes to the head count, the precision or both.

Figure 1

Key-value cache memory for one batch of sequences

Defaults reproduce OPT-13B at 2,048 tokens; raise the context or lower the key-value heads and watch the cache move.

Inputs

  • Layers L: 40, from 1 to 128
  • Key-value heads h: 40, from 1 to 128
  • Dimension per head d: 128, from 32 to 256
  • Bytes per value p: 2bytes, from 0.5 to 4
  • Context length T: 2048tokens, from 1024 to 1000000
  • Batch B: 1sequences, from 1 to 512

Outputs

  • Cache per token = 2 * L * h * d * p / 1024 KiB
  • Cache for the batch = 2 * L * h * d * p * T * B / pow(1024, 3) GiB

Source: Kwon et al. (2023), Ainslie et al. (2023)

Capacity, then, is the first constraint and bandwidth the second, and the two interact through the batch. A server that can hold more caches can batch more sequences, which amortises the reading of weights across more tokens and raises utilisation; one that cannot is pushed back towards the bandwidth-bound regime that Shazeer described. Kwon and his colleagues found that existing serving systems, which reserved a contiguous block for each request at its maximum possible length, used only 20.4 to 38.2 per cent of their cache memory to hold actual token states, the rest being lost to reservation and fragmentation6. Their remedy borrows the operating system’s virtual memory: the cache is divided into fixed blocks mapped through a table, so that a request occupies only the pages it has filled and sequences sharing a prefix can share its pages; their own measurement of the resulting system put usage at 96.3 per cent, and throughput rose two to four times at equal latency6. No multiplication was removed. The gain came entirely from the allocation of bytes.

Fewer heads with nearly the same answers

The most consequential change to the attention layer itself was a reduction in what it stores. Shazeer’s multi-query attention keeps many query heads but shares a single key head and a single value head among them, which cuts the cache, and hence the bytes read per token, by a factor equal to the number of heads4. In his translation experiments on a TPUv2, the incremental decoder fell from 46 to 3.8 microseconds per token while a training step barely moved, from 433 to 425 milliseconds, and quality declined only slightly4. That contrast is the thesis in miniature: an architectural change that is neutral for arithmetic and therefore for training turns out to be worth an order of magnitude at inference, because inference is paid for in memory traffic. Pope’s group reported that an optimised multi-query layout let PaLM 540B on 64 chips support a maximum context of 43,000 tokens at batch 128, against 1,320 for multi-head attention, with 30 per cent of memory reserved for the cache3.

Joshua Ainslie and his co-authors at Google Research then generalised the idea. Grouped-query attention divides the query heads into groups that each share one key and one value head, interpolating between the multi-head and multi-query extremes, and an existing multi-head checkpoint can be converted by mean-pooling its key and value heads and continuing pre-training for 5 per cent of the original steps, which for T5-XXL took about 600 TPUv3 chip-days7. The chart below shows the time per sample they measured: eight groups brought the XXL model from 1.51 to 0.28 seconds, close to multi-query attention’s 0.24, while its average score across their tasks was 47.1 against 47.2 for the multi-head original and 46.6 for multi-query7.

Figure 2

Inference time per sample for T5 variants with different attention heads

Look at how close grouped-query XXL comes to multi-query speed while keeping almost all of multi-head quality.

Show the data
modelTime per sample (seconds)
MHA-Large0.37
MHA-XXL1.51
MQA-XXL0.24
GQA-8-XXL0.28

Source: Ainslie et al. (2023)

The line continues past grouping. DeepSeek’s multi-head latent attention caches a compressed latent vector per token in place of per-head keys and values; the firm’s own comparison sets its cache at the equivalent of grouped-query attention with only 2.25 groups, and against its earlier 67-billion-parameter dense model it reported a 93.3 per cent smaller cache and a maximum generation throughput 5.76 times higher8. Each step in this sequence, from Shazeer through Ainslie to latent compression, accepts some additional computation or some loss of representational freedom in exchange for fewer stored and fewer transferred bytes per token.

More arithmetic in exchange for fewer bytes

FlashAttention, from Tri Dao, Christopher Ré and their co-authors, makes the same trade inside a single kernel and makes it explicitly. On the A100 they describe, high-bandwidth memory offers 40 to 80GB at 1.5 to 2.0TB per second, while the on-chip SRAM of the 108 streaming multiprocessors totals far less but is estimated at around 19TB per second9. Standard attention writes the full matrix of scores to high-bandwidth memory and reads it back; FlashAttention tiles the computation so that blocks of queries, keys and values are loaded into SRAM, the softmax is computed incrementally with running normalisers, and the full matrix is never materialised, recomputing parts of it in the backward pass rather than storing them9. The authors prove that the number of high-bandwidth memory accesses falls from a term quadratic in sequence length to one that also divides by the size of SRAM, and that no exact attention algorithm can asymptotically do better across all SRAM sizes9. The table below, taken from their measurement on GPT-2 medium, is the clearest single piece of evidence for my thesis: the faster method performs more floating-point operations, not fewer.

Figure 3

Standard attention against FlashAttention on GPT-2 medium, forward and backward pass

FlashAttention does more arithmetic yet runs several times faster, because it moves roughly a ninth of the bytes.

MeasureStandard attentionFlashAttention
Arithmetic (GFLOPs)66.675.2
Memory reads and writes (GB)40.34.4
Runtime (ms)41.77.3

Source: Dao et al. (2022)

The mechanism that links these devices can be stated as a sequence, and every remedy above intervenes at one of its links.

Figure 4

Why generating one token is a memory problem

Each step follows from the one before; the remedies at the end act on the bytes, not the multiplications.

  1. A token is sampled

    Decoding is sequential: each new token needs a full forward pass over all layers before the next can begin.

  2. The cache is reread

    Every layer reads the stored keys and values of all earlier tokens, together with the weights, from high-bandwidth memory.

  3. Arithmetic per byte falls

    The ratio of memory access to computation grows with context length over model dimension and with the reciprocal of the batch.

  4. The cores wait

    At batch 512 and 2,048 tokens PaLM 540B's cache reached 3TB, and the chip is essentially idle while it loads.

  5. Engineering acts on bytes

    Share key and value heads, page the cache, fuse attention into on-chip memory: each cuts traffic rather than operations.

Source: Pope et al. (2022), Shazeer (2019), Kwon et al. (2023)

Positions are stretched, not extrapolated

Rotary position embeddings are sometimes counted among the devices that make long windows practicable, on the assumption that they let a model run beyond the length it was trained on. The primary record does not support that claim as stated. Shouyuan Chen and his co-authors at Meta report that rotary embeddings, which encode position by rotating query and key vectors through angles proportional to their index, have weak extrapolation properties: evaluated past the trained length, attention scores can become catastrophically large, and direct fine-tuning of LLaMA at a longer length moved its effective window only from 2,048 to 2,560 tokens after more than 10,000 batches10. Their position interpolation instead rescales positions downward so that a longer sequence falls within the trained range; it extended LLaMA models from 7 to 65 billion parameters to 32,768 tokens with about 1,000 fine-tuning steps, and they bound the interpolated attention score at roughly 600 times below the extrapolated one in their LLaMA 7B setting10. Positional technique, then, governs whether a stored cache can be read meaningfully at a given length; it does not reduce what the cache costs, and it therefore falls outside the memory devices considered above.

A longer window is not a longer memory

The distinction between holding a record and being able to retrieve it is old; Plato’s figure of the aviary in the Theaetetus, in which a man may possess birds without having the one he wants in hand, states it precisely. Nelson Liu, Percy Liang and their co-authors tested it on language models by placing the single document that answers a question at different positions among retrieved distractors11. Accuracy traced a U-shape: highest when the relevant document came first or last, lowest in the middle. With 30 documents, GPT-3.5-Turbo (16K) answered 73.4 per cent of questions correctly when the answer sat first, 50.5 per cent when it sat tenth and 63.7 per cent when it sat last, and the middle figure is below the 56.0 per cent the same model achieved with no documents at all11. The authors also found that extended-context variants performed almost identically to their shorter-window counterparts whenever the input fitted both, so that the larger window bought admissibility rather than better use11.

Figure 5

Multi-document question answering accuracy by position of the relevant document, 30 documents

Follow the lead line down into the middle positions and back up at the end; the closed-book score for the same model was 56.0%.

Show the data
positionGPT-3.5-Turbo (16K) (%)Claude-1.3 (100K) (%)MPT-30B-Instruct (%)LongChat-13B (16K) (%)
1st73.459.151.666.9
5th55.155.151.354.8
10th50.554.951.252.5
15th50.955.74952.9
20th51.856.649.652.2
25th54.956.151.351.3
30th63.76054.155.1

Source: Liu et al. (2024)

Those models are now old, and a sceptic may fairly ask whether the gap has closed. The RULER benchmark from Cheng-Ping Hsieh, Boris Ginsburg and colleagues at NVIDIA is the most systematic answer available to me: it extends the needle-in-a-haystack test with multiple needles, multi-hop tracing and aggregation, and grades 17 models against the 85.6 per cent that Llama 2 (7B) scores at 4,000 tokens12. Although every model claimed a window of at least 32,000 tokens and nearly all scored almost perfectly on the vanilla retrieval test, only half kept satisfactory performance at 32,000 tokens; Gemini 1.5 Pro alone remained above the threshold at 128,000 tokens, the longest length tested12. The evidence admits of two readings. One is that effective context is improving and simply lags its advertisement; the other is that the gap is structural, because a softmax distributed over ever more positions must dilute its weight somewhere. I do not think the present record decides between them, but either reading separates the window that is sold from the memory that is delivered.

The case that arithmetic still governs

The strongest objection is that I have described inference and called it the transformer. Training cost, which still decides who can build a frontier model at all, is set by the roughly six operations per parameter per token that Kaplan’s accounting implies once the backward pass is included, with the context term negligible at the lengths on which most pre-training is done2. Mixture-of-experts designs attack exactly that quantity: DeepSeek-V2 stores 236 billion parameters but activates 21 billion for each token, and its authors report a 42.5 per cent saving in training cost relative to their dense predecessor while crediting the mixture-of-experts layers with economical training through sparse computation8. State-space models such as Mamba, from Albert Gu and Tri Dao, replace attention with a selective recurrence whose state has fixed size, giving linear-time training, constant-time steps at inference and a reported fivefold throughput advantage over transformers13. On this view the history of the architecture is one of compute and memory moving together, and to single out bytes is to mistake one constraint for the whole.

I concede the training point without reservation, and I concede that mixture-of-experts is primarily a compute device. Two considerations nonetheless keep the memory reading in place for long context specifically. The first is that sparsity in computation is not sparsity in storage: a model that activates 21 billion parameters per token must still hold all 236 billion where they can be reached, so that mixture-of-experts converts a compute saving into a capacity requirement8. The second is that Gu and Dao frame their own contribution in terms that support rather than contradict the thesis. They describe the central problem of sequence modelling as compressing context into a smaller state, and they locate attention’s inefficiency precisely in its refusal to compress, which forces it to keep the entire cache13. A recurrent model escapes the memory bill by holding a fixed state, and it pays, on their own analysis, in how well that state has preserved what was seen; that is the same trade between bytes kept and things recalled that the lost-in-the-middle results expose from the other side.

Who pays for the bytes, and who sets the price

If the cost of a long prompt is a memory cost, it should surface in prices, and it does. When Anthropic extended Claude Sonnet 4 to a million tokens in August 2025, it raised the input price for prompts above 200,000 tokens from $3 to $6 per million and the output price from $15 to $22.50, citing increased computational requirements, and pointed buyers to prompt caching and to batch processing, the latter at a further 50 per cent saving14. Anthropic states only the general reason; the mapping onto the mechanism is my own reading. A step in price at a fixed length is consistent with the point at which a sequence’s cache displaces enough other sequences to reduce the batch; caching a shared prefix resembles the page sharing that Kwon’s system made possible; and batch processing may be understood as selling the latency a provider gives up when it waits to fill a batch and amortise the weights6. The buyer, meanwhile, pays for every token admitted to the window, whether or not the model will use the tenth document as well as the first.

The economic incidence follows from who controls each layer of the constraint. Model designers decide how many key-value heads to keep and at what precision, and thereby how many bytes each token of context will cost for the life of the model; serving engineers decide how those bytes are paged, shared and scheduled; and the makers of high-bandwidth memory and of accelerators decide how fast the bytes can move, on a curve that has risen far more slowly than arithmetic for two decades5. Pricing then distributes the residual between provider and buyer. On my reading the arrangement resembles a congestion charge on a fixed facility more than a marginal cost of production, since the scarce input is capacity per accelerator and the price of a long prompt rises with the share of it the prompt occupies. What the schedule does not price is recall. As of June 2026 a buyer purchases admissibility to the window at a rate set by memory, and receives in exchange a probability of use that, on the best evidence available, depends on where in the window the needed fact happens to sit; whether that probability will converge on the advertisement, or whether the gap is the permanent price of attention’s refusal to compress, is the question the architecture has not yet answered.