concept / transformer-architecture
Next task →
University/Generative AI/Sequence models/Transformer Architecture
Architectures · Sequence models · Attention-based networks

Transformer Architecture

A Transformer is a stack of blocks, each combining multi-head self-attention with a position-wise feed-forward network, residual connections and normalization. Attention mixes information across tokens; the feed-forward network transforms each token independently.

35 sectionsintermediate240 minhand-authored · structural 73/100
Take assessment →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

A Transformer is a neural network architecture for sequences. It maps a sequence of token representations

X∈Rn×dX\in\mathbb{R}^{n\times d}

to another sequence of the same shape, using a stack of identical blocks. Each block has two sublayers:

  1. multi-head self-attention, which lets each position read from other positions;
  2. a position-wise feed-forward network (FFN), which transforms each position independently.

Both sublayers are wrapped in residual connections and normalization. The original 2017 paper used post-norm blocks; most modern language models use pre-norm blocks, which are easier to train at depth. The architecture is not the same thing as the autoregressive objective p(x)=∏tp(xt∣x<t)p(x)=\prod_t p(x_t\mid x_{<t}): that factorization describes any autoregressive model, including an RNN. The Transformer is the block that computes the conditional distributions.

2. Why this concept exists

Before attention, sequence models were dominated by recurrent networks. An RNN computes ht=f(ht−1,xt)h_t=f(h_{t-1},x_t), so it must process tokens sequentially. That creates two problems:

  • Long paths for long-range dependencies. Information from token 1 reaches token nn only after n−1n-1 recurrent steps, and gradients must traverse the same path.
  • Limited parallelism during training. The recurrence cannot be parallelized across time, even though modern accelerators are built for large matrix products.

Convolutional sequence models parallelize better but have a fixed receptive field per layer; stacking many layers is needed to connect distant positions.

Self-attention solves both problems. Every position computes a query, and every position produces a key and a value. The query-key dot products give all pairwise interaction weights in one matrix multiplication, so the path length between any two positions is one layer and training parallelizes across the sequence. The cost is quadratic memory and time in the sequence length, which is the central engineering trade-off of the architecture.

3. Historical background

Attention for sequence-to-sequence models was introduced by Bahdanau, Cho and Bengio (2015) as a way for a decoder to look back at encoder states. Vaswani et al. (2017), Attention Is All You Need, removed the recurrence entirely and built an encoder–decoder from stacked self-attention and feed-forward layers. BERT (2018) used a bidirectional encoder for pretraining; GPT (2018–2020) used a causal decoder for language modelling. Later work changed normalization placement, positional encoding (learned, sinusoidal, rotary), activation functions (ReLU to GELU/SwiGLU), and attention kernels (FlashAttention), but the block structure has remained remarkably stable.

4. Fundamental problem

Given a sequence of vectors, produce context-dependent representations in which each position can use information from any other position, while keeping the computation parallel and the parameter count independent of sequence length.

The design constraints are:

  • Content-based routing: which positions matter should depend on the data, not on a fixed distance.
  • Permutation handling: attention itself is permutation-equivariant, so position information must be injected explicitly.
  • Stability at depth: residual connections and normalization must keep gradients well-scaled across dozens of layers.
  • Causality for generation: a decoder must not see future tokens.
  • Efficiency: the naive attention matrix is n×nn\times n, which becomes the bottleneck for long contexts.

5. First-principles explanation

Start with a set of token vectors x1,…,xn∈Rdx_1,\dots,x_n\in\mathbb{R}^d. We want a new vector yiy_i that is a weighted average of information from other tokens, with weights depending on the content of xix_i and xjx_j.

A simple content-based weight is a dot product: sij=⟨qi,kj⟩s_{ij}=\langle q_i,k_j\rangle. Large positive values mean “ii finds jj relevant.” To turn scores into a convex combination, apply softmax over jj:

aij=exp⁡(sij)∑lexp⁡(sil),yi=∑jaijvj.a_{ij}=\frac{\exp(s_{ij})}{\sum_{l}\exp(s_{il})},\qquad y_i=\sum_j a_{ij}v_j.

This is the whole idea of attention. The Transformer makes it expressive by (a) learning linear maps Q=XWQQ=XW_Q, K=XWKK=XW_K, V=XWVV=XW_V; (b) running several attention heads in parallel and concatenating them; (c) adding a position-wise FFN; and (d) wrapping each sublayer in a residual connection and normalization.

6. Prerequisite concepts

You need: (a) matrix multiplication and shape reasoning; (b) the softmax function and why the 1/dk1/\sqrt{d_k} scale controls its temperature; (c) the definition of self-attention; (d) backpropagation through a computation graph; (e) LayerNorm or RMSNorm; (f) residual connections. If any of these is missing, study the linked concept first — the Transformer is a composition of them, not a new primitive.

7. Complete mathematical formulation

Let X∈Rn×dX\in\mathbb{R}^{n\times d} be the input, with nn tokens and model width dd. Choose hh heads and per-head width dk=d/hd_k=d/h.

Per head ii:

Qi=XWQi,Ki=XWKi,Vi=XWVi,Q_i=XW_{Q_i},\quad K_i=XW_{K_i},\quad V_i=XW_{V_i},

with WQi,WKi,WVi∈Rd×dkW_{Q_i},W_{K_i},W_{V_i}\in\mathbb{R}^{d\times d_k}. Then

head⁡i=softmax⁡(QiKi⊤dk+M)Vi,\operatorname{head}_i=\operatorname{softmax}\left(\frac{Q_iK_i^\top}{\sqrt{d_k}}+M\right)V_i,

where M∈Rn×nM\in\mathbb{R}^{n\times n} is an optional mask: Mtj=−∞M_{tj}=-\infty for positions that token tt may not attend to, and 00 otherwise.

Multi-head output:

MHA⁡(X)=Concat⁡(head⁡1,…,head⁡h)WO,\operatorname{MHA}(X)=\operatorname{Concat}(\operatorname{head}_1,\dots,\operatorname{head}_h)W_O,

with WO∈Rd×dW_O\in\mathbb{R}^{d\times d}.

Pre-norm block (modern default):

X′=X+MHA⁡(LN⁡1(X)),X′′=X′+FFN⁡(LN⁡2(X′)),FFN⁡(Z)=σ(ZW1+b1)W2+b2.\begin{aligned} X'&=X+\operatorname{MHA}(\operatorname{LN}_1(X)),\\ X''&=X'+\operatorname{FFN}(\operatorname{LN}_2(X')),\\ \operatorname{FFN}(Z)&=\sigma(ZW_1+b_1)W_2+b_2. \end{aligned}

Here W1∈Rd×dffW_1\in\mathbb{R}^{d\times d_{ff}}, W2∈Rdff×dW_2\in\mathbb{R}^{d_{ff}\times d}, and σ\sigma is applied elementwise (ReLU, GELU or SwiGLU). The original paper used post-norm: LN⁡(X+MHA⁡(X))\operatorname{LN}(X+\operatorname{MHA}(X)).

Causal mask. For autoregressive decoding, set Mtj=−∞M_{tj}=-\infty whenever j>tj>t. Then row tt of the attention matrix has zeros in future positions, so token tt cannot read token t+1t+1.

8. Notation dictionary

| Symbol | Meaning | Shape | |---|---|---| | nn | sequence length (number of tokens) | integer | | dd | model width / hidden dimension | integer | | hh | number of attention heads | integer | | dkd_k | per-head dimension, d/hd/h | integer | | XX | input token representations | n×dn\times d | | WQ,WK,WVW_Q,W_K,W_V | query, key, value projections | d×dkd\times d_k per head | | WOW_O | output projection after concatenation | d×dd\times d | | Q,K,VQ,K,V | projected queries, keys, values | n×dkn\times d_k per head | | MM | additive attention mask | n×nn\times n | | softmax⁡\operatorname{softmax} | row-wise normalization | applied to n×nn\times n | | LN⁡\operatorname{LN} | layer normalization | applied per token | | W1,W2W_1,W_2 | FFN matrices | d×dffd\times d_{ff}, dff×dd_{ff}\times d | | dffd_{ff} | FFN hidden width, often 4d4d | integer | | σ\sigma | elementwise nonlinearity | function |

9. Step-by-step derivation

Step 1 — attention as a differentiable lookup. Fix a query q∈Rdkq\in\mathbb{R}^{d_k} and keys k1,…,knk_1,\dots,k_n. The score sj=⟨q,kj⟩/dks_j=\langle q,k_j\rangle/\sqrt{d_k} measures alignment. Softmax converts scores to weights aj≥0a_j\ge0, ∑jaj=1\sum_j a_j=1. The output y=∑jajvjy=\sum_j a_jv_j is a convex combination of values. This is a soft, differentiable dictionary lookup: the query selects which values to read.

Step 2 — why divide by dk\sqrt{d_k}. If the components of qq and kk are independent with mean 0 and variance 1, then ⟨q,k⟩\langle q,k\rangle has variance dkd_k. Without scaling, the logits grow like dk\sqrt{d_k}, the softmax saturates, and gradients vanish. Dividing by dk\sqrt{d_k} keeps the logit variance near 1. This is a variance argument, not a cosmetic convention.

Step 3 — batching all queries. Stack queries into Q∈Rn×dkQ\in\mathbb{R}^{n\times d_k} and keys into K∈Rn×dkK\in\mathbb{R}^{n\times d_k}. Then QK⊤QK^\top is the n×nn\times n matrix of all pairwise scores. One matrix multiplication computes every interaction, which is why training parallelizes across positions.

Step 4 — multiple heads. A single attention head produces one weighted average per token. Multiple heads let the model attend to different subspaces or relations simultaneously. Each head has its own projections and its own dkd_k-dimensional output; concatenating hh heads gives dd channels, and WOW_O mixes them. The parameter count is dominated by 4d24d^2 for the four projections, independent of nn.

Step 5 — add the FFN. Attention mixes information across tokens but is linear in the values once the weights are fixed. The position-wise FFN adds nonlinearity and capacity within each token: the same two-layer MLP is applied to every row of XX. It is where most of the parameters live: 2ddff2dd_{ff} per layer, which is 8d28d^2 when dff=4dd_{ff}=4d.

Step 6 — residual and normalization. A residual connection computes X+sublayer⁡(X)X+\operatorname{sublayer}(X), so gradients have an identity path to earlier layers. Normalization keeps activation scale controlled. Pre-norm applies LN before the sublayer, which keeps the residual stream unnormalized and is more stable for deep stacks; post-norm applies LN after the residual addition, as in the original paper.

Step 7 — positions. Without position information, attention is permutation-equivariant: permuting the input tokens permutes the output in the same way, so the model cannot distinguish “dog bites man” from “man bites dog.” Positional encodings (sinusoidal, learned, or rotary) inject order. The encoding is added to or rotates the token representations before attention.

10. Proofs and proof intuition

Proposition 1 (permutation equivariance). Let PP be an n×nn\times n permutation matrix and let f(X)=softmax⁡(QK⊤/dk)Vf(X)=\operatorname{softmax}(QK^\top/\sqrt{d_k})V with Q=XWQQ=XW_Q, K=XWKK=XW_K, V=XWVV=XW_V. Then f(PX)=Pf(X)f(PX)=Pf(X).

Proof. Q′=PXWQ=PQQ'=PXW_Q=PQ, K′=PKK'=PK, V′=PVV'=PV. Scores are Q′K′⊤=PQSK⊤P⊤=P(QK⊤)P⊤Q'K'^\top=PQS K^\top P^\top=P(QK^\top)P^\top. Softmax commutes with row and column permutations, so the attention matrix becomes PAP⊤PAP^\top. Therefore f(PX)=PAP⊤PV=PAP⊤PV=PAV=Pf(X)f(PX)=PAP^\top PV=PAP^\top P V=P A V=P f(X). □\square

This is exactly why positional information must be added: the bare attention operator cannot see order.

Proposition 2 (causality). If Mtj=−∞M_{tj}=-\infty for j>tj>t and finite otherwise, then output row tt depends only on input rows 1,…,t1,\dots,t.

Proof. For j>tj>t, exp⁡(Stj+Mtj)=0\exp(S_{tj}+M_{tj})=0, so atj=0a_{tj}=0. Row tt of the output is ∑j≤tatjVj\sum_{j\le t}a_{tj}V_j, a combination of the first tt value rows. □\square

Proposition 3 (parameter count per block). With dff=4dd_{ff}=4d and biases ignored, one pre-norm block has 4d24d^2 attention parameters, 8d28d^2 FFN parameters, and 4d4d normalization parameters (two LNs with scale and shift). The total is 12d2+4d12d^2+4d, independent of nn.

11. Geometric interpretation

Each token is a point in Rd\mathbb{R}^d. A query defines a direction; dot products with keys measure alignment. Softmax turns alignments into a probability distribution over tokens, and the output is the corresponding weighted average of value vectors. Multi-head attention repeats this in several learned subspaces, so different heads can specialize in syntactic, semantic or positional relations.

The residual stream is a shared workspace. Each attention head and FFN reads from it, computes an update, and writes the update back by addition. LayerNorm controls the scale of the workspace before each read. This “read–write” view explains why residual connections are essential: without them, each layer would overwrite the representation instead of refining it.

13. Numerical worked example

Take n=2n=2, d=2d=2, one head, and

X=(1001),WQ=WK=WV=I.X=\begin{pmatrix}1&0\\0&1\end{pmatrix},\qquad W_Q=W_K=W_V=I.

Then Q=K=V=XQ=K=V=X and QK⊤=XX⊤=(1001)QK^\top=X X^\top=\begin{pmatrix}1&0\\0&1\end{pmatrix}. With dk=2d_k=2, the scale is 1/21/\sqrt2, so the score matrix is

S=(0.707000.707).S=\begin{pmatrix}0.707&0\\0&0.707\end{pmatrix}.

Apply a causal mask: token 1 may attend only to itself, token 2 to both. Row 1 has weights (1,0)(1,0), so y1=(1,0)y_1=(1,0). Row 2 has logits (0,0.707)(0,0.707); softmax gives

softmax⁡(0,0.707)=(11+e0.707,e0.7071+e0.707)≈(0.330,0.670).\operatorname{softmax}(0,0.707)=\left(\frac{1}{1+e^{0.707}},\frac{e^{0.707}}{1+e^{0.707}}\right)\approx(0.330,0.670).

Thus y2≈0.330(1,0)+0.670(0,1)=(0.330,0.670)y_2\approx0.330(1,0)+0.670(0,1)=(0.330,0.670). The first token's representation is unchanged; the second mixes both tokens. Without the mask, row 1 would also mix, with weights (0.670,0.330)(0.670,0.330). This small calculation is the entire attention mechanism; a real model learns the projections and stacks many such blocks.

15. Algorithm pseudocode

algorithm TransformerBlock(X, params, mask):
    # X: n x d
    Z <- LayerNorm(X)
    Q <- Z W_Q; K <- Z W_K; V <- Z W_V       # per head, or batched
    S <- Q K^T / sqrt(d_k) + mask
    A <- softmax_rows(S)
    H <- A V
    X <- X + Concat(heads) W_O               # residual
    Z <- LayerNorm(X)
    F <- activation(Z W_1 + b_1) W_2 + b_2
    X <- X + F                               # residual
    return X

# Stack N blocks, then apply a task head (LM logits, classifier, ...)

16. Implementation from scratch

import numpy as np

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

def layer_norm(x, eps=1e-5):
    mu = x.mean(axis=-1, keepdims=True)
    var = x.var(axis=-1, keepdims=True)
    return (x - mu) / np.sqrt(var + eps)

def attention(x, wq, wk, wv, mask=None):
    """Single-head self-attention. x: (n, d); weights: (d, dk)."""
    q, k, v = x @ wq, x @ wk, x @ wv
    scores = q @ k.T / np.sqrt(q.shape[-1])
    if mask is not None:
        scores = scores + mask
    weights = softmax(scores, axis=-1)
    return weights @ v, weights

def transformer_block(x, wq, wk, wv, wo, w1, b1, w2, b2, mask=None):
    z = layer_norm(x)
    a, _ = attention(z, wq, wk, wv, mask)
    x = x + a @ wo
    z = layer_norm(x)
    f = np.maximum(0.0, z @ w1 + b1) @ w2 + b2
    return x + f

rng = np.random.default_rng(0)
n, d, dk, dff = 4, 8, 4, 16
x = rng.standard_normal((n, d))
wq, wk, wv = (rng.standard_normal((d, dk)) / np.sqrt(d) for _ in range(3))
wo = rng.standard_normal((dk, d)) / np.sqrt(dk)
w1 = rng.standard_normal((d, dff)) / np.sqrt(d)
b1 = np.zeros(dff)
w2 = rng.standard_normal((dff, d)) / np.sqrt(dff)
b2 = np.zeros(d)
mask = np.triu(np.full((n, n), -1e9), k=1)   # causal: no future tokens

out = transformer_block(x, wq, wk, wv, wo, w1, b1, w2, b2, mask)
assert out.shape == (n, d)
print("block output shape", out.shape)

The causal mask is an upper-triangular matrix of large negative numbers added before the softmax. After exponentiation those entries become zero, so future positions receive no weight.

17. Professional library implementation

import torch
from torch import nn

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, 16, 512)                 # batch, sequence, width
mask = nn.Transformer.generate_square_subsequent_mask(16)
out = block(x, src_mask=mask)
print(out.shape)                            # torch.Size([2, 16, 512])

norm_first=True selects pre-norm. batch_first=True makes the tensor layout (B,n,d)(B,n,d); PyTorch's default is (n,B,d)(n,B,d), which is a common source of shape bugs. For inference, use nn.MultiheadAttention with a KV cache rather than recomputing the full prefix at every step.

18. Code walkthrough

Scratch block. The function follows the pre-norm equations exactly. layer_norm normalizes each token vector across the feature dimension. attention computes QK⊤/dkQK^\top/\sqrt{d_k}, adds the mask, applies a numerically stable row-wise softmax, and multiplies by VV. The residual additions are the two x = x + ... lines. The FFN is a two-layer MLP with ReLU; production models often use GELU or a gated variant.

Library block. nn.TransformerEncoderLayer packages the same computation with fused kernels, dropout, and optional pre-norm. The important thing is to check the tensor layout and the mask convention: PyTorch's src_mask is additive and must have shape compatible with (n,n)(n,n) or (B⋅h,n,n)(B\cdot h,n,n). A mask with the wrong sign will either leak future tokens or block everything.

19. Tensor and memory analysis

The attention score matrix has shape B×h×n×nB\times h\times n\times n before the softmax, so it costs 4Bhn24Bhn^2 bytes in fp32 (or 2Bhn22Bhn^2 in fp16). For B=8B=8, h=32h=32, n=4096n=4096, that is about 17 GB in fp16 just for the scores — often the reason long-context training runs out of memory. FlashAttention avoids materializing this matrix by computing attention in tiles, reducing HBM traffic to O(n2d2/M)O(n^2d^2/M) where MM is on-chip memory.

The KV cache for autoregressive inference stores keys and values for every past token: 2×B×h×n×dk2\times B\times h\times n\times d_k values per layer. At long context this grows linearly and can dominate memory. The FFN activations are B×n×dffB\times n\times d_{ff} per layer, usually smaller than the attention matrix for long nn but larger for short nn and wide dffd_{ff}.

20. Time complexity

Per layer, the attention score computation is O(n2d)O(n^2d) (or O(n2dk)O(n^2d_k) summed over heads), the softmax is O(n2h)O(n^2h), and the output projection is O(n2d)O(n^2d). The FFN is O(nd dff)O(nd\,d_{ff}), which is O(nd2)O(nd^2) when dff=4dd_{ff}=4d. For n≫dn\gg d, attention dominates; for short sequences and wide models, the FFN dominates.

A full forward pass through LL layers is O(L(n2d+nd2))O(L(n^2d+nd^2)). Autoregressive generation with a KV cache costs O(Lnd)O(Lnd) per new token for attention (plus O(Ld2)O(Ld^2) for the FFN), so generating nn tokens costs O(Ln2d+Lnd2)O(Ln^2d+Ln d^2) — still quadratic overall because each step attends to a growing cache.

21. Space complexity

Weights: O(Ld2)O(Ld^2) for attention projections and O(Lddff)O(Ldd_{ff}) for FFNs, independent of sequence length. Activations during training: O(Ln2)O(Ln^2) for the attention matrices if materialized, plus O(Lnd)O(Lnd) for token representations. Inference with a KV cache: O(Lnd)O(Lnd) for cached keys and values, plus O(Ld2)O(Ld^2) for weights. The quadratic attention activation is the main memory bottleneck for long sequences.

22. Experimental demonstration

  1. Shape and causality test. Implement the scratch block. Feed a random sequence, then change only the last token. With a causal mask, the first n−1n-1 output rows must be unchanged (up to floating-point error); without the mask, they should change. This is a direct test that the mask is doing its job.
  2. Permutation test. Permute the input tokens and verify that the unmasked attention output is permuted in the same way. Add positional encodings and show that the equivariance breaks, as intended.
  3. Head ablation. On a small trained model, zero out one head at a time and measure the change in validation loss. Report the distribution, not a single anecdote.
  4. Scaling measurement. Time the attention block for n∈{128,256,512,1024,2048}n\in\{128,256,512,1024,2048\} and plot wall-clock time against n2n^2. The slope should approach 1 on a log-log plot when attention dominates.

23. Benchmark results

Do not quote a single “Transformer speed” number. Throughput depends on sequence length, batch size, model width, precision, kernel implementation, GPU generation, and whether the workload is prefill or decode. Report the hardware, dtype, batch shape, sequence length, and whether attention is materialized or fused. For long-context claims, report peak memory as well as tokens per second; a kernel that is faster at n=512n=512 may lose at n=8192n=8192 because of memory traffic.

24. Limitations

  • Quadratic attention cost. Time and memory grow as O(n2)O(n^2) for the score matrix. Long-context models need FlashAttention, sliding windows, sparse attention, or linear/state-space alternatives.
  • Position handling is not automatic. Attention is permutation-equivariant; the choice of positional encoding (absolute, relative, rotary) materially changes length generalization.
  • Data hungry. Transformers have few architectural priors, so they typically need large datasets or strong pretraining to match convolution/RNN inductive biases on small data.
  • Interpretability is not free. Attention weights are not a complete explanation of model behavior; they are one signal among many.
  • Training instability at scale. Loss spikes, attention logit growth, and normalization placement matter; pre-norm and QK normalization are common mitigations.
  • KV-cache memory. Inference cost grows with context length and batch size, which limits serving throughput.

25. Failure scenarios

  1. Mask sign or shape error. Adding +∞+\infty instead of −∞-\infty leaks future tokens; a mask with the wrong broadcast shape silently applies to the wrong axis. Test causality by changing the last token.
  2. Missing 1/dk1/\sqrt{d_k}. Logits grow with dkd_k, the softmax saturates, and gradients vanish. Check the scale of attention logits during training.
  3. Wrong tensor layout. PyTorch's default is (n,B,d)(n,B,d); passing (B,n,d)(B,n,d) without batch_first=True mixes batch and sequence dimensions.
  4. LayerNorm on the wrong axis. Normalizing across the sequence instead of across features changes the operation entirely. LN normalizes each token's feature vector.
  5. Positional encoding omitted. The model becomes permutation-equivariant and cannot distinguish word order.
  6. KV-cache misalignment. Reusing a cache with a different batch order or mask produces plausible but wrong continuations.
  7. Attention logits overflow in fp16. Softmax is stable only after subtracting the row maximum; fused kernels handle this, naive code may not.

26. Common misconceptions

  • “The Transformer is just attention.” No: the FFN, residuals, normalization, and positional information are essential. Attention alone is a linear mixing operation once the weights are fixed.
  • “Attention weights explain the prediction.” They show where information is read, not why the output is what it is. Multiple heads and the FFN also matter.
  • “The formula p(x)=∏tp(xt∣x<t)p(x)=\prod_t p(x_t\mid x_{<t}) defines the Transformer.” It defines an autoregressive likelihood; an RNN or a state-space model can use the same factorization.
  • “More heads always help.” Heads share a fixed width dd; too many heads make each head low-dimensional. Head count is a design choice, not a monotone improvement.
  • “Pre-norm and post-norm are equivalent.” They place normalization on different sides of the residual addition and have different training dynamics.
  • “Attention is O(n2)O(n^2) in parameters.” Parameters are O(d2)O(d^2) and independent of nn; the O(n2)O(n^2) cost is in computation and activations.

27. Alternative approaches

  • Recurrent networks (LSTM/GRU): linear-time inference and strong inductive bias for local order, but sequential training and long gradient paths.
  • Convolutional sequence models: local receptive fields, efficient kernels, but long-range dependencies require depth or dilation.
  • State-space models (S4, Mamba): linear or near-linear scaling in sequence length, competitive on long sequences, different inductive bias.
  • Linear attention / Performer: approximate softmax attention with linear cost; trades exactness for scalability.
  • Sparse and sliding-window attention: restrict the attention pattern to reduce O(n2)O(n^2) to O(nn)O(n\sqrt{n}) or O(nw)O(nw).
  • FlashAttention: exact attention with better IO, not a different mathematical model.

29. Research applications

  • Large language models: GPT-style decoders, instruction tuning, and long-context extension.
  • Vision Transformers: split an image into patches and treat them as tokens.
  • Speech and audio: Conformer-style models combine convolution and attention.
  • Biology: protein language models and structure prediction (AlphaFold-style architectures).
  • Multimodal models: cross-attention between text, image, and audio tokens.
  • Efficient inference: KV-cache compression, speculative decoding, and attention-kernel optimization.

30. Important research papers

  • Vaswani et al. (2017), Attention Is All You Need, NeurIPS. The original architecture.
  • Devlin et al. (2018), BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding, NAACL. Bidirectional encoder pretraining.
  • Brown et al. (2020), Language Models are Few-Shot Learners, NeurIPS. GPT-3 and in-context learning at scale.
  • Dao et al. (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness, NeurIPS. IO-aware exact attention.

31. Further reading

  • The Annotated Transformer (Harvard NLP) — a line-by-line PyTorch implementation.
  • Vaswani et al. (2017), plus the original code release.
  • Jay Alammar, The Illustrated Transformer — useful for intuition, but verify formulas against the paper.
  • PyTorch nn.TransformerEncoderLayer documentation for the exact mask and layout conventions.
  • Dao et al. (2022) for the memory hierarchy argument behind FlashAttention.

32. Practical exercises

  1. Implement single-head causal attention in NumPy and verify the 2×22\times2 numerical example in this lesson exactly.
  2. Add multi-head attention with h=2h=2 and dk=d/2d_k=d/2; check that concatenating the heads and applying WOW_O preserves the output shape.
  3. Add a position-wise FFN with dff=4dd_{ff}=4d and count the parameters per block for d=512d=512. Compare with the formula 12d2+4d12d^2+4d.
  4. Implement pre-norm and post-norm blocks. Train both on a tiny sequence task and compare gradient norms in the first few steps.
  5. Prove that unmasked attention is permutation-equivariant, then show empirically that adding positional encodings breaks the symmetry.
  6. Measure attention time for n=128,256,512,1024n=128,256,512,1024 and fit the growth exponent. Explain where the O(n2)O(n^2) term becomes visible.
  7. Break causality deliberately by flipping the mask sign; show that the last-token perturbation changes earlier outputs.

What a correct answer looks like. Items 4, 6 and 7 are measurements, so the expected result is stated rather than a single number.

  1. With X=I2X=I_2 and identity projections, scaled scores are diag⁡(1/2,1/2)\operatorname{diag}(1/\sqrt2,1/\sqrt2). Row 1 attends only to token 1, so y1=(1,0)y_1=(1,0). Row 2 has logits (0,1/2)(0,1/\sqrt2), so weights (0.330,0.670)(0.330,0.670) and y2=(0.330,0.670)y_2=(0.330,0.670).
  2. Each head produces (n,dk)(n,d_k); concatenation gives (n,hdk)=(n,d)(n,h d_k)=(n,d), and WO∈Rd×dW_O\in\mathbb{R}^{d\times d} preserves the shape.
  3. Attention weights are 4d24d^2; the FFN with dff=4dd_{ff}=4d is 8d28d^2; so 12d212d^2 plus O(d)O(d) biases. At d=512d=512 that is about 3.153.15 million weights per block.
  4. Pre-norm blocks usually show larger and more stable gradient norms early; post-norm blocks often need learning-rate warmup. Report the actual curves, not the expectation.
  5. For a permutation matrix PP, Q′=PQQ'=PQ, K′=PKK'=PK, V′=PVV'=PV, so Q′K′⊤=P(QK⊤)P⊤Q'K'^\top=P(QK^\top)P^\top and softmax gives PAP⊤PAP^\top. Hence f(PX)=Pf(X)f(PX)=P f(X): the operator cannot distinguish order, so positions must be injected.
  6. Plot time against nn on log–log axes. Once the n2dn^2d term dominates, the slope approaches 2; at small nn the linear and launch-overhead terms flatten it.
  7. Flipping the mask sign lets each position attend to the future. Perturbing the last token then changes earlier outputs, which is the empirical signature of leakage.

33. Debugging challenges

  • The model trains but validation loss is barely above a unigram baseline. Check the causal mask: if future tokens leak, the training loss is artificially low and generation is inconsistent.
  • Attention logits grow to hundreds and the softmax is one-hot. Check the 1/dk1/\sqrt{d_k} scale and whether QK normalization is needed.
  • Shapes fail at the output projection. Print the shape after concatenating heads; it should be (B,n,d)(B,n,d), not (B,n,h,dk)(B,n,h,d_k) without reshaping.
  • Loss is NaN after a few steps in fp16. Check for −∞-\infty mask entries combined with an unstable softmax implementation; subtract the row maximum before exponentiating.
  • Inference is much slower than training. You are probably recomputing the full prefix instead of using a KV cache.
  • LayerNorm changes the result when you permute tokens. You are normalizing across the sequence axis instead of the feature axis.

35. Interview questions

  • Write the attention equation and explain every symbol and shape.
  • Why divide by dk\sqrt{d_k}? Derive the variance argument.
  • Why is the FFN position-wise, and what would change if it mixed across tokens?
  • What is the difference between pre-norm and post-norm? Why do deep models prefer pre-norm?
  • Why does attention need positional information? Prove permutation equivariance.
  • How does a causal mask work, and how would you test it?
  • Count the parameters in one Transformer block for d=512d=512, dff=2048d_{ff}=2048, ignoring biases.
  • What is the time and memory complexity of attention, and how does FlashAttention change the constants?
  • What does the KV cache store, and why does it grow with context length?
  • Why is p(x)=∏tp(xt∣x<t)p(x)=\prod_t p(x_t\mid x_{<t}) not specific to Transformers?

36. Research questions

  • Which architectural priors improve length generalization beyond the training context?
  • How do attention heads specialize, and can that specialization be predicted or controlled?
  • What is the right trade-off between exact attention, sparse attention, and state-space models for a given workload?
  • How should positional encodings be designed for multimodal sequences with different time scales?
  • Can KV-cache compression preserve long-context accuracy without retraining?
  • What causes attention-logit growth at scale, and which normalization scheme is most robust?

37. Mastery assessment

To demonstrate mastery: (1) write the full pre-norm block equations from memory, with shapes; (2) implement single-head causal attention and pass the causality and permutation tests; (3) derive the 1/dk1/\sqrt{d_k} variance argument and the O(n2d+nd2)O(n^2d+nd^2) per-layer cost; (4) explain the roles of the FFN, residuals, normalization, and positional encoding; (5) diagnose at least three concrete failure modes. A trained large model is not required; a correct small implementation plus a clear derivation is stronger evidence than a copied training script.

39. Completion criteria

All of: attention equation and block equations written correctly; NumPy implementation passing shape, causality, and permutation tests; parameter count checked against 12d2+4d12d^2+4d; complexity derived; three failure modes reproduced or explained. Only then mark the concept as implemented.

Research papers linked to this concept