Lecture 17: Attention and Transformers

From fixed-length recurrent summaries to soft attention, learnable self-attention, and the Transformer block.

1. From recurrent summaries to attention

The previous lecture built recurrent neural networks (RNNs). An RNN reads a sequence one token at a time and carries information forward in a hidden state, and the same weights are reused at every step . This lecture follows a path from that architecture to the one behind GPT, in three steps.

GPT itself is the subject of the next lecture. This lecture builds the Transformer.

Scope. These notes follow the Lecture 17 slides from November 5, 2026, in slide order. Figures on the slides that come from published papers and textbooks are described in the text and are not reproduced. The three diagrams in these notes were redrawn in simplified form from the corresponding slides.

The motivating task is machine translation. Translating “Where is the library?” into Spanish gives “¿Dónde está la biblioteca?”, and translating “Where is the huge public library?” gives “¿Dónde está la enorme biblioteca pública?”. In both sentences the article “the” becomes “la” because “biblioteca” is a feminine noun, so the correct translation of one word depends on another word that may be several positions away. In general, translating a single word can require the whole sentence.

A standard encoder-decoder RNN handles this by compressing the source sentence into one fixed-length vector, the final hidden state of the encoder, and asking the decoder to produce the whole translation from that vector. The fixed-length vector is a bottleneck. All of the information in the sentence has to pass through it, which makes long-range dependencies hard for RNNs.

2. Soft attention in sequence-to-sequence models

The original idea

Attention was first developed for translation by Bahdanau et al. . Instead of forcing the decoder to rely on one summary vector, the model performs a soft search over the source sentence and retrieves the parts that are relevant to the target word it is about to produce.

The benefit is clearest on long sentences. The slides reproduce a figure from the paper that plots translation quality, measured by the BLEU score, against sentence length. The two encoder-decoder baselines without attention lose quality steadily as the sentences get longer. The attention model trained on sentences of up to 50 words stays roughly flat out to 60 words.

The construction uses two RNNs.

Hard versus soft attention

There are two ways to let a model choose where to look.

Hard attention makes a zero-one choice: the model selects some locations and ignores the rest. A discrete choice is not differentiable, so it cannot be trained by ordinary backpropagation and needs other techniques such as reinforcement learning. In exchange, a hard selection may be easier to interpret, because the model states exactly which input it used. The slides show an example from Lei et al. , in which a model that rates beer reviews selects the phrase describing the color of the beer as its justification for the rating of its appearance.

Soft attention replaces the discrete choice with a weighted average. Every location receives a nonnegative weight, and the weights sum to one. A weighted average is differentiable in the weights, so the whole model can be trained end to end with gradient descent .

The weights can be inspected after training. The slides show them for an English-to-French translation as a grid, with one row per French word and one column per English word. Most of the weight lies near the diagonal, because the two languages mostly share word order. The weight leaves the diagonal exactly where the order differs: “European Economic Area” is translated as “zone économique européenne”, and the weights for those three words run in the opposite direction. The rest of the lecture uses soft attention.

Under the hood: the context vector

Let s_{t-1} be the decoder state before output step t, and let h_1,\dots,h_T be the encoder hidden states. The slides write the source index as a primed t; these notes use j to keep the two indices visually distinct. Soft attention has three steps. First, a score measures how well each encoder state matches the current decoder state. In the lecture, the score is the output of a small neural network that takes the two vectors as input and is trained together with the rest of the model:

e_{tj}=\mathrm{NN}(s_{t-1},h_j).

Second, a softmax turns the scores into weights:

\alpha_{tj}=\frac{\exp(e_{tj})}{\sum_{m=1}^{T}\exp(e_{tm})}.

Third, the context vector is the weighted average of the encoder states:

c_t=\sum_{j=1}^{T}\alpha_{tj}h_j.

Because the weights are nonnegative and sum to one, c_t is a convex combination of the hidden states. It always lies between them and never outside their range. With attention added, the decoder still looks like a standard RNN, except that it takes a context vector as an extra input at every step. Since each step receives its own context vector, the model is no longer limited to a single summary of the source sentence.

Diagram of soft attention: encoder hidden states are combined by a weighted sum into a context vector that feeds the decoder state.
Figure 1. Soft attention builds a context vector for each output step. The previous decoder state and each encoder hidden state are scored and passed through a softmax to give the attention weights. The weighted sum of the encoder states is the context vector, which enters the decoder state that emits the next word. The diagram shows a single output step and omits the inputs to the two RNNs.

Example: soft attention for image captioning

The same mechanism applies outside translation. In image captioning, the goal is to map an image to a sentence. Three tools are already available.

A direct combination passes the image through a CNN to obtain one feature vector, uses it to initialize an RNN, and lets the RNN emit a distribution over the vocabulary at each step. The difficulty is the same bottleneck as before. The RNN looks at the whole image only once, although different words of the caption refer to different parts of the image.

Soft attention removes the bottleneck . The CNN now produces a grid of L feature vectors, one per image region, each of size D. At every step the decoder state produces two distributions: one over the vocabulary, which gives the next word, and one over the L locations, which gives the attention weights. The weighted combination of the region features under those weights is a single vector of size D. It is fed into the next decoder step together with the previous word. The roles are identical to the translation case, with image regions in place of source words.

3. Self-attention

Removing recurrence

In the original mechanism, attention is an addition to a recurrent model. The encoder and decoder still process their sequences one step at a time. The slides pose the natural question: if attention already ties the inputs together across the sequence, is the recurrence still needed? In the diagram on the slides, both recurrent parts are crossed out, the chain of decoder states and the bidirectional encoder.

The answer of Vaswani et al. is that the recurrence is not needed . In self-attention, a sequence attends to itself. Each token builds its new representation as a weighted average over all tokens of the same sequence, and no recurrent state is carried from one position to the next.

A parameter-free form

The simplest version has three steps and no learnable parameters. Given token embeddings x_1,\dots,x_T and a current input x_i:

  1. Compute dot products. The score between positions i and j is x_i^\top x_j.
  2. Normalize with a softmax. The scores for a fixed i are turned into weights a_{ij} that sum to one over j.
  3. Compute the output. The output is the weighted sum of the embeddings.
a_{ij}=\frac{\exp(x_i^\top x_j)}{\sum_{m=1}^{T}\exp(x_i^\top x_m)},\qquad A_i=\sum_{j=1}^{T}a_{ij}x_j.

The output A_i is a context-aware embedding of token i: it starts from the original embeddings and mixes in the tokens that are most similar to x_i.

This form has no learnable parameters. The weights are fully determined by the embeddings, so it is not very useful on its own.

Learnable queries, keys, and values

To make self-attention learnable, three weight matrices project each input embedding into three spaces:

q_i=W^q x_i,\qquad k_i=W^k x_i,\qquad v_i=W^v x_i.

The three projections give each token three roles.

The slides summarize the mechanism as “queries select keys, and keys unlock values.” The score now compares a query with a key, and the weighted sum is taken over values:

a_{ij}=\frac{\exp(q_i^\top k_j)}{\sum_{m=1}^{T}\exp(q_i^\top k_m)},\qquad A_i=\sum_{j=1}^{T}a_{ij}v_j.

As in the parameter-free form, the dot product is a measure of similarity or compatibility, and this kind of scoring is called multiplicative attention. For each query, the model learns which key-value pairs it should attend to. The mechanism is called self-attention because the query and the key-value pairs are computed from the same input sequence, whereas in Section 2 the query came from the decoder and the keys and values came from the encoder.

The three matrices are trained by gradient descent, which supplies the learnable parameters that the basic form lacked.

Dimensional analysis

Each token is embedded in a continuous space of size d_e. The projections map it to a query of size d_q, a key of size d_k, and a value of size d_v, and all three output sizes are design choices. If an embedding is treated as a row vector of shape 1\times d_e, then W^q has shape d_e\times d_q, W^k has shape d_e\times d_k, and W^v has shape d_e\times d_v. Each attention weight is a single number, and the output for one token has shape 1\times d_v.

One constraint applies. The dot product between a query and a key is defined only when the two vectors have the same length, so d_q=d_k is required. The value size is free.

The original Transformer uses d_e=512, d_q=d_k=64, and d_v=64. It also uses 8 attention heads, which play the role of channels, and 8\times 64=512, so everything ends up with the same dimension as the input.

4. Multi-head attention and the matrix form

Multiple heads

A single set of projections produces a single pattern of weights. Multi-head attention applies self-attention several times in parallel, in the same way that a convolutional layer applies several kernels to produce several channels. Each head has its own W^q, W^k, and W^v, and the results are concatenated . Because the projections differ, different heads can attend to different parts of the sequence.

The shapes work out as follows. One head returns a matrix of shape T\times d_v, with one row per token. Concatenating h heads gives shape T\times(h\,d_v), and a final linear layer is applied to the concatenation. In the original Transformer the input has shape T\times 512 and d_v=512/h=64, so the output of the multi-head layer has the same shape as its input.

Self-attention in matrix form

The per-token formulas can be written for the whole sequence at once. Stack the embeddings as the rows of X\in\mathbb R^{T\times d_e}. Because the tokens are rows, the projections multiply from the right:

Q=XW^q,\qquad K=XW^k,\qquad V=XW^v.

One attention head is then

A=\mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V,

where the softmax is applied to each row separately. Figure 2 shows the shapes involved.

Diagram of the matrix shapes in one attention head: queries times transposed keys gives a square score matrix, which multiplies the values to give the output.
Figure 2. Shapes in one attention head. The product of the queries and the transposed keys is a square matrix with one score for every pair of tokens. After scaling and a row-wise softmax, it multiplies the values to give one output row per token. The diagram shows shapes only and does not show the projections that produce the three matrices.

The table lists what each matrix holds.

QuantityShapeMeaning
QT\times d_kone query per token
K^\topd_k\times Tone key per token, as columns
QK^\topT\times Tscores of every token against every token
VT\times d_vone value per token
AT\times d_vrow i is the context-aware embedding of token i

This is the same computation as in Section 3, carried out for all T tokens at once. It consists of a few matrix multiplications, which is why it runs efficiently on GPUs.

Why the scores are scaled

Dividing by \sqrt{d_k} keeps the dot products from growing with the dimension, so that the softmax does not saturate. A dot product is a sum of d_k terms, so its typical size grows with d_k. Large scores push the softmax toward a one-hot output, in which almost all of the weight sits on one position. Scaling keeps the scores in a range where the softmax remains responsive when d_k is large.

The quadratic cost

The score matrix QK^\top has one entry for every pair of positions, so attention needs O(T^2) memory and computation in the sequence length T. Doubling the context multiplies the work by four. This quadratic growth is the main cost of replacing recurrence with attention.

What trained heads attend to

The slides close this part with a figure from Vaswani et al. that shows attention weights in a trained model, taken from the encoder self-attention in layer 5 of 6. The weights are drawn for the single word “making” in a long English sentence, with a different color for each head. Many of the heads attend from “making” to the distant words “more difficult”, which complete the phrase that the verb begins. This is the kind of long-distance dependency that motivated attention in Section 1, and it is resolved here in a single step instead of through many recurrent updates.

5. The Transformer

Encoder and decoder

The Transformer of Vaswani et al. keeps the encoder-decoder layout of the translation models in Section 2 and builds both halves from attention .

The encoder embeds the input tokens, adds a positional encoding, and passes the result through a stack of N identical blocks. Each block applies multi-head self-attention and then a feed-forward network. Inside encoder self-attention, the new representation of a token is computed from all tokens of the input. For the second token, for example, its query is compared by dot product with the key of every token, the softmax turns the scores into weights, each value is multiplied by its weight, and the sum is passed to the feed-forward network.

The decoder embeds the output tokens, shifted right by one position, and passes them through its own stack of blocks. Each decoder block has three parts: masked self-attention over the output tokens, attention over the encoder output, and a feed-forward network. Decoder self-attention is the same computation as in the encoder, except that the positions after the current token are blocked out. The attention over the encoder output plays the role that the context vector played in Section 2. A final linear layer and a softmax turn the decoder output into probabilities over the vocabulary.

Inside a Transformer block

A block has two sublayers, and each is wrapped in the same pattern: normalize, transform, and add the result back to the input. In the form shown on the slides,

h=x+\mathrm{MultiHead}(\mathrm{LN}(x)), \mathrm{out}=h+\mathrm{FFN}(\mathrm{LN}(h)), \mathrm{FFN}(h)=W_2\,\phi(W_1 h+b_1)+b_2,

where x has shape T\times d, LN is layer normalization, and \phi is an activation function. Figure 3 shows the same computation as a diagram.

Diagram of a pre-norm Transformer block: layer normalization, multi-head attention and a residual addition, followed by layer normalization, a feed-forward network and a second residual addition.
Figure 3. A pre-norm Transformer block. Each sublayer is preceded by layer normalization, and its output is added back to its input through a residual connection. The block is repeated to form the stack. The diagram shows one block for one input sequence and omits the positional encoding and the final output layers.

Each component has a distinct job.

The block is stacked N times, with N=6 in the original Transformer.

Causal masking

In decoder self-attention, token i is allowed to attend only to tokens 1,\dots,i. Attending to later tokens would let the model read the answer it is supposed to predict. The restriction is enforced by adding a mask matrix M to the scores before the softmax:

A=\mathrm{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right)V,

where M_{ij}=0 if j\le i and M_{ij}=-\infty otherwise. Since \exp(-\infty)=0, future tokens receive exactly zero weight, and the remaining weights are renormalized over the allowed positions. For the sentence “Where is the library ?”, the query “Where” may attend only to itself, the query “is” may attend to “Where” and “is”, and only the final token may attend to all five positions.

The slides show the mask for this sentence as a grid, with one row per query and one column per key.

QueryWhereisthelibrary?
Whereallowed-\infty-\infty-\infty-\infty
isallowedallowed-\infty-\infty-\infty
theallowedallowedallowed-\infty-\infty
libraryallowedallowedallowedallowed-\infty
?allowedallowedallowedallowedallowed

The mask has an important consequence for training. Because position i never sees later tokens, one forward pass trains next-token prediction at all T positions in parallel, with no peeking at the answers. This is the training advantage over RNNs. Generation is still sequential, as it is for an RNN: the model produces one token, appends it to the input, and runs again. The masked decoder is the building block of GPT.

6. Position information

The slides collect the ingredients of the Transformer as four tricks. Three have already appeared: self-attention, in which each layer combines words with others; multi-head attention, with 8 heads that are learned independently; and scaled dot-product attention, which divides by \sqrt{d_k} so that the softmax does not saturate when d_k is large. The fourth is the positional encoding, which lets the model distinguish positions even though it no longer has an RNN.

Attention ignores order

Scaled dot-product attention and the fully connected layer are permutation-equivariant: reordering the inputs just reorders the outputs. Nothing in the computation refers to where a token sits in the sequence. A model with this property cannot distinguish two sentences that contain the same words in different orders.

Sinusoidal positional encodings

The original remedy is to add a vector of small constant values to each embedding, where the vector depends only on the position . For position p and coordinate pair i in an embedding of size d,

\mathrm{PE}(p,2i)=\sin\left(\frac{p}{10000^{2i/d}}\right),\qquad \mathrm{PE}(p,2i+1)=\cos\left(\frac{p}{10000^{2i/d}}\right).

Each pair of coordinates oscillates at its own frequency, so every position receives a distinct pattern. As a result, the same word has a slightly different embedding depending on where it occurs in the sentence, and reordering the input no longer produces a reordered copy of the same output. In the original Transformer the encoding has the same size as the embedding, 512, so that the two can be added.

Do we need positional encodings?

Haviv et al. trained language models with no positional encoding at all and found that they still learn positional information . The slides show a figure from that paper in which a probe tries to recover the absolute position of a token from the hidden states at each layer. For the model without positional encodings, the error at the input is as large as that of a random baseline, but it falls within the first few layers to nearly the level of models with learned or sinusoidal encodings.

There is an important caveat. The result holds for causal, decoder-only models. The mask itself leaks position, because token i attends to exactly i tokens. Without a mask, as in an encoder, dropping the positional encodings makes the model permutation-equivariant again, and word order is lost.

Positional encodings today

Three approaches are in common use.

The rotation in RoPE has a useful consequence. Writing R_{m\theta} for the rotation applied at position m, the score between a query at position m and a key at position n is

(R_{m\theta}q_m)^\top(R_{n\theta}k_n)=q_m^\top R_{(n-m)\theta}k_n.

The score depends on the positions only through the offset n-m, so the model obtains relative position without any additional parameters.

7. Three families of Transformers

The encoder and decoder stacks can be used together or separately, which gives three families of models .

FamilyExamplesAttentionTrained toGood at
Encoder-onlyBERT (2018)Bidirectional: every token sees the whole inputFill in masked-out wordsClassification, search, embeddings
Encoder-decoderOriginal Transformer (2017), T5 (2019)Bidirectional encoder, plus a causal decoder that also attends to the encoderMap an input sequence to an output sequenceTranslation, summarization
Decoder-onlyGPT series (2018 onward), Llama, Qwen, DeepSeekCausal: each token sees only the pastPredict the next tokenOpen-ended generation and chat

The decoder-only family won out for generation and is the dominant design today. It is the starting point for the next lecture on GPT, the generative pre-trained Transformer.

The central construction of the lecture is to replace a single recurrent summary with a learned, weighted average over all positions. Queries, keys, and values make that average trainable, multiple heads let it capture several relations at once, and residual connections, normalization, and feed-forward layers turn it into a block that can be stacked. With a causal mask, the same block becomes a next-token predictor.