Hypothetical scenario. Northwind can compare candidate passages, but Maya notices a new problem. In one conversation, “it” refers to a borrowing request; in another, it refers to a device. Dev points to the initial token representation. Priya asks how the model can use the surrounding sequence to treat these occurrences differently.
Maya: “The same word appears in both questions, but it refers to something different.”
Dev: “The initial representation alone does not settle which context this position uses.”
Priya: “Trace the queries, keys and values. Then separate the attention calculation from the state we retain.”
You will follow how attention constructs a position-specific mixture, distinguish self-attention from cross-attention, and calculate score-grid work separately from retained KV state. These are mechanisms for reasoning about context and memory; an attention weight is not proof that a policy claim is true.
Which sequence supplies the representations?
In self-attention, queries, keys and values are derived from the same sequence of representations. In cross-attention, queries come from one sequence while keys and values come from another. An encoder-decoder can therefore let a decoder position query an encoded source. This is a source-of-representations distinction, not a claim that cross-attention understands external facts. The T5 study by Raffel and colleagues provides an encoder-decoder reference.
Hypothetical scenario. Choose four target positions and six source positions. One cross-attention head compares 4 × 6 = 24 query-key pairs. Self-attention over four target positions has a 4 × 4 = 16-position score grid before considering masks. These are grid counts, not execution-time measurements. Dense self-attention's score grid grows quadratically with sequence length; linear-attention approaches change the computation and its assumptions rather than making every transformer linear. Do not equate a KV cache with removing all attention comparisons.
Why isolated embeddings and uniform mixing are insufficient
An embedding gives a token an initial vector representation, but the same token can appear in different contexts. Simply averaging every token vector treats all positions identically for that average. It cannot by itself express that one position should receive a different mixture than another.
Attention introduces position-specific queries and comparisons. However, an analogy such as “highlight the important words” is incomplete. The mechanism produces numerical mixtures, not a human judgment of importance. Its weights are learned to support the training objective; they are not automatically factuality scores or explanations of every downstream decision.
Order matters too. A set of content vectors without position information does not encode whether a phrase appeared first or last. A transformer therefore needs a way to represent or incorporate position, in addition to the content-comparison mechanism. the attention definitions explains this distinction.
Keep attention computation separate from state lifetime
Hypothetical scenario. A causal decoder processes prefix P, then appends token t. Queries score permitted keys and combine their values; the causal mask excludes future positions. Cross-attention instead obtains keys and values from the selected external representation. Name which sequence supplies each tensor before counting its size.
| Artifact | Concrete evidence | Decision boundary |
|---|---|---|
| Q / K / V | query positions and source sequence | Define permitted attention |
| Mask | causal or task-specific visibility | Exclude forbidden positions |
| KV state | model, prefix, layout, lifetime | Release after actual execution |
Cached keys and values avoid selected repeated projection work, while active sequences retain their state across decode steps. A cache hit does not erase the logical prefix or the cost of attending to retained positions. A toy state shape with two layers, two KV heads, head dimension four, five positions and two bytes per value uses 2 × 2 × 2 × 4 × 5 × 2 = 320 payload bytes: the first factor two counts keys and values. Layout, metadata and runtime workspace are additional.
A query chooses a mixture of value vectors
In a standard attention layer, learned projections produce queries, keys, and values from the input representations. A query is compared with keys to obtain scores. The scores become weights, and the output is a weighted sum of values. Keys participate in comparison; values supply the vectors being mixed.
Scaled dot-product attention divides each query–key dot product by the square root of the key dimension, applies any mask, and uses softmax to obtain weights over allowed positions. Softmax exponentiates scores and divides each exponential by their sum. For finite allowed scores, the weights are nonnegative and sum to one. The formal mechanism is described in Attention Is All You Need and the the attention definitions.
Multi-head attention carries out multiple projected comparisons and combines their outputs. A full transformer also includes transformations such as feed-forward layers and connections that preserve and update the running representation. Attention alone is not the whole model, and a visualization of one head is not a complete account of its behavior.
Work a mixture whose arithmetic is visible
Hypothetical scenario. Use the two-coordinate query q = [1, 0], keys k₁ = [0, 1] and k₂ = [0, −1], and values v₁ = [2, 0] and v₂ = [0, 4]. These vectors are chosen for an exact calculation, not observed model activations.
The dot products are q · k₁ = 1 × 0 + 0 × 1 = 0 and q · k₂ = 1 × 0 + 0 × (−1) = 0. The key dimension is 2. Dividing by √2 still leaves both scores at zero. Softmax uses exp(0) = 1 for each score, so both weights are 1 ÷ (1 + 1) = 0.5.
The weighted output is 0.5 × [2, 0] + 0.5 × [0, 4] = [1, 0] + [0, 2] = [1, 2]. The output is a mixture of values. It is not a token identifier, and it does not have to equal either input value.
Now suppose the second position is disallowed by a mask. Its weight becomes zero; the sole allowed position receives weight one. The output is then 1 × [2, 0] = [2, 0]. The mask changes which interactions are permitted. It is not evidence that the disallowed token was unimportant in a human sense.
In a dense comparison between n query positions and n key positions, the score grid has n × n entries. At n = 4 that is 16; at n = 8 it is 64. Doubling sequence length quadruples that grid's entry count. This calculation describes the full pairwise grid, not every implementation's allocated memory.
A key/value cache is not a quadratic score grid
During causal autoregressive generation, earlier positions do not depend on tokens that come later. An implementation can retain their keys and values and reuse them for a new token instead of recomputing those earlier projections. It still needs to compare the new query with relevant cached keys and combine values. Caching does not make all work independent of context length. See Hugging Face's cache explanation.
For a simplified dense cache with identical dimensions across layers, its payload in bytes is 2 × L × B × T × H × d × s. Here 2 counts keys and values, L is cached layers, B is batch size, T is retained positions, H is the number of key/value heads, d is coordinates per head, and s is bytes per stored coordinate. This counts only cached values under the stated layout.
Hypothetical example. Choose L = 2, B = 1, T = 4, H = 1, d = 2, and s = 2 bytes. The payload is 2 × 2 × 1 × 4 × 1 × 2 × 2 = 64 bytes. Retaining 8 positions with everything else fixed gives 128 bytes. Cache payload grows linearly with retained positions in this model, unlike the full pairwise score grid.
This estimate excludes model weights, temporary tensors, allocator overhead, page bookkeeping, and other serving state. Architectures can also change which positions or heads are retained. Measure the implementation after identifying the relevant dimensions; do not turn this small formula into a complete GPU-capacity estimate.
Work the memory budget for a growing chat
Toy math. Choose 32 layers, one active sequence, 4,096 retained tokens, eight key/value heads, 128 coordinates per head and two bytes per coordinate. Starting from 2 × layers × batch × tokens × KV heads × head width × bytes, one retained token costs 2 × 32 × 1 × 8 × 128 × 2 = 131,072 bytes. At 4,096 tokens this is 536,870,912 bytes = 512 MiB, using 1 MiB = 1,048,576 bytes. At 8,192 tokens it becomes 1,024 MiB = 1 GiB. Four such 8,192-token sequences require 4 GiB of cache payload, before weights or temporary work.
Multi-head attention (MHA) gives query heads separate key/value heads. Multi-query attention (MQA) shares one key/value head across query heads. Grouped-query attention (GQA) puts query heads into groups that share keys and values. Cache size follows the number of KV heads, not the query-head count. With the same chosen dimensions and 32 query heads, changing the KV-head count from eight to 32 multiplies payload by four: 512 MiB becomes 2 GiB at 4,096 tokens. One KV head instead gives 512 ÷ 8 = 64 MiB. These are architectural comparisons, not settings that can be changed arbitrarily on a deployed checkpoint.
Prefill processes the supplied prompt and populates cached state. Decode repeatedly produces another token using the retained history. A long prompt can therefore increase both initial work and the state carried through generation. Admission needs the expected generated length too: an 8,192-token prompt with room for another 2,048 tokens has a planned maximum of 10,240 retained tokens, not 8,192. Under the eight-head example that is 131,072 × 10,240 = 1,342,177,280 bytes = 1.25 GiB for one sequence.
In the wild: grouping heads changes the serving trade
Ainslie and colleagues’ GQA paper studies grouped-query models as a compromise between multi-head and multi-query attention, including conversion from multi-head checkpoints. Its experiments motivate treating the number of KV heads as an architectural choice with quality and runtime consequences. They do not establish Northwind’s acceptance rate or GPU throughput.
Sam should inspect the chosen checkpoint’s configuration, count its actual KV heads, then test the serving implementation. A model name or advertised context limit cannot fill in those dimensions. If the assistant cannot preserve its promised context within capacity, decide explicitly between shorter evidence, a bounded summary, queued admission or a rejected request.
When an evaluation accidentally reveals the answer
Hypothetical scenario. A training experiment intended to predict the next token permits a position to attend to future tokens that include the target. Its reported loss becomes much better, and the team initially interprets the result as a modeling improvement.
The evaluation has changed the information available to the prediction. A causal mask is part of the task definition, not just an optimization detail. If the intended inference process cannot access those future tokens, the improved training result does not establish performance under the intended conditions.
Inspect allowed positions, alignment between inputs and targets, and the information used during evaluation. A correct matrix multiplication with an incorrect mask can still answer the wrong experimental question. The same principle applies when a document system inadvertently includes the answer or restricted material in its context.
Avoid collapsing three different problems
“All attention-related memory grows quadratically.” The full pairwise score grid has a quadratic entry count, but the simplified key/value-cache payload above is linear in retained positions. Name the tensor or structure being counted.
“An efficient attention kernel fixes missing evidence.” FlashAttention addresses the computation and memory-traffic organization of exact attention. That is different from proving that an answer uses the right evidence. Do not present a kernel choice as a general cure for long-context quality problems.
“A large attention weight is a truth score.” The weight controls a numerical mixture under a model's learned scoring mechanism. Its normalization does not make it a calibrated probability that a retrieved claim is correct.
“Caching eliminates the cost of reading a long history.” Retaining past keys and values avoids repeated work of a particular kind. It does not remove the need to access relevant cached data for a new query. Separate reuse, access cost, and answer quality.
Where the mechanism helps a system designer
Use this explanation when checking tensor shapes, causal constraints, cache estimates, or the difference between processing an input sequence and generating another token. Trace which representation is stored, which operation is repeated, and which dimensions change with workload.
Do not infer a proprietary model's internal attention structure from its advertised context size. Nor should a theoretical entry count be presented as measured latency or memory. A serving decision needs the actual architecture, implementation, hardware, request pattern, and evaluation criteria. The mechanism narrows the questions; it does not supply missing measurements.
Limits of the memory model
This payload estimate assumes identical cached dimensions across layers and full retained history. Actual serving also needs weights, activations, temporary workspace, fragmentation and bookkeeping; sliding windows, cache quantization and shared prefixes change the accounting. Measure the implementation before choosing a concurrency limit, and evaluate answer quality separately from memory or latency.
Test the q / k / v boundary
A timeout returns to the caller while decode continues. Is its KV memory free?
Reveal the design reasoning
No. Caller waiting and runtime state lifetime differ. Retain the reservation until completion or confirmed cancellation releases the sequence. Include retained and abandoned work in admission.
Decision: Count compute, live KV payload and runtime overhead independently.
Check yourself: identify the object being calculated
Two allowed keys have equal scores and values [6, 0] and [0, 2]. What is the attention output? What if the second key is masked?
Normalize, then mix values
Equal scores give weights 0.5 and 0.5. The output is [3, 1]. Masking the second key leaves only the first allowed, giving [6, 0]. Neither output is a correctness probability.
With the cache layout in the worked example, retaining twice as many positions changes the payload from 64 to how many bytes? Does the full pairwise grid change by the same factor?
Separate the storage models
The cache payload doubles to 128 bytes with other dimensions fixed. A full n-by-n score grid quadruples its entry count when both sequence dimensions double. They count different objects.
A faster exact-attention kernel reduces measured runtime. Does that prove that a document answer no longer misses an exception?
Distinguish speed from task quality
No. Runtime evidence supports the measured performance result under its setup. Answer correctness needs its own evaluation with the relevant evidence and question. A computational optimization is not a factuality guarantee.
Northwind decision log
Budget cache memory by active tokens.
Include key/value heads, layers and element width.
Admit a conversation only when its growth fits.
Go deeper: attention, sequences and retained state
- Video lesson: Attention in transformers, step-by-step — Grant Sanderson. Watch first for a visual account of queries, keys and value mixing.
- Book chapter: Understanding Deep Learning, chapter 12: Transformers — Simon J. D. Prince. Develop the attention mechanism inside the complete transformer block.
- Book chapter: Deep Learning, chapter 10: Sequence Modeling: Recurrent and Recursive Nets — Ian Goodfellow, Yoshua Bengio and Aaron Courville. Compare retained recurrent state with attention over a sequence.
- Primary paper: GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints — Joshua Ainslie and colleagues. Connect KV-head sharing to the serving trade-off.
Check the mechanism in this lesson
Does cross-attention between four target positions and six source positions have a four-by-four comparison grid?
Compare the explanation
No. Queries belong to four target positions while keys belong to six source positions, giving 4 × 6 = 24 pairs for the declared head. Keep the two sequence identities visible.
Carry the decision forward
Northwind can now distinguish context-dependent mixtures, visibility masks and retained state. Page 05 uses those distinctions to compare prediction problems: selecting a relevant passage and generating an answer need not have the same model interface.