It is how each position of a sequence takes in information from the others, choosing for itself which ones matter; it is the core of the transformer and of the models built from it.
On the path DNA-SocketAttention is how a position takes in information from other positions. In a language model a position may read only itself and the positions before it, so the position where the answer is read can reach the slots placed earlier in the prompt. Whether it actually uses what is there is a separate question, and the study tests it.
On the path Attention paperThe paper’s scaled dot-product attention: queries, keys and values, and why the scores are divided by the square root of their width.
On the path Inside a language modelHow each position takes in information from the others: queries, keys and values, and the mask that keeps a language model from reading ahead.
Reading the other positions
Many kinds of data come as a row of parts whose meaning depends on one another. Read the sentence “The animal didn’t cross the street because it was tired.” To understand “it”, you look back and decide that it means the animal; change “tired” to “too wide” and the same word means the street. A patch of a photograph is fur or shadow depending on the patches around it, and an amino acid in a protein behaves according to others that lie far from it in the chain but close to it once the chain is folded. Attention is the operation that lets each part, each position, gather information from the other positions, choosing for itself which of them matter. This page builds it from that idea, writes it in symbols, follows it through an example, and then asks what its parts mean, how it is trained and what it costs.
Suppose each position holds a vector that describes its own part and nothing else, such as a word’s embedding: the vector of “it” is then the same in both sentences. Attention changes that. It works like a lookup in a table that tolerates inexact matches. Every position offers two things: a key, which says what kind of information it holds, and a value, the information itself. A position that needs information issues a query, a description of what it is looking for. The query is compared with every key, and the better a key matches, the higher its score; a softmax turns the scores into weights that are positive and add up to 1; and the position receives the weighted average of the values. The three names come from this picture of a lookup; they describe the part each plays in the computation, not anything written inside the vectors.
When one key matches far better than the others, this is an ordinary lookup that returns that key’s value. When several match about equally, the position receives a blend of their values. Where do queries, keys and values come from? Each is the position’s own vector multiplied by a matrix, one matrix for each of the three. Before training these are arbitrary matrices: the multiplications are as good as any others, and a head built from them reads arbitrary positions and brings back arbitrary mixtures. Training changes the matrices until the head reads the positions that help predict what follows and brings back what is useful from them. What a query or a key stands for is therefore not fixed in advance; it is whatever training made of the multiplications.
Attention is the heart of the transformer, and so of the large language models built from it, where the positions are the tokens of a text. The same operation, unchanged, reads the patches of an image, the letters of a DNA sequence or the amino acids of a protein; what differs from one use to another is what the vectors hold and which positions may read which.
The operation in symbols
The same idea in symbols, for one head. Each position i holds a vector xi of d numbers; stacked, one row per position, these vectors form the matrix X. Three learned matrices turn every row into a query, a key and a value:
The query qi, key ki and value vi of position i are its vector xi, of d numbers, times the learned matrices WQ and WK, each of d rows and dk columns, and WV, of d rows and dv columns, usually dv = dk. Queries and keys have the same length, dk numbers, because they will be compared with each other. To review: a vector times a matrix.
Position i then reads the others in three steps: it scores every position, turns the scores into weights, and takes the weighted average of the values.
Here i is the position that reads and j a position it reads; qi is i’s query, and kj and vj are j’s key and value. The score sij of position j for position i is the dot product of i’s query with j’s key, divided by √dk, the square root of the keys’ length. The weight aij is the softmax of i’s scores: e raised to each score, divided by the sum over all positions l, so the weights are positive and add up to 1. The output oi is the sum of every position’s value vj times its weight. To review: dot products, exponentials and the softmax.
Each step has a reason. A dot product is large when two vectors point the same way, so a query “matches” the keys that point in its direction. Dividing by √dk keeps the scores at the same spread whatever the length of the keys, so that the softmax does not saturate in large heads. The softmax makes the weights a proper share of one, and the average lets several positions contribute in proportion. The formula also fixes, for any matrices, trained or not, what each of the three can do: the query and the key appear only in the score, so together they decide where a position reads; the value appears only in the average, so it decides what comes back. That division of labour is all the names refer to. Done for all positions at once, with the queries, keys and values stacked into matrices Q, K and V, the three steps are one line (Vaswani et al., 2017):
Q, K and V hold the queries, keys and values of all T positions, one row each; Attn(Q, K, V) is the output, one row per position. The matrix QKT (the T is the transpose) holds in row i the dot products of query i with every key. Divided by √dk and passed row by row through the softmax, it becomes the matrix of weights, and multiplying the weights by V takes each row’s weighted average of the values. To review: matrix products and the transpose.
The output oi has as many numbers as a value, usually dk. One more learned matrix, WO, turns it back into d numbers, and the result is added to the position’s vector, xi + oiWO (a residual connection). Attention as a whole therefore never changes the width: what comes out has as many numbers as what went in, so it can be added to its input and passed to the next layer.
A worked example
A small example makes this concrete, with one head, the simplest form of attention. Take the sentence about the animal, up to the word that reads, “The animal didn’t cross the street because it”, and give each word a row of six numbers: the embedding the table holds for its token, with its position added. Stacked, the eight rows form a matrix X. The three matrices WQ, WK and WV are six by six, so every query, key and value has six numbers: dk = 6, since a single head usually works at the full width. As in a real model, no single number of an embedding means anything on its own; the numbers here are made up, chosen so that the example ends the way a trained head would, and in a real model the embeddings and all three matrices are learned. With random matrices of the same size, “it” would spread its weight in some arbitrary pattern; reading “animal” is what training would have to teach it.
Then “it” reads the sentence, in the three steps of the formula. Its query is compared with every key, and the dot products are divided by √6: the score of “animal” is 2.85, far above the others, which range from 0.69 for “street” down to −0.99 for “cross”. The softmax turns the scores into weights that add up to 1. The output of “it” is the weighted average of the values, six numbers that come mostly from the value of “animal”.
Last, WO, here six by six as well, turns the output into the six numbers the head writes, and they are added to the row of “it”, which keeps its six numbers. Two kinds of numbers meet here. The learned ones, the embedding table and WQ, WK, WV and WO, are set in training and fixed afterwards; the others, X, the queries, keys, values, scores, weights and outputs, are computed afresh for every sentence and thrown away after it. Attention learns how to look, never what a particular sentence says.
Only looking back
A language model is trained to predict each token from the tokens before it, so a position must not be able to see the text that follows it, or it could simply read the answer. Its attention is therefore causal: a position may read itself and every earlier position, never a later one. Information in a language model consequently travels in one direction only, from earlier positions to later ones, and whatever stands early in a text is within reach of every position after it.
In symbols, the mask is one more term added to the scores before the softmax:
Q, K, V and dk are as in the formula without the mask; Mij is the entry of the mask in row i, the reading position, and column j, the position read. The mask M adds 0 to the score where position i may read position j, that is where j ≤ i, and −∞ where j comes later; e raised to −∞ is 0, so a later position gets a weight of exactly 0. Everything else is the formula without the mask. To review: the softmax.
Not every attention is causal. A model that reads a whole text at once to understand it, such as BERT, lets every position read every other, before and after (transformer families). And in cross-attention the queries come from one sequence and the keys and values from another, as when a translation model reads the sentence it translates.
Apart from the mask, which decides only who may read whom, nothing in this formula refers to where a position stands: the scores depend on the vectors alone. Shuffle the words before the last position and the last position would receive exactly the same result. The order of the tokens therefore enters separately, through position encoding: the original transformer added to each embedding a vector of sine waves that depends on its position (Vaswani et al., 2017), and most current models rotate queries and keys instead.
A head you can read
The numbers of a real embedding mean nothing one by one, which hides how a head’s rule works. To see it, build a head by hand whose numbers do mean something. Take the prompt “The cat ate it” and give each token a row of four numbers: how much it is a thing, how much a pronoun, how much an action, and its position. Here the head is small, its queries and keys two numbers long, dk = 2. WK makes every key say how much its token is a thing and how much an action; WQ makes a pronoun ask strongly for a thing (the query of “it” is (4, 0)), an action ask more mildly (2, 0), and the other tokens ask for almost nothing. The score of “cat”, whose key is (1, 0.2), for “it” is 4 · 1/√2 = 2.83, the highest, so “it” reads “cat” with a weight of 0.81.
What the names mean, and what they do not
“Query”, “key” and “value” sound as if each vector had a meaning of its own. Mechanically there is nothing more than this: at each position the model has one vector, its row of X on the residual stream, and three matrices read three new vectors from that same row. The formula gives the query and the key the job of deciding where to read and the value the job of carrying what is read, but nothing in it makes a particular query a particular question.
Even the query and the key, taken one by one, mean nothing fixed. The score of position i for position j is
The score sij is the dot product of query qi = xiWQ with key kj = xjWK, which is the row xi times the product of the two matrices WQWKT times the row xj turned on its side (the T is the transpose). To review: dot products and matrix products.
So only the product WQWKT matters. In the head built by hand, doubling every query and halving every key, WQ times 2 and WK times 0.5, changes the query of “it” from (4, 0) to (8, 0) and the key of “cat” from (1, 0.2) to (0.5, 0.2), yet the score stays exactly 2.83, and so does every other. Swapping the two numbers of every query and every key changes all of them again and no score at all. The same holds for any invertible change made to the queries and undone on the keys (weight-space symmetries). The individual queries and keys are therefore not what carries meaning; the product is. The same goes for the value and output matrices, which act only through their product WVWO.
The product can be read. For the head built by hand it is a 4 by 4 table, one row and one column for each of the four input numbers, “is a thing”, “is a pronoun”, “is an action” and the position:
WQWKT is the product of the head’s query matrix and the transpose of its key matrix, 4 by 4 because each has 4 rows, one per number of a row of X. Entry (a, b) says how strongly a position whose row has feature a is drawn to a position whose row has feature b. Only two entries are not zero: a pronoun (row 2) is drawn to a thing (column 1) with strength 4, and an action (row 3) to a thing with strength 2. To review: matrix products.
That table is the head’s whole rule for who reads whom: “a pronoun looks for a thing”. It is written in the features the rows already carry, and the query and key are just two halves of it, in whatever coordinates training happened to choose. Interpretability calls the product the head’s query-key circuit, and the product of value and output matrices its output-value circuit, which says what is moved once the head reads (circuits).
Where the meaning comes from, and how far it reaches
In the head built by hand the matrices were chosen so that the rule is easy to read. In a trained model nobody chooses them. Training changes them, by gradient descent, in whatever direction lowers the error in predicting the next token. If knowing what a pronoun refers to helps predict the words after it, some head’s query-key product drifts towards drawing pronouns to fitting nouns, because the rows already contain features such as “this is a pronoun” or “this is an animal”, put there by the embeddings and earlier layers. A head acquires a meaning only by being trained on data where that meaning helps; before training its products are random and so are its weights. And the meaning settles in the product, not in the two matrices: train the same head twice from different random starts and its queries and keys come out completely different, while the product of the two holds the same rule. So training does give the operations a meaning, but to the pair: it turns two arbitrary multiplications into one learned rule for who reads whom, and a third into a learned choice of what is carried.
Claims such as “attention resolves what it refers to” are therefore not claims about attention in general. They are findings about particular heads in particular trained models, made in two steps: first look at a head’s weights or its attention patterns and form a hypothesis, then test it by intervening, for example by switching the head off and checking that the behaviour breaks. Some heads have such a clean story: induction heads, which copy what followed the last occurrence of the current token, or heads that attend to the previous token. Many heads have none, and one behaviour is often spread over several heads and layers.
A last caution follows from the same view. A large attention weight shows where a head reads, not why the model reached its answer: the value read may be small, later layers may ignore it, and other heads may carry the same information. Jain and Wallace (2019) put it as “attention is not explanation”, and Wiegreffe and Pinter (2019) replied with the conditions under which it can be. Attention weights are a place to start looking, and an experiment is what turns a look into an explanation (reading and writing hidden states).
What training does to a head
Training adjusts every learned number of the model to lower one quantity: the error L in predicting the next token (loss functions). For a head these numbers are WQ, WK, WV and WO. For each example the error is passed backwards through the head by the chain rule, and each matrix moves a little in the direction that would have lowered it (gradient descent). Nothing in this process speaks of pronouns or nouns; whatever rule a head ends up with has to come out of it. Two different signals reach the head, one for what it brings back and one for where it reads.
Call u the direction in which the output oi of position i should have moved to lower the error. What to bring back is the simpler signal: the output is a weighted average of the values, so the values and WO are nudged towards carrying whatever pushes the output along u, much as a least-squares fit is. Where to read reaches the scores through the softmax, and for the score of a source j it is
Here i is the reading position and j a position it reads; aij and sij are the weight and the score of j for i; vj is j’s value; oi is the head’s output at i; and u is the direction in which oi should have moved to lower the error, the gradient of the error with respect to the output with its sign reversed. The change in the error L for a small change in the score sij (∂ is a partial derivative) is minus the current weight aij times the difference between how much source j’s value vj would help, u·vj, and how much the current output oi, the average of all the values read, helps, u·oi. Gradient descent moves the score against the derivative, so the score rises by an amount proportional to aij(u·vj − u·oi): it rises when the source would help more than the current mix, and falls when it would help less. To review: derivatives, the chain rule and the softmax.
So a head’s attention drifts towards the positions whose content would have helped more than what it read: sources that pay off are reinforced. Two consequences follow from the formula. First, the change is multiplied by the current weight aij: a position that receives almost no attention gets almost no signal, even if it holds exactly what is needed. That is one reason scores are kept moderate early in training, by the division by √dk and by small starting weights: a saturated softmax stops learning. Second, where and what depend on each other. Reading a position helps only if its value carries something useful, and a value learns to carry something only from positions that are read, so the two parts of a head grow together. This is one reason abilities can appear suddenly in training: induction heads form in a short phase change (Olsson et al., 2022), because the previous-token head they rely on must exist first.
Seen through the head’s table, each update adds to WQWKT, for every reader and source, the reader’s features times the source’s features times that source’s gradient. The entry (pronoun, thing) therefore grows whenever pronoun readers meet thing sources and reading the thing helped, and the rule “a pronoun looks for a thing” is built up from such updates, one example at a time. Researchers watch the same process in real models: the loss, a head’s weights or its table over the steps of training, how spread out its attention is, and the moment a behaviour appears, tested by switching heads off at saved checkpoints.
Why the scores are divided by √dk
The division by √dk looks like a detail, but without it attention would stop learning as models grew wider. The reason is the size of a dot product. If the dk numbers of a query and of a key are independent, each with mean 0 and variance 1, their dot product is a sum of dk such products:
q and k are a query and a key of dk numbers, and qr and kr their r-th numbers, assumed independent, with mean 0 and variance 1; Var is the variance. The variance of the dot product of q and k is the sum of the variances of its dk terms qrkr, each of which is 1, so it is dk, and the typical size of a score grows like √dk. Dividing by √dk brings the variance back to 1 at any width. To review: variance, and the variance of a sum of independent terms.
Large scores mean large gaps between scores, and large gaps make the softmax saturate: it puts nearly all the weight on one position, and its slopes, through which training adjusts the queries and keys, become tiny. With the division, the scores keep the same spread at any width, and the softmax stays in the range where it still responds. Vaswani et al. give this argument for the scaling.
Several heads
A single head gathers one kind of information at a time. But a word may need several things at once: the word just before it, to know its grammatical role; a related word far back, to know what it refers to; the beginning of the sentence, to know the topic. Multi-head attention runs H attentions side by side, the heads, each with its own matrices, joins their outputs and mixes them with one more learned matrix:
Head h is an attention with its own query, key and value matrices WQ,h, WK,h and WV,h, each of shape (d, d/H), applied to the matrix X of all positions’ vectors, of shape (T, d), T being the number of positions and d the width; H is the number of heads; each head’s output has shape (T, d/H). The outputs of the H heads are placed side by side (the square brackets), giving shape (T, d) again, and multiplied by the output matrix WO, of shape (d, d), which mixes what the heads found into one vector per position; MultiHead(X) is the result. To review: matrix products.
Each head works in a smaller space: the width is split between the heads, dk = d/H, so with a width of 4,096 and 32 heads each head’s queries, keys and values have 128 numbers, and the total work is about the same as for one large head. In the sentence about the animal, the six numbers are split between three heads of two numbers each, each head with its own matrices of six by two numbers. For “it”, the three heads read differently: head 1 puts 0.75 of its weight on “animal”, head 2 puts 0.75 on “because”, the word just before, and head 3 spreads its weight over the whole sentence, never more than 0.22 on one word. Each head gives two numbers; placed side by side they make six again, which WO mixes and the row of “it” receives.
Studies of trained models find heads with recognisable jobs: some attend to the previous token, some to the matching bracket or quote, some copy a word that appeared earlier after the same context (induction heads, Olsson et al., 2022), though many heads do things that are harder to name.
Many current models let several query heads share one key head and one value head, to make the memory of keys smaller: grouped-query attention, and its extreme, multi-query attention. Multi-head latent attention instead stores one small latent vector per token and rebuilds every head’s keys and values from it.
Any number of tokens, all at once
Nothing learned in attention depends on the number of tokens. WQ has shape (d, dk) however long the prompt is; a prompt of T tokens simply gives Q, K and V with T rows, a T × T matrix of scores and T rows of output. The same weights therefore serve a prompt of 4 tokens or of 100,000. The limits lie elsewhere: in the positions the model met in training, its context window, and in the memory for the T × T scores.
And all T rows are computed at once. A recurrent network such as a GRU reads a text one token after another: its state after token t is computed from its state after token t − 1, so T tokens take T steps, one after the other, and what the first token said reaches the last only through all the states in between. Attention has no such chain. Every step above is a matrix product over all the rows together, which a GPU computes in parallel, and any token reads any earlier token directly, in one step. In training, where the whole text is known, the mask lets a model learn to predict every next token of a text in a single pass. This is the main reason transformers replaced recurrent networks (Vaswani et al., 2017). The price is the T × T scores, whose work and memory grow with the square of the length. When it generates, a model still writes one token at a time, but it keeps the keys and values of the earlier tokens (the KV cache), so that each new token only computes its own row.
The cost, and how it is reduced
Each position scores every position it may read. For a text of n positions that is n × n scores per head, nearly half of them masked: the work grows with the square of the length.
Each of the ways around this cost has a page of its own. While a model generates text, the keys and values of earlier tokens are computed once and kept, in the KV cache, which grouped-query attention and multi-head latent attention make smaller. FlashAttention computes exactly the same attention block by block, without ever storing the full matrix of scores. Sparse attention lets each position read only some positions, a window of recent ones or a chosen few. Linear attention changes the similarity so that the cost grows only with the length, and blocks that replace attention by a memory of fixed size are beyond attention.
To sum up: attention lets each position gather information from the others by matching queries with keys and averaging values; the causal mask makes information flow only forward; the scaling keeps the softmax responsive; several heads gather several kinds of information at once; and the cost grows with the square of the length, which the variants of attention address in different ways.
On the path DNA-Socket
Causal attention is what lets a model use an input placed early in its prompt. In DNA-Socket’s prompts, the slots that carry the gene stand before the question, the options and the final position, where the model’s answer is read (answering a multiple-choice question), so every one of these later positions can read the slots. Whether they actually do, and how much, depends on what they find there, because attention weights follow the match between queries and keys: being within reach is not the same as being read.
In Qwen3.5-4B, the full-attention blocks have 16 query heads and 4 key-value heads, each head of size 256 (from the model’s card): grouped-query attention, with four query heads sharing each key-value head. The card calls them gated attention: their output is multiplied, number by number, by a gate between 0 and 1 that is computed from the position’s own vector (Qiu et al., 2025). Their position encoding is rotary but partial, over 64 dimensions: only part of each query and key is rotated by its position. These attention blocks are one in every four; the other three are Gated DeltaNet blocks, a kind of linear attention (beyond attention).
Reading the slots is not automatic. In J-WRITE, the arm that tested the study’s first idea, a trained connector wrote information from the gene’s DNA into the slots of Qwen3.5-4B as a sparse code: a combination of only a few of the word directions of the model’s Jacobian lens. The model did not use it in any variant tried; the written information “stayed at the DNA slots and barely reached the answer position”. They are explained elsewhere: DNA on its own page, trained connectors in connecting encoders, the Jacobian lens in reading hidden states, and J-WRITE in the first idea.
On the path Attention paper
In the paper. This is the paper’s “scaled dot-product attention” (section 3.2.1). Bahdanau’s earlier attention computed its scores with a small network (additive attention); the paper chose the dot product because a whole table of scores is then one matrix product, fast on a GPU. Without the scaling, dot products did worse than the additive kind for large dk, and the paper names the sharp softmax as the reason. In the model dk = 64, and each attention layer runs eight of these side by side (multi-head attention). The decoder’s self-attention is masked with −∞ for the positions after each word.
Test yourself
Every query of a head is doubled and every key halved. What happens to the head’s weights, and what does that say about what a query means?
Nothing: every score is the dot product of a query with a key, so doubling one and halving the other leaves it unchanged. Only the product of the query and key matrices decides where the head reads; the queries and keys on their own have no fixed meaning (weight-space symmetries).
Why can the last position of a prompt use information placed near its start, while the first position cannot use information placed at the end?
Causal attention lets every position read itself and all the positions before it, never a later one. Being readable does not guarantee being read, though: the weights depend on how well the reading position’s queries match the keys of what is there.
What does dividing the scores by √dk do?
It keeps the scores at the same spread whatever the width of the heads. Without it, the variance of a dot product grows with dk, the gaps between scores grow, and the softmax saturates: almost all the weight goes to one position, and the slopes through which training adjusts queries and keys become tiny.
Where it leads
Kept in this browser only, never sent.
Paths through it
- DNA-Socketstep 4 of 22Follow this path
- Attention paperstep 6 of 17Follow this path
- Inside a language modelstep 3 of 4Follow this path