Skip to content
ml-recall

Topic notes

Attention & Transformers

Attention and the Transformer; scaled dot-product attention, masking, multi-head attention, positional encoding, the blocks, model families, cost, and vision and speech models.

4-min read AI-checked

Practise 65 questions Take a test

Key ideas

Formulas

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V,Mij={0allowed−∞masked\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V,\qquad M_{ij} = \begin{cases} 0 & \text{allowed} \\ -\infty & \text{masked} \end{cases} MultiHead(X)=Concat(head1,…,headh) Wo,PE(i, 2j)=sin⁡i100002j/d,PE(i, 2j+1)=cos⁡i100002j/d\mathrm{MultiHead}(X) = \mathrm{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)\,W_o,\qquad PE_{(i,\,2j)} = \sin\frac{i}{10000^{2j/d}},\quad PE_{(i,\,2j+1)} = \cos\frac{i}{10000^{2j/d}}

Shapes: input (B,T,d)(B, T, d); per-head queries (B,h,T,d/h)(B, h, T, d/h); scores (B,h,T,T)(B, h, T, T); output (B,T,d)(B, T, d). Position-wise FFN d→4d→dd \to 4d \to d has 8d2+5d8d^2 + 5d parameters.

Worked example

Three tokens with Q=K=V=X=[100111]Q = K = V = X = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{bmatrix}, dk=2d_k = 2, causal mask.

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

References

  1. 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)
  2. 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)
  3. 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
  4. 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)
  5. Hugging Face LLM Course — Chapter 1.6 Transformer Architectures (Encoder models, Decoder models, Sequence-to-sequence models)
  6. Wikipedia: Transformer (deep learning) — Subsequent work, Efficient implementation, KV caching
  7. 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
  8. Hugging Face Audio Course — Unit 3, Seq2Seq architectures (Automatic speech recognition; Text-to-speech)