Chapter 8

Attention and transformers

A transformer1 is a neural network that turns the embeddings of a text into new vectors, one for each position, with a stack of blocks of the same form. Each block has two parts: attention, which lets each position read the vectors of other positions, and a feed-forward network, which works on each position alone.

For example, the model of Section 7.1 has 32 blocks2. Each block turns the 8 vectors3 of the text The ride of 3 km cost $ into 8 new vectors of 4096 numbers. The last vector of the last block gives the logits.

Attention is the only part where the positions exchange numbers. Its cost grows with the square of the length of the text, so long texts are expensive to train on and to read.

8.1Attention

Consider the position of ␣$ in the above text. To predict the price, its vector needs the distance 3, which is three positions earlier. A layer of Section 3.1 changes each vector on its own, so it cannot bring the distance to the position of ␣$.

A straightforward way is to give each position the average of the vectors up to it, as for the text embeddings of Section 6.3. However, the average gives the same weight to each position. For example, 3 gets 1/8 of the average at ␣$, as much as The.

The idea is to take a weighted average, where each position chooses the weights by what it looks for. Attention is the part of a block that gives each position a weighted average of the vectors of the positions that it reads.

Each position calculates three vectors from its own vector: a query, a key and a value. Each of them is the product of a weight matrix and the vector, as in a layer with no bias and no activation function. The query describes what the position looks for, the key what it holds, and the value what it gives to the positions that read it.

Let qiq_i denote the query of position ii, and let kjk_j and vjv_j denote the key and the value of position jj. The score of position jj for position ii is as follows: sij=qi⋅kjdks_{ij} = \frac{q_i \cdot k_j}{\sqrt{d_k}} where dkd_k is the number of numbers in each query and key. The attention weights wijw_{ij} are the softmax of the scores of the positions jj that ii reads (see Section 7.2). The output of position ii is ∑jwijvj\sum_j w_{ij} v_j. The attention weights are not parameters: the model calculates them again for each text.

As an example, suppose that dk=4d_k = 4 and that the query of ␣$ is (1, 1, 1, 1). The following table shows the key of each position, its score and its attention weight:

token key score attention weight
The (−1, −1, −1, −1) −2 0.01
␣ride (−1, −1, −1, −1) −2 0.01
␣of (−1, −1, −1, −1) −2 0.01
␣ (−1, −1, −1, −1) −2 0.01
3 (1, 1, 1, 1) 2 0.55
␣km (1, 1, 1, 0) 1.5 0.33
␣cost (1, 1, −1, −1) 0 0.07
␣$ (−1, −1, −1, −1) −2 0.01

For example, the score of 3 is (1+1+1+1)/4=2(1 + 1 + 1 + 1)/\sqrt{4} = 2. The sum in the softmax is e2+e1.5+e0+5e−2≈13.55e^2 + e^{1.5} + e^0 + 5 e^{-2} \approx 13.55, so the attention weight of 3 is 7.39/13.55≈0.557.39 / 13.55 \approx 0.55. The output of ␣$ is then 0.55 times the value of 3, plus 0.33 times the value of ␣km, and so on. Thus, more than half of the attention weight goes to the distance.

The three matrices are parameters, and the training changes them together with all other parameters. Nothing in the model says that ␣$ needs the distance. Gradient descent finds a query and a key that match in this way because they make the loss of the next token smaller.

Note that the division by dk\sqrt{d_k} keeps the scores from growing with dkd_k. Without it, queries and keys with many numbers give large scores, and the softmax gives almost all of the attention weight to one position. Its derivatives are then almost 0, and the training barely changes the attention weights4.

8.2Reading earlier positions

Causal attention5 is attention in which each position reads only itself and the positions before it, and language models use it. The model sets the scores of the later positions to −∞-\infty, so their attention weights are e−∞=0e^{-\infty} = 0. For example, the position of ␣ride reads The and itself, but not ␣of.

The following picture shows which positions read which in the above text, where each row is a reading position and its shaded cells are the positions that it reads:

The ␣ride ␣of ␣ 3 ␣km ␣cost ␣$ The ␣ride ␣of ␣ 3 ␣km ␣cost ␣$

The row of ␣$ has 8 shaded cells, one for each row of the above table. The row of The has only one. In all, 1 + 2 + … + 8 = 36 of the 64 cells are shaded.

The reason for this rule is the training. One pass through a training text gives the loss at every position, where each position predicts the token after it (see Section 7.2). If a position could read the next position, its vector would contain the token that it has to predict.

For example, in the training text The ride of 3 km cost $9., the position of ␣$ predicts 9. With causal attention, it cannot read the position of 9.

Thus, in every block, the vector at a position depends only on the tokens up to that position. When the model writes a new token, the vectors of the earlier positions do not change. Chapter 10 shows how the program reuses them.

An embedding model reads a whole text and writes nothing (see Section 6.3), so it has no next token to hide. In this case, we can let each position read every position, and many embedding models do so6. All 64 cells of their picture are shaded. The embedding of the text is often the average of the vectors of the last block7.

8.3Positions

Attention by itself does not see the order of the tokens. When each position reads every position, the output of a position depends on its own token and on the keys and values that it reads, but not on their order.

For example, the position of bit reads the same five tokens in the dog bit the man and in the man bit the dog. It gets the same output in both texts. An embedding model would then give the two texts the same embedding, as the average of Section 6.3 does8.

A straightforward way to add the order is to give each position its own vector of dd numbers and to add this vector to the embedding of the token at that position9. The position vectors can be learned by the training, like the embeddings. For example, a model can have learned vectors for 1,024 positions10. However, such a model has no vector for position 1,025, so it cannot read a longer text.

Rotary position embedding11 is a method that rotates the query and the key of each position by an angle that grows with the position12. A rotation does not stretch a vector, so the dot product of a query and a key changes only through the angle between them. Thus, for the same two tokens, the score depends on their distance, not on where they are in the text.

As an example, suppose that dk=2d_k = 2, that the angle grows by 20° per position, and that a query and a key are both (1, 0) before the rotation. The following picture shows the query at position 8 and the key at position 5 on the left, and the query at position 4 and the key at position 1 on the right:

q8 k5 60° q4 k1 60°

In both cases, the angle between the query and the key is 60°, and their dot product is cos⁡60°=0.5\cos 60° = 0.5. For the distance 1, for example at positions 6 and 5, the angle is 20°. The dot product is then cos⁡20°≈0.94\cos 20° \approx 0.94.

Note that a rotation exists for every position, so the method has no last position. However, a model has seen only the distances in its training texts, and it predicts the tokens of longer texts badly13. In practice, a model is trained further on long texts before it reads them (see Section 8.5).

8.4The block

The feed-forward network of a block consists of two layers of Section 3.1, which each position goes through on its own. The first layer turns the dd numbers of the vector into more numbers and applies an activation function. The second layer turns them back into dd numbers. For example, in the model of Section 7.1, the first layer gives 14,336 numbers14, 3.5 times d=4096d = 4096.

A block runs attention and then the feed-forward network. Each of the two parts adds its output to the vector that it reads, instead of replacing the vector15. Each part then only has to learn a change of the vector. The following picture shows a block for the first three positions of the above text, without the additions:

attention feed-forward The ␣ride ␣of

Attention is the only part with lines between the positions. Each line goes from a position to the same position or to a later one. The feed-forward network has one box for each position, because each position goes through it alone.

A head is one of several attentions that a block runs side by side on the same vectors, and each head has its own three matrices and shorter queries, keys and values. For example, the above model has 32 heads with queries of 128 numbers, and 32 · 128 = 4096. Each head divides its scores by 128\sqrt{128}, because dk=128d_k = 128. A fourth matrix turns the 32 outputs into one vector of 4096 numbers.

The heads learn to read different things. For example, in a model of 2018 whose positions read every position, one head found the object of a verb more than 75% of the time16.

Thus, a block of the above model has 7 weight matrices. Attention has 4 of them: the matrices of the queries, the keys and the values, each for all heads together, and the matrix that joins the heads17. The feed-forward network has the other 3. The following table shows their numbers of weights:

part matrices weights
attention 4 41,943,040
feed-forward network 3 176,160,768
block 7 218,103,808

The feed-forward network has about four fifths of the weights of a block18.

8.5The context window

The context window of a model is the largest number of tokens that it can read at once, the prompt and the written tokens together. For example, the model of Section 7.1 has a context window of 8,192 tokens. A later version with blocks of the same sizes has a context window of 131,072 tokens19. In practice, the largest models of two large providers have context windows of about 1,000,000 tokens20.

An API refuses a request whose prompt alone is longer than the context window. When an answer reaches the end of the window, the API stops it21. Chapter 18 shows how well a model uses a long prompt.

Attention at position ii calculates ii scores, so a text of nn tokens needs 1+2+…+n=n(n+1)/21 + 2 + \dots + n = n(n + 1)/2 scores in each head of each block. For example, the 8 tokens of the above text need the 36 scores of the shaded cells of Section 8.2. A text twice as long needs about 4 times as many scores: 16 tokens need 136.

Thus, the time complexity of attention is O(n2)O(n^2) for a text of nn tokens. The weight matrices take O(n)O(n) time, because each position goes through each of them once22.

We can compare the two in the above model. The weight matrices of a block do 218,103,808 multiplications for each position, one for each weight. Attention at position ii does 2⋅4096⋅i2 \cdot 4096 \cdot i multiplications: 4096⋅i4096 \cdot i for the scores of the 32 heads, and as many for the weighted averages of the values. The following table shows the share of attention in the multiplications of a block for a text of nn tokens:

tokens nn 1,024 8,192 32,768 131,072
share of attention 2% 13% 38% 71%

For example, for 8,192 tokens, attention does 4096 · 8192 · 8193 multiplications and the weight matrices 218,103,808 · 8192, so attention has 13% of the sum. The two shares are equal at about 53,000 tokens. This is the extra cost of a long text that the estimate of 2 operations per parameter in Section 3.3 leaves out.

For this reason, the pretraining (see Section 9.2) can leave long texts to a late stage. For example, a model can be trained on texts of 8,192 tokens first, and then on longer texts until it reads 131,072 tokens23.

Some models let some or all of their blocks read only the last ℓ\ell positions24. Such a block takes O(nℓ)O(n\ell) time instead of O(n2)O(n^2). On the other hand, it cannot read a token that is more than ℓ\ell positions back, and the token can reach the position only through several blocks.


  1. The transformer was published in 2017 as a model for translation: Attention Is All You Need. Its two stacks of blocks read a text and write its translation, and a language model has only the second kind, without its attention to the first stack.↩︎

  2. The numbers are those of Llama 3 8B, as in Section 7.1: Meta-Llama-3-8B. The Llama 3 Herd of Models gives the same 32 layers, the model dimension 4,096, the feed-forward dimension 14,336, 32 attention heads and 8 key and value heads.↩︎

  3. Llama 3 also puts the special token <|begin_of_text|> before the text, so it reads 9 positions.↩︎

  4. The paper on the transformer suggests this reason in its Section 3.2.1: “for large values of dk, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients.” Its heads have queries of 64 numbers, so they divide by 8.↩︎

  5. The paper on the transformer does this in its Section 3.2.3, “masking out (setting to −∞) all values in the input of the softmax which correspond to illegal connections.”↩︎

  6. BERT, published in 2018, lets each position read every position. Its paper says that the earlier GPT uses attention “where every token can only attend to context to its left”: BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding. In 2024, NV-Embed turned a language model into an embedding model and removed its causal attention for the training: NV-Embed.↩︎

  7. For example, Sentence-BERT tried the average, the vector of a special token and the maximum of each number over the positions, and it uses the average by default: Sentence-BERT, published in 2019. An embedding model with causal attention often takes the vector of the last position instead, because only the last position has read the whole text. For example, the embedding models of Text and Code Embeddings by Contrastive Pre-Training, cited in Section 6.3, add a special token at the end of the text and take its vector in the last block.↩︎

  8. With causal attention, each position reads a different number of tokens, and a model can learn the order from this alone. A study of 2023 trained such models with no positions at all, and on its tasks they did as well as models with positions, or better: The Impact of Positional Encoding on Length Generalization in Transformers.↩︎

  9. The transformer of 2017 adds fixed vectors made of sines and cosines. Its Section 3.5 gives the reason: “Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence.”↩︎

  10. GPT-2, published in 2019, raised the number of positions “from 512 to 1024 tokens”: Language Models are Unsupervised Multitask Learners. Its configuration file gives "n_positions": 1024: config.json. The library transformers keeps the position vectors in a learned table, wpe: modeling_gpt2.py.↩︎

  11. The method was published in 2021: RoFormer: Enhanced Transformer with Rotary Position Embedding. Its Section 3.1 asks that the dot product of a query and a key depend on the two tokens and on “their relative position m − n” only.↩︎

  12. In practice, the method cuts the query and the key into pairs of numbers, and each pair turns at its own speed, from fast for the first pair to slow for the last pair. In the paper, the pair pp, counted from 0, turns by b−2p/dkb^{-2p/d_k} radians per position, with bb = 10,000. Llama 3 uses bb = 500,000 and dk=128d_k = 128: The Llama 3 Herd of Models.↩︎

  13. In a study of 2023, a model trained on texts of 2,048 tokens and run on longer texts got a loss “comparable to untrained models”: Extending Context Window of Large Language Models via Positional Interpolation.↩︎

  14. Its activation function, SwiGLU (see Section 3.1), multiplies the results of two matrices of 4096 · 14,336 numbers, so the feed-forward network has three matrices: GLU Variants Improve Transformer, published in 2020 by N. Shazeer. The transformer of 2017 has d=512d = 512, 2048 numbers in the middle and the ReLU.↩︎

  15. This way of joining layers was published in 2015 for image models: Deep Residual Learning for Image Recognition. LLaMA also scales the input of each part with RMSNorm “to improve the training stability”: LLaMA: Open and Efficient Foundation Language Models.↩︎

  16. The model is BERT. The study found heads “that find direct objects of verbs, determiners of nouns, objects of prepositions, and objects of possessive pronouns with >75% accuracy”: What Does BERT Look At? An Analysis of BERT’s Attention, published in 2019.↩︎

  17. The matrices of the keys and the values have only 4096 · 1024 numbers each, because the model has 8 heads of keys and values, and each of them serves 4 heads of queries. This grouped-query attention was published in 2023: GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. Chapter 10 shows why fewer keys and values help.↩︎

  18. The 32 blocks have 6,979,321,856 of the 8,030,261,248 parameters that Hugging Face gives for the model, and the embedding matrix and the output matrix of Section 7.1 have 525,336,576 each. The other 266,240 parameters are the scales of the RMSNorm, two in each block and one after the last block.↩︎

  19. Llama 3.1 8B: Llama-3.1-8B. Its configuration file gives "max_position_embeddings": 131072 and "original_max_position_embeddings": 8192. GPT-2 has a context window of 1,024 tokens.↩︎

  20. Anthropic’s documentation gives 1,000,000 tokens for its current models: Context windows. OpenAI’s documentation gives 1.05 million for its current models: Models.↩︎

  21. Anthropic’s API returns the error “prompt is too long” when the input alone is longer than the window. On Claude 4.5 and newer models, it stops the answer with the stop reason model_context_window_exceeded, and earlier models refuse a request whose input and maximum number of output tokens do not fit: Context windows. OpenAI’s documentation says that the context window “includes input, output, and reasoning tokens”: Conversation state.↩︎

  22. FlashAttention calculates the scores in parts and never stores all of them at once. Its extra memory is “linear instead of quadratic in the sequence length”, but its arithmetic still grows with the square of the length: FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, published in 2022.↩︎

  23. Llama 3 405B was trained in this way, and its paper gives the reason in Section 3.4.2: “We do not train on long sequences earlier because the compute in self-attention layers grows quadratically in the sequence length.” The Llama 3 Herd of Models.↩︎

  24. For example, Mistral 7B lets each block read the last 4,096 positions, and its paper notes that the stack of blocks reads further than one block: Mistral 7B. Gemma 3 has 5 blocks that read the last 1,024 positions for each block with full attention: Gemma 3 Technical Report.↩︎