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.
1. Concept overview
A Transformer is a neural network architecture for sequences. It maps a sequence of token representations
to another sequence of the same shape, using a stack of identical blocks. Each block has two sublayers:
- multi-head self-attention, which lets each position read from other positions;
- 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 : 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 , so it must process tokens sequentially. That creates two problems:
- Long paths for long-range dependencies. Information from token 1 reaches token only after 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 , which becomes the bottleneck for long contexts.
5. First-principles explanation
Start with a set of token vectors . We want a new vector that is a weighted average of information from other tokens, with weights depending on the content of and .
A simple content-based weight is a dot product: . Large positive values mean “ finds relevant.” To turn scores into a convex combination, apply softmax over :
This is the whole idea of attention. The Transformer makes it expressive by (a) learning linear maps , , ; (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 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 be the input, with tokens and model width . Choose heads and per-head width .
Per head :
with . Then
where is an optional mask: for positions that token may not attend to, and otherwise.
Multi-head output:
with .
Pre-norm block (modern default):
Here , , and is applied elementwise (ReLU, GELU or SwiGLU). The original paper used post-norm: .
Causal mask. For autoregressive decoding, set whenever . Then row of the attention matrix has zeros in future positions, so token cannot read token .
8. Notation dictionary
| Symbol | Meaning | Shape | |---|---|---| | | sequence length (number of tokens) | integer | | | model width / hidden dimension | integer | | | number of attention heads | integer | | | per-head dimension, | integer | | | input token representations | | | | query, key, value projections | per head | | | output projection after concatenation | | | | projected queries, keys, values | per head | | | additive attention mask | | | | row-wise normalization | applied to | | | layer normalization | applied per token | | | FFN matrices | , | | | FFN hidden width, often | integer | | | elementwise nonlinearity | function |
9. Step-by-step derivation
Step 1 — attention as a differentiable lookup. Fix a query and keys . The score measures alignment. Softmax converts scores to weights , . The output 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 . If the components of and are independent with mean 0 and variance 1, then has variance . Without scaling, the logits grow like , the softmax saturates, and gradients vanish. Dividing by keeps the logit variance near 1. This is a variance argument, not a cosmetic convention.
Step 3 — batching all queries. Stack queries into and keys into . Then is the 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 -dimensional output; concatenating heads gives channels, and mixes them. The parameter count is dominated by for the four projections, independent of .
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 . It is where most of the parameters live: per layer, which is when .
Step 6 — residual and normalization. A residual connection computes , 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 be an permutation matrix and let with , , . Then .
Proof. , , . Scores are . Softmax commutes with row and column permutations, so the attention matrix becomes . Therefore .
This is exactly why positional information must be added: the bare attention operator cannot see order.
Proposition 2 (causality). If for and finite otherwise, then output row depends only on input rows .
Proof. For , , so . Row of the output is , a combination of the first value rows.
Proposition 3 (parameter count per block). With and biases ignored, one pre-norm block has attention parameters, FFN parameters, and normalization parameters (two LNs with scale and shift). The total is , independent of .
11. Geometric interpretation
Each token is a point in . 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 , , one head, and
Then and . With , the scale is , so the score matrix is
Apply a causal mask: token 1 may attend only to itself, token 2 to both. Row 1 has weights , so . Row 2 has logits ; softmax gives
Thus . The first token's representation is unchanged; the second mixes both tokens. Without the mask, row 1 would also mix, with weights . 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 ; PyTorch's default is , 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 , adds the mask, applies a numerically stable row-wise softmax, and multiplies by . 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 or . 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 before the softmax, so it costs bytes in fp32 (or in fp16). For , , , 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 where is on-chip memory.
The KV cache for autoregressive inference stores keys and values for every past token: values per layer. At long context this grows linearly and can dominate memory. The FFN activations are per layer, usually smaller than the attention matrix for long but larger for short and wide .
20. Time complexity
Per layer, the attention score computation is (or summed over heads), the softmax is , and the output projection is . The FFN is , which is when . For , attention dominates; for short sequences and wide models, the FFN dominates.
A full forward pass through layers is . Autoregressive generation with a KV cache costs per new token for attention (plus for the FFN), so generating tokens costs — still quadratic overall because each step attends to a growing cache.
21. Space complexity
Weights: for attention projections and for FFNs, independent of sequence length. Activations during training: for the attention matrices if materialized, plus for token representations. Inference with a KV cache: for cached keys and values, plus for weights. The quadratic attention activation is the main memory bottleneck for long sequences.
22. Experimental demonstration
- Shape and causality test. Implement the scratch block. Feed a random sequence, then change only the last token. With a causal mask, the first 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.
- 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.
- 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.
- Scaling measurement. Time the attention block for and plot wall-clock time against . 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 may lose at because of memory traffic.
24. Limitations
- Quadratic attention cost. Time and memory grow as 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
- Mask sign or shape error. Adding instead of leaks future tokens; a mask with the wrong broadcast shape silently applies to the wrong axis. Test causality by changing the last token.
- Missing . Logits grow with , the softmax saturates, and gradients vanish. Check the scale of attention logits during training.
- Wrong tensor layout. PyTorch's default is ; passing without
batch_first=Truemixes batch and sequence dimensions. - LayerNorm on the wrong axis. Normalizing across the sequence instead of across features changes the operation entirely. LN normalizes each token's feature vector.
- Positional encoding omitted. The model becomes permutation-equivariant and cannot distinguish word order.
- KV-cache misalignment. Reusing a cache with a different batch order or mask produces plausible but wrong continuations.
- 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 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 ; 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 in parameters.” Parameters are and independent of ; the 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 to or .
- 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.TransformerEncoderLayerdocumentation for the exact mask and layout conventions. - Dao et al. (2022) for the memory hierarchy argument behind FlashAttention.
32. Practical exercises
- Implement single-head causal attention in NumPy and verify the numerical example in this lesson exactly.
- Add multi-head attention with and ; check that concatenating the heads and applying preserves the output shape.
- Add a position-wise FFN with and count the parameters per block for . Compare with the formula .
- Implement pre-norm and post-norm blocks. Train both on a tiny sequence task and compare gradient norms in the first few steps.
- Prove that unmasked attention is permutation-equivariant, then show empirically that adding positional encodings breaks the symmetry.
- Measure attention time for and fit the growth exponent. Explain where the term becomes visible.
- 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.
- With and identity projections, scaled scores are . Row 1 attends only to token 1, so . Row 2 has logits , so weights and .
- Each head produces ; concatenation gives , and preserves the shape.
- Attention weights are ; the FFN with is ; so plus biases. At that is about million weights per block.
- 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.
- For a permutation matrix , , , , so and softmax gives . Hence : the operator cannot distinguish order, so positions must be injected.
- Plot time against on log–log axes. Once the term dominates, the slope approaches 2; at small the linear and launch-overhead terms flatten it.
- 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 scale and whether QK normalization is needed.
- Shapes fail at the output projection. Print the shape after concatenating heads; it should be , not without reshaping.
- Loss is NaN after a few steps in fp16. Check for 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 ? 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 , , 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 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 variance argument and the 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 ; complexity derived; three failure modes reproduced or explained. Only then mark the concept as implemented.