Skip to content

Module 14

Anurag Prasad edited this page Nov 9, 2026 · 8 revisions

Module 14 — Transformer Architecture and Self-Attention

⬅️ Module 13 · 🗺️ Curriculum · 🏠 Home · Module 15 ➡️

Level: Advanced · Prerequisites: Modules 01, 09, 13 · Time: about 10–12 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

The Transformer (Vaswani et al. 2017) replaced recurrence with self-attention: every token directly attends to every other token in one parallel operation. It underlies modern language, vision, speech and multimodal models. This module derives scaled dot-product attention, multi-head attention and the full encoder/decoder block, and shows how to count parameters and cost.

After this module you should be able to:

  • derive queries, keys, values and scaled dot-product attention, including why we divide by $\sqrt{d_k}$;
  • explain permutation equivariance, and causal and padding masks;
  • track tensor shapes through multi-head attention, the feed-forward network, residuals and norms;
  • distinguish encoder-only, decoder-only and encoder–decoder designs and compute parameters/FLOPs.

Beginner: the big picture

Read the sentence "The animal didn't cross the street because it was tired." To interpret "it", you look at other words. Self-attention formalises this: each token asks a query ("what am I looking for?"), every token offers a key ("what do I contain?") and a value ("what do I pass on?"). Tokens whose keys match the query contribute more of their values. Because all tokens do this simultaneously, training is parallel across the sequence.

flowchart TD
    X["Token embeddings + positions"] --> LN1["LayerNorm"]
    LN1 --> MHA["Multi-head self-attention"]
    X --> R1(("+"))
    MHA --> R1
    R1 --> LN2["LayerNorm"]
    LN2 --> FFN["Feed-forward network (MLP)"]
    R1 --> R2(("+"))
    FFN --> R2
    R2 --> OUT["Block output (repeat N times)"]
Loading

Figure 14.1 — A pre-LN Transformer block. Original diagram; the architecture follows Vaswani et al. (2017) with the pre-LN arrangement analysed by Xiong et al. (2020).

Core concepts and derivations

Tokenisation overview and embeddings

Text → tokens (sub-words, Module 23) → integer IDs → rows of an embedding matrix $E\in\mathbb{R}^{V\times d}$, giving $X\in\mathbb{R}^{T\times d}$. Position information is added separately (Module 15).

Queries, keys and values

Three learned linear projections of the inputs: $Q=XW_Q$, $K=XW_K$, $V=XW_V$ with $W_Q,W_K\in\mathbb{R}^{d\times d_k}$, $W_V\in\mathbb{R}^{d\times d_v}$. Query–key similarity decides where to look; values carry what is retrieved — a soft, differentiable dictionary lookup.

Scaled dot-product self-attention

$$ \mathrm{Attn}(Q,K,V)=\mathrm{softmax}!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V,\qquad Q,K\in\mathbb{R}^{T\times d_k},\ V\in\mathbb{R}^{T\times d_v}. $$

Why $\sqrt{d_k}$? If the components of $\mathbf{q},\mathbf{k}$ are independent with zero mean and unit variance, $\mathbf{q}^\top\mathbf{k}=\sum_{i=1}^{d_k}q_ik_i$ has mean 0 and variance $d_k$. Large logits push softmax into saturation (one-hot, vanishing gradients); dividing by $\sqrt{d_k}$ restores unit variance.

Attention scores and softmax

Row $i$ of the softmax is a probability distribution over positions $j$: output $\mathbf{o}i=\sum_j\alpha{ij}\mathbf{v}_j$ is a convex combination of values. Cost: $O(T^2d_k)$ time and $O(T^2)$ memory for the score matrix — the quadratic bottleneck for long contexts (Module 23).

Permutation equivariance without positional information

For a permutation matrix $P$, $Q\to PQ$, $K\to PK$, $V\to PV$ give

$$ \mathrm{softmax}!\Bigl(\frac{PQK^\top P^\top}{\sqrt{d_k}}\Bigr)PV=P\mathrm{softmax}!\Bigl(\frac{QK^\top}{\sqrt{d_k}}\Bigr)P^\top PV=P\mathrm{Attn}(Q,K,V), $$

(softmax is row-wise, so it commutes with row/column permutation). Self-attention is therefore permutation-equivariant: it sees a set of tokens, which is why positional information must be injected (Module 15).

Causal and padding masks

Add $-\infty$ to logits $S_{ij}$ where attention is forbidden before the softmax: causal mask ($j>i$) for autoregressive decoding so token $i$ cannot see the future; padding mask for pad tokens. Masked entries get exactly zero weight.

Attention weights without and with a causal mask

Figure 14.2 — Random $8\times8$ attention maps. Left: bidirectional (encoder) attention. Right: causal attention — the upper triangle is zero and row $i$ attends only to positions $\le i$. Original figure (figures/make_figs_2.py).

Multi-head attention

Run $h$ attention operations in parallel with independent projections of size $d_k=d_v=d/h$, concatenate and mix:

$$ \mathrm{MHA}(X)=\mathrm{Concat}(\mathrm{head}_1,\dots,\mathrm{head}_h),W_O,\qquad \mathrm{head}_i=\mathrm{Attn}(XW_Q^{(i)},XW_K^{(i)},XW_V^{(i)}),\quad W_O\in\mathbb{R}^{d\times d}. $$

Heads can specialise (syntax, coreference, positional patterns). Shapes: $X\ (B,T,d)\to$ reshape $(B,h,T,d/h)\to$ scores $(B,h,T,T)\to$ output $(B,T,d)$.

Position-wise feed-forward network

Applied independently to each token: $\mathrm{FFN}(\mathbf{x})=W_2,\phi(W_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}2$ with hidden width $d{ff}\approx4d$ (or gated variants like SwiGLU with $\approx\frac83d$). Most Transformer parameters and much of its "knowledge" live here.

Residual connections and normalisation

Each sub-layer is wrapped as $\mathbf{x}\leftarrow\mathbf{x}+\mathrm{Sublayer}(\mathrm{LN}(\mathbf{x}))$ (pre-LN, Module 09), with a final LayerNorm. Residuals give the residual stream view: layers read from and write additively to a shared stream.

Encoder/decoder blocks and cross-attention

The encoder stacks bidirectional self-attention + FFN. The decoder has (i) causal self-attention, (ii) cross-attention with queries from the decoder and keys/values from the encoder output, (iii) FFN. Cross-attention is the Module 13 mechanism in $QKV$ form.

Autoregressive versus bidirectional patterns

Family Attention Objective Examples
Encoder-only bidirectional masked-token prediction BERT
Decoder-only causal next-token prediction GPT, LLaMA
Encoder–decoder both + cross span/seq2seq T5, original Transformer

Worked example

$T=2$, $d_k=2$, $Q=\begin{pmatrix}1&0\0&1\end{pmatrix}$, $K=\begin{pmatrix}1&0\1&1\end{pmatrix}$, $V=I$.

$QK^\top=\begin{pmatrix}1&1\0&1\end{pmatrix}$; divide by $\sqrt2$: $\begin{pmatrix}0.707&0.707\0&0.707\end{pmatrix}$. Row 1 softmax: $(0.5,0.5)$. Row 2: $e^0=1$, $e^{0.707}=2.028$ → $(0.330,0.670)$. Output $=\alpha V$: rows $(0.5,0.5)$ and $(0.330,0.670)$. With a causal mask, row 1 would attend only to itself: weights $(1,0)$.

Parameter count per layer ($d_{ff}=4d$, ignoring biases/norms): attention $4d^2$ + FFN $8d^2$ $=12d^2$. GPT-2 small ($d=768$, 12 layers): $12\cdot12\cdot768^2\approx85$M non-embedding parameters (plus $\approx38.6$M token embeddings for a 50,257 vocabulary).

Implementation

import numpy as np

def softmax(s):
    s = s - s.max(-1, keepdims=True); e = np.exp(s); return e / e.sum(-1, keepdims=True)

def mha(X, Wq, Wk, Wv, Wo, h, causal=False):
    T, d = X.shape; dk = d // h
    split = lambda M: (X @ M).reshape(T, h, dk).transpose(1, 0, 2)     # (h, T, dk)
    Q, K, V = split(Wq), split(Wk), split(Wv)
    S = Q @ K.transpose(0, 2, 1) / np.sqrt(dk)                          # (h, T, T)
    if causal: S = np.where(np.tril(np.ones((T, T))) == 1, S, -np.inf)
    A = softmax(S); O = (A @ V).transpose(1, 0, 2).reshape(T, d)        # concat heads
    return O @ Wo, A

# check the worked example
Q = np.eye(2); K = np.array([[1., 0.], [1., 1.]]); print(softmax(Q @ K.T / np.sqrt(2)).round(3))
import torch, torch.nn as nn
layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, dim_feedforward=2048, norm_first=True, batch_first=True)
mask = nn.Transformer.generate_square_subsequent_mask(T)          # causal mask

Advanced topics

  • Efficient attention: FlashAttention (IO-aware exact attention), sparse/local/sliding-window attention, linear attention, multi-query and grouped-query attention to shrink the KV cache (Module 23).
  • Architecture variants: RMSNorm, SwiGLU, parallel attention+FFN blocks, mixture-of-experts FFNs, QK-norm.
  • Vision Transformers treat image patches as tokens (Dosovitskiy et al. 2021).
  • Mechanistic interpretability: induction heads, residual-stream analysis, superposition.
  • Scaling and stability: learning-rate warm-up, $\mu$P, attention-logit growth and z-loss, precision issues in softmax.
  • Expressivity and limits: fixed-depth attention has theoretical limitations on some sequential/algorithmic tasks; chain-of-thought extends effective computation.

Pitfalls and best practices

  • Forgetting the causal mask during training of decoder models (information leak → train loss collapses to ~0, generation fails).
  • Wrong mask polarity/dtype; adding $-10^9$ in half precision overflow issues (use -inf or dtype-min).
  • Mixing $(B,T,d)$ and $(T,B,d)$ conventions.
  • Not scaling logits by $1/\sqrt{d_k}$.
  • Ignoring that $T^2$ memory limits context length.

Conceptual questions and answers

Q1. Why divide by $\sqrt{d_k}$?

Dot products of unit-variance vectors have variance $d_k$; unscaled logits saturate the softmax and kill gradients. Dividing keeps their variance near 1.

Q2. Why is self-attention permutation-equivariant and what is the consequence?

Permuting the inputs permutes the outputs identically because the operations are symmetric across positions; word order is invisible unless positional information is added.

Q3. What does multi-head attention buy over single-head attention of the same width?

Multiple independent softmaxes let the layer attend to different positions/relations simultaneously; a single softmax averages everything into one distribution.

Q4. How are causal masks implemented and why before the softmax?

Set forbidden logits to $-\infty$ so $\exp(-\infty)=0$ and the remaining weights renormalise to sum to 1; masking after softmax would break normalisation.

Q5. Where are most of a Transformer's parameters?

FFN layers ($8d^2$ per layer) hold about two-thirds of the non-embedding parameters; attention has $4d^2$.

Q6. Encoder-only vs decoder-only models?

Encoder-only (bidirectional) models give contextual representations for understanding tasks; decoder-only (causal) models generate text autoregressively and, at scale, also solve understanding tasks via prompting.

Q7. What is cross-attention?

Attention whose queries come from one sequence (decoder) and keys/values from another (encoder output), letting the decoder read the source.

Q8. What is the time/memory complexity of self-attention and why does it matter?

$O(T^2d)$ compute and $O(T^2)$ memory per head for the score matrix, limiting context length; motivates FlashAttention, sparse and linear variants.

Q9. Why are residual connections essential in Transformers?

They keep an identity gradient path through dozens of layers and let each sublayer add a refinement to the residual stream.

Sources and further reading

  • Vaswani, A., et al. (2017). Attention is all you need. NeurIPS. arXiv:1706.03762.
  • Devlin, J., et al. (2019). BERT. NAACL. arXiv:1810.04805.
  • Radford, A., et al. (2018, 2019). Improving language understanding by generative pre-training; Language models are unsupervised multitask learners (GPT, GPT-2). OpenAI technical reports.
  • Raffel, C., et al. (2020). Exploring the limits of transfer learning with a unified text-to-text Transformer (T5). JMLR, 21.
  • Xiong, R., et al. (2020). On layer normalization in the Transformer architecture. ICML.
  • Shazeer, N. (2020). GLU variants improve Transformer. arXiv:2002.05202.
  • Dosovitskiy, A., et al. (2021). An image is worth 16×16 words: Transformers for image recognition at scale. ICLR. arXiv:2010.11929.
  • Elhage, N., et al. (2021). A mathematical framework for Transformer circuits. Anthropic (Transformer Circuits Thread).
  • Phuong, M., & Hutter, M. (2022). Formal algorithms for Transformers. arXiv:2207.09238.

⬅️ Module 13 · 🗺️ Curriculum · 🏠 Home · Module 15 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally