Skip to content
ML to LLMs
Cheat sheets

Transformer architecture

Attention, blocks, shapes, families, and costs on one page.

Attention: Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V\text{Attention}(Q,K,V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right)V, with Q=XWQQ = XW_Q, K=XWKK = XW_K, V=XWVV = XW_V.

StagePurpose
Token + position embeddingsidentity and order
Layer normalizationstable activations (pre-norm in modern models)
Multi-head self-attentionmix information across positions
Residual connectionpreserve signal, help gradients
Feed-forward network (d→4d→dd \to 4d \to d)transform each position; most parameters
Final norm + output headlogits over the vocabulary

Shapes (sequence length nn, width dd, hh heads, dk=d/hd_k = d/h):

TensorShape
XX[n,d][n, d]
Q,K,VQ, K, V per head[n,dk][n, d_k]
QK⊤QK^\top, attention weights[n,n][n, n] per head
Block output[n,d][n, d]

Parameters per block: attention 4d2+4d4d^2 + 4d; FFN 2d dff+dff+d2 d\,d_{\text{ff}} + d_{\text{ff}} + d; two layer norms 4d4d. GPT-2 small (d=768d=768, 12 layers): 124M total.

FamilyMaskUse
Encoder-onlynone (bidirectional)classification, embeddings, rerankers
Decoder-onlycausalgeneration, chat LLMs
Encoder-decodercausal decoder + cross-attentiontranslation, summarization

Costs: attention O(n2d)O(n^2 d) per layer; KV cache grows with nn × layers × width; generation with a KV cache costs O(n)O(n) per new token.

Lessons: Self-attention · The transformer architecture · Lab: attention