AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
▦Deep Learning Architectures
  1. Convolutional Neural Networks (CNNs)
  2. CNN Architectures and Transfer Learning
  3. Recurrent Networks: RNN, LSTM and GRU
  4. Embeddings: Meaning as Vectors
  5. Attention and Transformers
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Deep Learning Architectures

Attention and Transformers

The architecture behind GPT, BERT, ViT and Whisper. Queries, keys and values; scaled dot-product attention; masks; multi-head attention; positional encodings; and how the Transformer block is assembled.

Advanced~35 min·6 references
Key terms
AttentionSelf-attentionMulti-head attentionTransformerPositional encodingEncoderDecoderLayer normalization

In 2017, Vaswani et al. proposed a sequence model with no recurrence and no convolution — only Attention — in a paper titled “Attention Is All You Need”[1]. The Transformer trains in parallel over all positions, scales remarkably well with data and compute, and now underlies nearly every frontier model: GPT-style LLMs, BERT, Vision Transformers (Vision Transformer (ViT)), Whisper for speech and DiT-style diffusion models. Understanding one equation — softmax(QKᵀ/√d)V — gets you most of the way.

≈
A soft library lookup
You walk into a library with a question (the query). Every book has a label on its spine (its key) and contents (its value). A normal lookup returns the one book whose label matches exactly. Attention instead compares your question with every label, turns the match scores into percentages, and hands you a blend of all the books' contents weighted by those percentages — mostly the best matches, a little of the rest. In self-attention, every word in a sentence does this at the same time, asking the other words for the information it needs.

From RNN bottleneck to attention

Seq2seq RNNs compressed a whole sentence into one vector. Bahdanau et al. (2014) let the decoder, at each output step, score every encoder state, normalize the scores with a Softmax, and use the weighted average as context[2] — the model learned soft word alignments between languages on its own. Two problems remained: RNNs still process tokens one after another (slow to train), and information between distant words still had to travel through many steps. The Transformer removed the RNN entirely: every token attends directly to every other token, in one step, in parallel.

Scaled dot-product attention

Q = XW_Q K = XW_K V = XW_V Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V
X holds one row per token (its Embedding + position). Each token gets a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on?).
In words: Every token makes a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on?). Each query is compared with every key by a dot product, the scores are scaled and turned into weights by softmax, and the output is the weighted average of the values.
Symbols(hover a symbol in the formula)
X
input token vectors, one row per token (n × d_model)
W_Q
learned projection to queries (d_model × d_k); W_K and W_V likewise for keys and values
Q
queries (n × d_k)
K
keys (n × d_k)
V
values (n × d_v)
QKᵀ
all query–key dot products at once: an n × n score matrix (ᵀ = transpose)
√d_k
square root of the key dimension; dividing by it keeps scores from growing with d_k and saturating the softmax
softmax
Softmax applied to each row: positive weights that sum to 1
Attention(Q, K, V)
the output: for each token, a weighted mix of all value vectors (n × d_v)
▸Worked example
2 tokens, d_k = 2. Query of token 1: q = [1, 0]; keys k₁ = [1, 0], k₂ = [0, 1]; values v₁ = [1, 2], v₂ = [3, 0] Scores: q·k₁ = 1, q·k₂ = 0 → divide by √2: [0.7071, 0] softmax: e^0.7071 = 2.0281, e^0 = 1 → weights [2.0281/3.0281, 1/3.0281] = [0.6698, 0.3302] Output = 0.6698·[1, 2] + 0.3302·[3, 0] = [1.6605, 1.3395] Shapes in BERT-base, batch 32, 128 tokens: Q is 32 × 128 × 64 per head, QKᵀ is 32 × 128 × 128.
  1. Scores: QKᵀ is an n × n matrix: entry (i, j) is the Dot product of token i's query with token j's key — how relevant j is to i.
  2. Scale: divide by √d_k. If query and key components have unit variance, their dot product has variance d_k; for d_k = 64 scores would have std ≈ 8, pushing softmax into saturation (one weight ≈ 1, tiny gradients). Dividing by √d_k brings the std back to ≈ 1[1].
  3. Softmax each row → attention weights that are positive and sum to 1.
  4. Mix values: each token's output is the weighted average of all value vectors.

Tiny worked example (d_k = 2): query q = (1, 0); keys k₁ = (1, 0), k₂ = (0, 1), k₃ = (1, 1); scalar values 10, 20, 30. Scores q·k = (1, 0, 1), scaled by 1/√2 → (0.71, 0, 0.71). Softmax → (0.40, 0.20, 0.40). Output = 0.40·10 + 0.20·20 + 0.40·30 = 20. The query “prefers” tokens 1 and 3 equally and still takes a little from token 2.

Self-attention and masks

In Self-attention, Q, K and V all come from the same sequence, so every token gathers information from every other token of the same sentence. In “The animal didn't cross the street because it was too tired”, the representation of “it” can pull information directly from “animal”, one step away instead of eight. A causal mask sets scores for future positions to −∞ before the softmax, so token i only sees tokens ≤ i — required for a Decoder that generates text left to right. A padding mask hides padding tokens. Cross-attention takes Q from the decoder and K, V from the Encoder — exactly Bahdanau's idea.

i
The cost: quadratic in sequence length
The score matrix is n × n per head per layer. For n = 4,096 tokens that's 16.8 million scores; doubling the context quadruples the attention cost. This is why context windows were long limited, and why techniques like FlashAttention (exact attention computed in tiles without materializing the full matrix) and the KV cache (reuse past keys/values during generation) matter so much.

Multi-head attention

headᵢ = Attention(QW_Qⁱ, KW_Kⁱ, VW_Vⁱ) MultiHead = Concat(head₁, …, head_h) · W_O
h heads, each with its own projections of size d_k = d_model / h. Original Transformer: d_model = 512, h = 8, d_k = 64.
In words: Run h smaller attentions in parallel, each with its own projections so it can focus on a different kind of relation (syntax, coreference, position…). Glue their outputs side by side and mix them with one final linear layer.
Symbols(hover a symbol in the formula)
headᵢ
output of attention head i (n × d_k)
W_Qⁱ
head i's own query projection (d_model × d_k); W_Kⁱ and W_Vⁱ likewise
Concat(head₁, …, head_h)
place the h head outputs side by side: n × (h · d_k) = n × d_model
W_O
output projection (d_model × d_model) that mixes information across heads
MultiHead
the result of Multi-head attention (n × d_model)
▸Worked example
Base Transformer: d_model = 512, h = 8 → d_k = 512 / 8 = 64; a sentence of n = 10 tokens Each head: Q, K, V are 10 × 64 → headᵢ is 10 × 64 Concat of 8 heads: 10 × 512 → · W_O (512 × 512) → 10 × 512 Parameters: W_Q, W_K, W_V (all heads together) + W_O = 4 · 512 · 512 = 1,048,576 (plus biases) — the same as one big head.

One attention pattern can only express one kind of relationship at a time. Multi-head attention runs several attention operations in parallel on smaller projections, so different heads can specialise — one tracks the previous token, another links pronouns to nouns, another follows syntax. Because each head is d_model/h wide, the total cost is about the same as one full-width head[1][3].

Positional encoding

Attention by itself is order-blind: shuffle the input tokens and each output is the same, just shuffled. “Dog bites man” and “man bites dog” would look identical. A Positional encoding injects order. The original paper added fixed sinusoids of different frequencies to the embeddings; BERT and GPT-2 learn a position vector per index; many modern LLMs use RoPE (rotary embeddings, Su et al.), which rotates queries and keys by a position-dependent angle so that attention scores depend on relative distance[5]; ALiBi adds a distance-based penalty to scores (Press et al., 2021).

PE(pos, 2i) = sin(pos / 10000^(2i/d_model)) PE(pos, 2i+1) = cos(pos / 10000^(2i/d_model))
Sinusoidal encoding: each dimension pair is a sine/cosine wave with a different wavelength, from 2π to 10000·2π.
In words: Each pair of dimensions is a sine/cosine wave of the position, and every pair uses a different wavelength — fast waves in the first dimensions, very slow ones in the last. Together they give every position a unique pattern, like the hands of a clock.
Symbols(hover a symbol in the formula)
PE(pos, 2i)
value of the Positional encoding at position pos, even dimension 2i
PE(pos, 2i+1)
value at the neighbouring odd dimension 2i + 1
pos
token position in the sequence: 0, 1, 2, …
i
index of the dimension pair: 0 … d_model/2 − 1
d_model
model width (512 in the base Transformer)
10000^(2i/d_model)
wavelength factor: 1 for the first pair, up to 10,000 for the last
sin
sine (angles in radians)
cos
cosine
▸Worked example
d_model = 4, position pos = 1 Pair i = 0: 10000^(0/4) = 1 → sin(1) = 0.84147, cos(1) = 0.54030 Pair i = 1: 10000^(2/4) = 100 → sin(0.01) = 0.01000, cos(0.01) = 0.99995 PE(1) = [0.84147, 0.54030, 0.01000, 0.99995] — added to the token's embedding.

The Transformer block

x ← x + MultiHeadAttention(LayerNorm(x)) x ← x + FFN(LayerNorm(x)), FFN(x) = W₂ · GELU(W₁x + b₁) + b₂
A Pre-LN block (the modern default). The original paper put LayerNorm after each residual addition (Post-LN). FFN hidden size d_ff is usually 4 × d_model (2048 for 512).
In words: Each sub-layer reads a normalized copy of x and adds its result back onto x. Attention lets tokens exchange information; the FFN then processes each token on its own by expanding it to a wider hidden layer and projecting it back.
Symbols(hover a symbol in the formula)
x
the residual stream: one vector per token (n × d_model)
←
update: replace x by the right-hand side
LayerNorm
Layer normalization: rescale each token vector to mean 0 and variance 1, then apply a learned scale and shift
MultiHeadAttention
Multi-head attention (with a causal mask in a decoder)
FFN(x)
position-wise feed-forward network (a 2-layer MLP (Multilayer Perceptron))
W₁
first FFN weight matrix (d_model × d_ff), expands e.g. 512 → 2048
b₁
first FFN bias
W₂
second FFN weight matrix (d_ff × d_model), projects back 2048 → 512
b₂
second FFN bias
GELU
smooth ReLU-like activation: GELU(z) = z · Φ(z), where Φ is the standard normal CDF
▸Worked example
n = 10 tokens, d_model = 512, d_ff = 2048 x: 10 × 512 → W₁x + b₁: 10 × 2048 → GELU → W₂·(…) + b₂: 10 × 512 → added to x FFN parameters: 512·2048 + 2048 + 2048·512 + 512 = 2,099,712 GELU values: GELU(1) ≈ 0.8413, GELU(2) ≈ 1.9545, GELU(−1) ≈ −0.1587 (small negatives leak through, unlike ReLU).

A block has two sub-layers: attention (tokens exchange information) and a position-wise feed-forward MLP (each token processes what it gathered). Each sub-layer is wrapped in a residual connection and Layer normalization — the same tricks that made ResNets trainable. Stack N blocks (6 in the original, 12 in BERT-base, 96 in GPT-3) and you have a Transformer. Moving LayerNorm before each sub-layer (Pre-LN) makes deep stacks much more stable to train (Xiong et al., 2020).

Loading interactive…
The full encoder–decoder Transformer. Press Walk through to follow one translation step, or tap any block (e.g. Cross-attention) for details. Note the residual (skip) paths around every sub-layer.
VariantAttentionTrained toExamples
Encoder-onlyBidirectional (sees all tokens)Fill in masked tokens; produce representationsBERT, RoBERTa, ViT
Decoder-onlyCausal (sees only the past)Predict the next tokenGPT, LLaMA, Claude-style LLMs
Encoder–decoderBidirectional encoder + causal decoder + cross-attentionMap one sequence to anotherOriginal Transformer, T5, Whisper
Loading interactive…
Real scaled dot-product attention computed from small hand-designed Q/K vectors for 2–3 heads. Click a query token to see where it attends; the heatmap shows the full weight matrix.
  1. Coreference: pick “The animal didn't cross the street because it was too tired”, select the coreference head and click “it”. The thickest line should go to “animal”.
  2. Different heads, different jobs: switch to the previous-token head — the heatmap becomes a diagonal band just below the main diagonal. Same sentence, completely different pattern.
  3. Causal mask: toggle encoder → decoder. The upper triangle of the heatmap turns to zero: “it” can no longer see “tired”. Every row still sums to 1.
  4. Scaling / temperature: turn off the √d scaling or lower the temperature — the weights become sharp, nearly one-hot. Raise it — they flatten toward uniform. This is why the √d_k factor matters for gradients.
  5. Indonesian sentence: switch to the Indonesian example and check whether the heads behave the same way across languages.
knobNumber of heads h
What it is
How many parallel attention operations each layer runs (each of width d_model / h).
↑ If you increase it
More distinct relationship patterns per layer; but each head gets narrower (smaller d_k), and too-narrow heads lose expressiveness. Compute stays roughly constant.
↓ If you decrease it
Wider heads but fewer patterns; a single head must average over different kinds of relationships.
Typical values
d_k = 64–128 per head; e.g. 8 heads at d_model 512, 12 at 768, 32+ in large LLMs.
knobModel width d_model
What it is
Size of every token's representation vector throughout the network.
↑ If you increase it
More capacity per token; parameters grow ≈ quadratically (≈ 12·d_model² per layer), as do compute and memory. Larger models typically need a smaller learning rate.
↓ If you decrease it
Cheaper and faster, but less able to represent nuanced information.
Typical values
512 (original), 768 (BERT-base), 4096+ (7B-class LLMs).
knobNumber of layers N
What it is
How many Transformer blocks are stacked.
↑ If you increase it
More steps of reasoning/composition and more parameters; deeper stacks need Pre-LN, warmup and careful initialization to train stably. Inference latency grows linearly.
↓ If you decrease it
Faster and simpler; may underfit complex tasks.
Typical values
6 (original), 12 (BERT-base), 32 (7B LLMs), 96 (GPT-3).
knobContext length n
What it is
Maximum number of tokens the model attends over at once.
↑ If you increase it
Can use longer documents and conversations; attention compute and memory grow ∝ n² (the KV cache ∝ n), and quality may drop beyond lengths seen in training.
↓ If you decrease it
Much cheaper; text beyond the window must be truncated, chunked or retrieved (RAG).
Typical values
512 (BERT), 2,048 (GPT-3), 8k–1M+ in modern LLMs.
knobFFN size d_ff
What it is
Hidden width of the feed-forward MLP inside each block.
↑ If you increase it
More per-token processing capacity (the FFN holds about ⅔ of a block's parameters); more memory and compute.
↓ If you decrease it
Smaller, faster model with less capacity to store knowledge.
Typical values
4 × d_model; about 8/3 × d_model for SwiGLU FFNs.
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

def attention(q, k, v, causal=False):
    # q, k, v: (batch, heads, seq_len, d_k)
    scores = q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))      # (b, h, n, n)
    if causal:
        n = q.size(-2)
        future = torch.triu(torch.ones(n, n, dtype=torch.bool), diagonal=1)
        scores = scores.masked_fill(future, float("-inf"))          # hide future tokens
    weights = scores.softmax(dim=-1)                               # rows sum to 1
    return weights @ v, weights

q, k, v = (torch.randn(1, 8, 10, 64) for _ in range(3))
out, w = attention(q, k, v, causal=True)
ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)      # fused kernel, PyTorch >= 2.0
print(torch.allclose(out, ref, atol=1e-5))                         # True

# A full Pre-LN encoder block from PyTorch's building blocks
block = nn.TransformerEncoderLayer(d_model=512, nhead=8, dim_feedforward=2048,
                                   dropout=0.1, activation="gelu",
                                   batch_first=True, norm_first=True)
x = torch.randn(2, 10, 512)          # (batch, seq_len, d_model)
print(block(x).shape)                # torch.Size([2, 10, 512])
Attention from scratch, checked against PyTorch's fused scaled_dot_product_attention[6], plus a ready-made encoder block.
!
Common pitfalls
Watch out for these:
  • Forgetting the causal mask when training a decoder: the model “cheats” by looking at the token it should predict — training loss collapses, generation is garbage.
  • Forgetting the padding mask: real tokens attend to padding.
  • Memory blow-up with long sequences: the n × n matrix grows quadratically; use fused/Flash attention kernels.
  • No positional information: without positional encodings, word order is invisible.
  • Reading attention maps as explanations: high attention weight ≠ causal importance (Jain & Wallace, 2019).
  • Post-LN without warmup on deep models often diverges early.
▸Go deeper: complexity, the original training recipe, and further reading
Layer typeCompute per layerSequential stepsMax path length
Self-attentionO(n² · d)O(1)O(1)
RecurrentO(n · d²)O(n)O(n)
ConvolutionalO(k · n · d²)O(1)O(logₖ n)
From Table 1 of Vaswani et al.: attention connects any two positions in one step and parallelizes fully, at quadratic cost in n[1].

The original model was trained with Adam (β₂ = 0.98), 4,000 warmup steps followed by inverse-square-root decay, dropout 0.1 and label smoothing 0.1[1]. For step-by-step visuals, read Jay Alammar's “Illustrated Transformer”[3]; for runnable code, the Transformer chapter of “Dive into Deep Learning”[4].

Quiz

1.
Why are attention scores divided by √d_k?
2.
What does the causal mask do in a decoder-only model like GPT?
3.
You remove positional encodings from a Transformer. What happens?
4.
You double the context length from 4k to 8k tokens. Roughly how does the attention score computation change?
5.
Which architecture fits “translate an English sentence to Indonesian” in the original Transformer design?
Score: 0/5

References

  1. [1]
    Attention Is All You Need
    PaperVaswani et al.2017arxiv.org
  2. [2]
    Neural Machine Translation by Jointly Learning to Align and Translate
    PaperBahdanau, Cho & Bengio2014arxiv.org
  3. [3]
    The Illustrated Transformer
    ArticleAlammar2018jalammar.github.io
  4. [4]
    Dive into Deep Learning — The Transformer Architecture
    BookZhang, Lipton, Li & Smolad2l.ai
  5. [5]
    RoFormer: Enhanced Transformer with Rotary Position Embedding
    PaperSu et al.2021arxiv.org
  6. [6]
    torch.nn.functional.scaled_dot_product_attention
    DocsPyTorchdocs.pytorch.org
← Previous
Embeddings: Meaning as Vectors
Next → · Large Language Models
Tokenization: how text becomes numbers