Key ideas
- Attention is a soft lookup: a query is compared with every key, the scores go through a softmax, and the output is the weighted average of the values. Every value stays in the sum; only its weight changes.
- Scaled dot-product attention scores . For vectors with independent zero-mean, unit-variance entries a dot product has variance , so dividing by brings the scores back to unit variance1; unscaled, large dot products push the softmax into a region with tiny gradients2. Additive attention also handles queries and keys of different sizes1; when the sizes match, dot products win in practice because a batch of them is one optimized matrix multiplication2.
- Masking: scores that must be ignored (padding, or future tokens in a decoder) are set to (in code, a very large negative number) before the softmax, so they get weight 0 and the remaining weights still sum to 11,2. Zeroing weights after the softmax would leave rows that sum to less than 1. A causal mask on tokens leaves allowed entries.
- Self-attention takes queries, keys and values from the same sequence; cross-attention (encoder–decoder attention) takes queries from the decoder and keys and values from the encoder outputs3.
- Multi-head attention: heads, each with its own learned projections, run in parallel; their outputs are concatenated and multiplied by , so different heads can attend to different kinds of relations2. With head size the total cost is about that of one full-width head2, and PyTorch's module has parameters whatever is.
- Positional encoding: with no recurrence or convolution, attention by itself ignores token order, so position vectors of the same size are added to the token embeddings2. The sinusoidal encoding is a fixed formula defined for every position and may extrapolate to longer sequences2; a learned table (as in ViT) has one row per trained position4.
- Transformer block: multi-head self-attention, then a position-wise feed-forward network (the same MLP applied to every token)3, with hidden width in the original, 2. Each sublayer sits inside a residual connection followed by layer normalization, : "add & norm", or post-norm2,3. Later models such as ViT normalize before each sublayer instead (pre-norm), which trains more easily4. The decoder adds masked self-attention and cross-attention3. There is no recurrence and no pooling between blocks: every token keeps its own vector.
- Families5: encoder-only (BERT: bidirectional attention, pretrained by reconstructing masked words; classification, NER), decoder-only (GPT: causal attention, next-token prediction; text generation), encoder–decoder (T5, BART: summarization, translation).
- Cost2: a self-attention layer costs and stores an weight matrix per head, but needs sequential steps and has path length between any two tokens; a recurrent layer costs with sequential steps. Long sequences are therefore expensive. In generation, a KV cache keeps the keys and values of earlier tokens at every attention layer, so each new token computes only its own query, key and value6.
- Vision Transformer (ViT): an image with patch size becomes patch tokens, computed by one convolution whose kernel size and stride equal ; the output of a
<cls>token (or the average of the patch outputs) feeds the classifier4. With far less locality and translation bias than a CNN, ViT trails ResNets of similar size on mid-sized data and wins only after pretraining on very large datasets4,7. For fine-tuning at a higher resolution, the learned position embeddings are interpolated in 2D to the larger patch grid7. - Speech8: Whisper is an encoder–decoder; the encoder reads a log-mel spectrogram and the decoder, acting as a language model, generates text tokens through cross-attention. CTC models such as Wav2Vec2 are encoder-only and predict one character per audio frame; the seq2seq approach is the more powerful one. Text-to-speech models predict a spectrogram, and a separately trained vocoder turns it into a waveform.
Formulas
Shapes: input ; per-head queries ; scores ; output . Position-wise FFN has parameters.
Worked example
Three tokens with , , causal mask.
- Scores : row 2 is , row 3 is .
- Row 1 sees only itself: weight 1, output .
- Row 2 masks token 3: , output .
- Row 3 sees all: , output .
In code
import torch
from torch import nn
mha = nn.MultiheadAttention(embed_dim=768, num_heads=12, batch_first=True)
print(sum(p.numel() for p in mha.parameters())) # 2362368 = 4 * (768 * 768 + 768)
x = torch.zeros(2, 10, 768) # (batch, tokens, d_model)
causal = torch.triu(torch.ones(10, 10, dtype=torch.bool), diagonal=1) # True = blocked
with torch.no_grad():
out, w = mha(x, x, x, attn_mask=causal) # w is averaged over the heads
print(out.shape, w.shape) # torch.Size([2, 10, 768]) torch.Size([2, 10, 10])
print(w[0, 2, :4]) # tensor([0.3333, 0.3333, 0.3333, 0.0000]) token 3 sees tokens 1-3
Common pitfalls
- The scaling is , not ; without it large dot products saturate the softmax.
- Mask with before the softmax; zeroing after it breaks the normalization.
- More heads do not add parameters when the model width is fixed, because each head works on a slice; only a "wide" variant that gives every head the full width grows with .
- A Transformer without positional information treats its input as a bag of tokens.
- A learned position table has no rows for positions beyond its length; a longer input needs the table extended, and a ViT fine-tuned on larger images interpolates it.
- Encoder-only models are for understanding tasks, decoder-only for generation; "BERT for text generation" is a classic wrong answer, and so is "Whisper is a CTC model".
- Doubling a ViT's image side at fixed patch size gives the tokens and about the attention-score cost.
- Splitting heads needs
view(B, T, h, d // h).transpose(1, 2); a directview(B, h, T, d // h)mixes tokens and features.
References
- Dive into Deep Learning — Sec. 11.3 Attention Scoring Functions (11.3.1 Dot Product Attention, 11.3.2.1 Masked Softmax Operation, 11.3.4 Additive Attention)
- Vaswani et al. (2017), Attention Is All You Need — Sec. 3.1 Encoder and Decoder Stacks; 3.2.1 Scaled Dot-Product Attention; 3.2.2 Multi-Head Attention; 3.2.3 Applications of Attention in our Model; 3.3 Position-wise Feed-Forward Networks; 3.5 Positional Encoding; 4 Why Self-Attention (Table 1)
- Dive into Deep Learning — Sec. 11.7.1 Model; 11.7.2 Positionwise Feed-Forward Networks; 11.7.3 Residual Connection and Layer Normalization; 11.7.5 Decoder
- Dive into Deep Learning — Sec. 11.8.1 Model; 11.8.2 Patch Embedding; 11.8.3 Vision Transformer Encoder; 11.8.6 Summary and Discussion; 11.8.7 Exercises (Exercise 2)
- Hugging Face LLM Course — Chapter 1.6 Transformer Architectures (Encoder models, Decoder models, Sequence-to-sequence models)
- Wikipedia: Transformer (deep learning) — Subsequent work, Efficient implementation, KV caching
- Dosovitskiy et al. (2021), An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale — Sec. 1 Introduction; 3.1 Vision Transformer (ViT), Inductive bias; 3.2 Fine-tuning and Higher Resolution
- Hugging Face Audio Course — Unit 3, Seq2Seq architectures (Automatic speech recognition; Text-to-speech)