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
- Start from the unrolled RNN. Each input
x_t updates a hidden stateh_t , which produces an outputy_t . - Change the target. If the output at step
t is trained to be the next inputx_{t+1} , the network becomes a next-token predictor. This is the task GPT is trained on. - Change the machinery. Replace the recurrent cell with Transformer blocks, which connect positions through attention instead of through a hidden state passed along the sequence
.
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.
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.
- The encoder is a bidirectional RNN. It runs over the whole input in both directions, and the hidden state
h_j at source positionj is the concatenation of a forward state and a backward state. Eachh_j therefore summarizes the words on both sides of positionj . - The decoder is an ordinary forward RNN. It has a hidden state
s_t and emits the translated wordy_t . Its hidden state is updated with an additional input, the attention state, which is computed from all of the encoder hidden states.
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.
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
Second, a softmax turns the scores into weights:
Third, the context vector is the weighted average of the encoder states:
Because the weights are nonnegative and sum to one,
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.
- CNNs turn images into features, and gradients can be backpropagated through them.
- RNNs operate over sequences and can generate outputs of variable length.
- Embedding tables convert between numbers and words.
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
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
A parameter-free form
The simplest version has three steps and no learnable parameters. Given token embeddings
- Compute dot products. The score between positions
i andj isx_i^\top x_j . - Normalize with a softmax. The scores for a fixed
i are turned into weightsa_{ij} that sum to one overj . - Compute the output. The output is the weighted sum of the embeddings.
The output
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:
The three projections give each token three roles.
- The query
q_i is what tokeni is looking for. - The key
k_j is what tokenj offers to be matched against. - The value
v_j is the content that tokenj contributes once it has been selected.
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:
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
One constraint applies. The dot product between a query and a key is defined only when the two vectors have the same length, so
The original Transformer uses
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
The shapes work out as follows. One head returns a matrix of shape
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
One attention head is then
where the softmax is applied to each row separately. Figure 2 shows the shapes involved.
The table lists what each matrix holds.
| Quantity | Shape | Meaning |
|---|---|---|
| one query per token | ||
| one key per token, as columns | ||
| scores of every token against every token | ||
| one value per token | ||
| row |
This is the same computation as in Section 3, carried out for all
Why the scores are scaled
Dividing by
The quadratic cost
The score matrix
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
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,
where
Each component has a distinct job.
- Attention mixes information across tokens. It is the only place in the block where one position can read from another.
- The feed-forward network processes each token on its own. It is the same two-layer network applied at every position, with a hidden layer four times as wide as the embedding. For
d=512 the hidden width is 2048. The activation was ReLU in the original model. Later models use GELU, as in GPT and BERT, or SwiGLU, as in Llama and most open models. - Residual connections add the input of each sublayer to its output. They give gradients a direct path through many layers, in the same way that the cell state does in an LSTM.
- Layer normalization normalizes the vector of each token. The original paper normalized after each addition. Most models today normalize before each sublayer, which is called pre-norm and is the form written above, because it trains more stably.
The block is stacked
Causal masking
In decoder self-attention, token
where
The slides show the mask for this sentence as a grid, with one row per query and one column per key.
| Query | Where | is | the | library | ? |
|---|---|---|---|---|---|
| Where | allowed | ||||
| is | allowed | allowed | |||
| the | allowed | allowed | allowed | ||
| library | allowed | allowed | allowed | allowed | |
| ? | allowed | allowed | allowed | allowed | allowed |
The mask has an important consequence for training. Because position
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
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
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
There is an important caveat. The result holds for causal, decoder-only models. The mask itself leaks position, because token
Positional encodings today
Three approaches are in common use.
- Learned absolute embeddings. One trained vector per position is added to the token embedding. This is the approach of BERT and of GPT-1 through GPT-3. It is simple, but it offers nothing for positions beyond the longest sequence seen in training.
- Rotary embeddings (RoPE). Nothing is added to the input. Instead, each query and key is rotated by an angle proportional to its position
. RoPE is used by Llama, Qwen, Mistral, and most open language models today. - ALiBi. No position vectors are used at all. A penalty proportional to the distance between two tokens is subtracted from each attention score
.
The rotation in RoPE has a useful consequence. Writing
The score depends on the positions only through the offset
7. Three families of Transformers
The encoder and decoder stacks can be used together or separately, which gives three families of models
| Family | Examples | Attention | Trained to | Good at |
|---|---|---|---|---|
| Encoder-only | BERT (2018) | Bidirectional: every token sees the whole input | Fill in masked-out words | Classification, search, embeddings |
| Encoder-decoder | Original Transformer (2017), T5 (2019) | Bidirectional encoder, plus a causal decoder that also attends to the encoder | Map an input sequence to an output sequence | Translation, summarization |
| Decoder-only | GPT series (2018 onward), Llama, Qwen, DeepSeek | Causal: each token sees only the past | Predict the next token | Open-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.