Skip to content
Transformers and LLMs Core 24 min read

The transformer block

A transformer is one block repeated: normalise, let the positions talk to each other (attention), normalise, let each position think on its own (an MLP), and add both results back onto a running sum called the residual stream. Every design choice in that sentence has a reason, and the reasons tell you what will break if you change it.

10,000 ft

Every large language model — GPT, Llama, Claude, Gemini, DeepSeek — is a stack of nearly identical transformer blocks, 12 in GPT-2 small and 126 in Llama 3 405B. The block combines four ideas from across deep learning: multi-head attention to move information between positions; a per-position MLP (from neurons and MLPs) holding about two thirds of the parameters; residual connections (from ResNets) so that a hundred layers can be trained; and normalisation (from initialisation and normalisation) to keep activations at a stable scale. Its parameter count, \(\approx 12d^2\) per block, is the basis of every scaling law and compute estimate. Change the block and you change the field: most "new architectures" since 2017 are edits to it.

2,000 ft

The residual stream \(\mathbf{x}\) is a vector per token that flows through the whole network. Each block reads from it and writes back to it, twice:

  1. Normalise a copy: \(\mathbf{u} = \operatorname{Norm}(\mathbf{x})\).
  2. Communicate: multi-head (causal) attention over all positions, and add the result: \(\mathbf{x} \leftarrow \mathbf{x} + \operatorname{Attn}(\mathbf{u})\).
  3. Normalise again: \(\mathbf{u} = \operatorname{Norm}(\mathbf{x})\).
  4. Compute: a two-layer MLP applied to each position independently, and add: \(\mathbf{x} \leftarrow \mathbf{x} + \operatorname{MLP}(\mathbf{u})\).

Stack \(L\) blocks between an embedding lookup at the bottom and a final norm plus unembedding (projection to vocabulary logits) at the top.

A pre-norm transformer block (GPT-2 and Llama style)
A pre-norm transformer block (GPT-2 and Llama style). residual stream x (n × d), Norm (LayerNorm / RMSNorm), Multi-head causal attention (positions communicate), x + Attn(Norm(x)), Norm, MLP, per position d → 4d → d (or SwiGLU), x + MLP(Norm(x)), residual stream to next block, skipA pre-norm transformer block (GPT-2 and Llama style). residual stream x (n × d), Norm (LayerNorm / RMSNorm), Multi-head causal attention (positions communicate), x + Attn(Norm(x)), Norm, MLP, per position d → 4d → d (or SwiGLU), x + MLP(Norm(x)), residual stream to next block, skip

Ground level

The residual stream

Start with the part that looks least important: the +. Each sub-layer computes a change and adds it to \(\mathbf{x}\) rather than replacing \(\mathbf{x}\). So the vector at a position after \(L\) blocks is

\[ \mathbf{x}_L = \mathbf{x}_0 + \sum_{\ell=1}^{L}\big(\text{attn}_\ell + \text{mlp}_\ell\big), \]

the token's embedding plus every layer's contribution. This makes the residual stream a shared communication bus: any layer can read what any earlier layer wrote, as long as they agree on which directions of the \(d\)-dimensional space carry what. That is how the induction head on the multi-head page works — layer 2 reads a slot that layer 1 filled. Anthropic's circuits work made this the standard way to read transformers (A Mathematical Framework for Transformer Circuits).

It also makes training work. The derivative of \(\mathbf{x} + f(\mathbf{x})\) is \(I + \partial f/\partial\mathbf{x}\): there is always an identity path for the gradient from the loss straight back to any layer, however deep the stack.

The residual stream: every sub-layer reads a normalised copy and adds its write back
The residual stream: every sub-layer reads a normalised copy and adds its write back. token + position embedding, stream, final norm → unembed → logits, attn 1, mlp 1, attn 2, mlp 2, read, +=The residual stream: every sub-layer reads a normalised copy and adds its write back. token + position embedding, stream, final norm → unembed → logits, attn 1, mlp 1, attn 2, mlp 2, read, +=

Attention communicates, the MLP computes

The two sub-layers divide the work cleanly:

  • Attention is the only place where information moves between positions. Given the attention weights, it is linear in the values — a weighted average of linearly projected vectors.
  • The MLP is applied to each position separately and identically (the 2017 paper calls it "position-wise"; equivalently, two convolutions with kernel size 1). It never looks at other positions. It is where most of the nonlinearity and most of the parameters live.

Neither alone is enough. Attention without MLPs and without residual connections has a striking failure, proved by Dong, Cordonnier and Loukas: "without skip connections or multi-layer perceptrons (MLPs), the output converges doubly exponentially to a rank-1 matrix" — every token ends up with the same vector (arXiv:2103.03404). Repeated averaging smooths away all differences. You can watch it happen (real output of the third snippet in Build it; "spread" is 1 when tokens share nothing and 0 when they are identical):

attention only                L1:0.858  L2:0.358  L4:0.000  L8:0.000  L16:0.000  L24:0.000
attention + residual          L1:0.986  L2:0.967  L4:0.907  L8:0.498  L16:0.040  L24:0.002
+ residual, writes / sqrt(2L) L1:0.990  L2:0.991  L4:0.991  L8:0.988  L16:0.985  L24:0.982

Pure attention collapses by layer 4. The residual connection slows the collapse to a crawl; residual writes scaled down at initialisation (as GPT-2 does) keep the tokens distinct through all 24 layers. Training then has a well-conditioned starting point to improve on.

The MLP: where the parameters are

The original MLP is \(\operatorname{FFN}(\mathbf{u}) = \max(0, \mathbf{u}W_1 + \mathbf{b}_1)W_2 + \mathbf{b}_2\) with \(W_1 \in \mathbb{R}^{d \times 4d}\), \(W_2 \in \mathbb{R}^{4d \times d}\): expand to four times the width, apply a nonlinearity, project back. That is \(8d^2\) parameters against attention's \(4d^2\) — two thirds of each block. GPT-2 and BERT replaced ReLU with GELU, \(\mathbf{u}\,\Phi(\mathbf{u})\) with \(\Phi\) the standard normal CDF (Hendrycks & Gimpel, arXiv:1606.08415).

A useful way to read the MLP, from Geva et al.: the rows of \(W_1\) are keys that detect patterns in the input, and the rows of \(W_2\) are values written to the residual stream when their key fires. They showed "feed-forward layers in transformer-based language models operate as key-value memories, where each key correlates with textual patterns in the training examples, and each value induces a distribution over the output vocabulary" (arXiv:2012.14913). Much factual recall appears to be stored this way (3Blue1Brown's How might LLMs store facts visualises it).

Gated MLPs. Modern models use a GLU variant: two parallel input projections, one passed through an activation and used as a gate on the other.

\[ \operatorname{SwiGLU}(\mathbf{u}) = \big(\operatorname{SiLU}(\mathbf{u}W_1) \odot \mathbf{u}W_3\big)\,W_2,\qquad \operatorname{SiLU}(z) = z\,\sigma(z). \]

Shazeer found these variants improve perplexity at equal parameter count, and was unusually frank about why: "We offer no explanation as to why these architectures seem to work; we attribute their success, as all else, to divine benevolence" (GLU Variants Improve Transformer, arXiv:2002.05202). Three matrices instead of two means the hidden width shrinks to keep parameters fixed: \(3 \cdot d \cdot d_{ff} = 8d^2\) gives \(d_{ff} = \tfrac{8}{3}d\) (Shazeer's experiments went from \(d_{ff} = 3072\) to \(2048\)). In practice models round up: Llama 3 8B uses \(d = 4096\) and \(d_{ff} = 14{,}336 = 3.5d\) (Llama 3 paper, Table 3).

Normalisation: keeping the scale fixed

Every sub-layer receives a normalised copy of the residual stream, so its input has a predictable scale however large the stream has grown. Two variants are in use.

LayerNorm (Ba, Kiros, Hinton, arXiv:1607.06450) normalises each token's vector across its \(d\) features, then rescales with learned gain \(\boldsymbol{\gamma}\) and bias \(\boldsymbol{\beta}\):

\[ \operatorname{LN}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol{\beta},\qquad \mu = \frac{1}{d}\sum_i x_i,\quad \sigma^2 = \frac{1}{d}\sum_i (x_i - \mu)^2 . \]

RMSNorm (Zhang & Sennrich, arXiv:1910.07467) drops the mean subtraction and the bias:

\[ \operatorname{RMSNorm}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x}}{\sqrt{\tfrac{1}{d}\sum_i x_i^2 + \epsilon}} . \]

It is cheaper (one reduction instead of two) and works as well in practice; Llama and most recent open models use it. Unlike BatchNorm, both normalise within a token, so they behave identically in training and inference and don't care about batch size or sequence position.

Where the norm goes: post-norm and pre-norm

The 2017 transformer applied the norm after each residual addition — post-norm: \(\mathbf{x} \leftarrow \operatorname{LN}(\mathbf{x} + f(\mathbf{x}))\). GPT-2 moved it to the input of each sub-block — pre-norm: \(\mathbf{x} \leftarrow \mathbf{x} + f(\operatorname{LN}(\mathbf{x}))\) — and added a final norm after the last block (GPT-2 paper, §2.3).

The difference is whether the identity path is clean. In post-norm every block's output passes through a normalisation, so the gradient to early layers is repeatedly rescaled. Xiong et al. proved that at initialisation, for post-norm, "the expected gradients of the parameters near the output layer are large", which is why post-norm transformers need a careful learning-rate warm-up; with pre-norm "the gradients are well-behaved at initialization", and they trained pre-norm models without warm-up (arXiv:2002.04745). Pre-norm became the default for LLMs. (Post-norm is not dead: DeepNet rescales the residual branch to combine, in its authors' words, the "good performance of Post-LN and stable training of Pre-LN", training 1,000-layer models — arXiv:2203.00555.)

Post-norm (2017) vs pre-norm (GPT-2 onward)
Post-norm (2017) vs pre-norm (GPT-2 onward). Post-norm, x, sublayer f, x + f(x), LayerNorm, Pre-norm, Norm, x + f(Norm(x)), clean identity pathPost-norm (2017) vs pre-norm (GPT-2 onward). Post-norm, x, sublayer f, x + f(x), LayerNorm, Pre-norm, Norm, x + f(Norm(x)), clean identity path

From blocks to a model

The full decoder-only model (GPT, Llama):

  1. Embed: token id → row of \(E \in \mathbb{R}^{|V| \times d}\) (see tokenisation); in GPT-2 also add a learned position embedding (modern models instead rotate queries and keys, see positional encoding).
  2. Blocks: \(L\) pre-norm blocks with causal attention.
  3. Final norm, then unembed: logits \(= \operatorname{Norm}(\mathbf{x}_L)\,W_U\) with \(W_U \in \mathbb{R}^{d \times |V|}\). GPT-2 ties \(W_U = E^\top\); Llama 3 does not.
  4. Softmax over the vocabulary gives the next-token distribution for every position at once (training uses all of them; generation uses the last; see the language-modelling objective).

The same block, with or without the causal mask and with or without cross-attention, gives the three families: encoder-only (BERT: unmasked attention, for understanding tasks), decoder-only (GPT and nearly every LLM: causal), and encoder–decoder (the original transformer and T5: an unmasked encoder plus a causal decoder whose blocks have an extra cross-attention sub-layer).

Worked example: where GPT-2's 124 million parameters are

GPT-2 small: \(d = 768\), \(L = 12\), \(|V| = 50{,}257\), context 1,024, biases everywhere, tied unembedding. Counting every matrix (real output of the first snippet in Build it):

Component Formula Parameters
Attention per block \(d \cdot 3d + 3d\) (fused QKV) \(+ d^2 + d\) 2,362,368
MLP per block \(d \cdot 4d + 4d + 4d \cdot d + d\) 4,722,432
2 LayerNorms per block \(2 \cdot 2d\) 3,072
One block \(\approx 12d^2 = 7{,}077{,}888\) 7,087,872
12 blocks 85,054,464
Token + position embeddings \(50{,}257 \cdot 768 + 1{,}024 \cdot 768\) 39,383,808
Final LayerNorm \(2d\) 1,536
Total 124,439,808

The "124M" of GPT-2 small is exact. Two lessons: \(12d^2\) per block is accurate to 0.14%, and at this small size the embeddings are almost a third of the model. For Llama 3 8B (\(d = 4096\), 32 blocks, 8 key/value heads, SwiGLU with \(d_{ff} = 14{,}336\), no biases, untied output, 128K vocabulary) the same count gives 218,112,000 per block — attention 41.9M, MLP 176.2M, now 81% MLP because of GQA's smaller key/value projections and the wider SwiGLU — and 8.03B in total.

How the block has changed, 2017 → 2024

Transformer (2017) GPT-2 (2019) Llama 3 (2024)
Stack encoder–decoder decoder-only decoder-only
Norm LayerNorm, post LayerNorm, pre + final RMSNorm, pre + final
Position sinusoidal, added learned, added RoPE on Q and K
Attention MHA MHA GQA, 8 KV heads
MLP ReLU, \(4d\) GELU, \(4d\) SwiGLU, \(3.5d\)
Biases yes yes no
Unembedding tied tied untied

The block's skeleton — norm, attention, add, norm, MLP, add — has not changed. Everything else has been tuned. PaLM tried running attention and MLP in parallel from the same normalised input, \(\mathbf{y} = \mathbf{x} + \operatorname{MLP}(\operatorname{LN}(\mathbf{x})) + \operatorname{Attn}(\operatorname{LN}(\mathbf{x}))\), reporting "roughly 15% faster training speed at large scales" with "no quality degradation at 62B scale" (PaLM, arXiv:2204.02311) — evidence that the order of the two sub-layers matters less than you might expect.

History

From ResNet to the LLM block

2015 — He et al. introduce residual connections to train 152-layer image networks (arXiv:1512.03385). 2016 — Layer normalisation (Ba, Kiros, Hinton); GELU (Hendrycks & Gimpel); gated linear units for language modelling (Dauphin et al., arXiv:1612.08083). 2017 — the transformer block: post-norm, ReLU MLP of width \(4d\), dropout 0.1 (arXiv:1706.03762). 2019 — GPT-2 moves to pre-norm with a final norm and scales residual-layer weights by \(1/\sqrt{N}\) at initialisation; RMSNorm is proposed. 2020 — Xiong et al. explain why pre-norm removes the need for warm-up; Shazeer's GLU variants; Kaplan et al. show performance depends "very mildly" on depth versus width at fixed parameter count (arXiv:2001.08361). 2021 — the residual-stream view of transformers. 2022–2023 — PaLM and LLaMA settle the modern recipe: pre-RMSNorm, SwiGLU, RoPE, no biases.

First principles

Build the block from requirements.

1. Positions must exchange information, in a content-dependent way, for any sequence length. That is attention (see first principles of attention). But attention is an averaging operation: each output is a convex combination of value vectors. Stacked alone it smooths everything to the mean — the rank-collapse result.

2. Each position must then transform what it gathered nonlinearly. A per-position MLP adds the nonlinearity and capacity. Applying it per position (rather than across the sequence) keeps the cost linear in \(n\) and lets every position share the same weights, like a convolution with kernel size 1. Interleaving the two — mix, transform, mix, transform — is the same pattern as alternating spatial and channel mixing in vision networks.

3. The stack must be deep and still trainable. Depth lets later layers compose earlier features (the induction head needs two layers; real circuits need many). Residual connections give each layer an identity path, so the network starts close to the identity function and each layer learns a correction; gradients reach early layers undiminished.

4. The scale must not drift. Every sub-layer adds to the stream, so the stream's norm grows with depth (you can see it creep up in the Build it output). Normalising the input to each sub-layer (pre-norm) decouples the sub-layer's behaviour from that growth while leaving the stream itself, and its identity path, untouched. Initialising the output projections small (GPT-2's \(1/\sqrt{N}\)) keeps the early sum of writes from swamping the embedding.

What breaks if you change it? Remove the MLP: rank collapse and no per-token nonlinearity. Remove attention: positions never interact; the model is a bag of independent token classifiers. Remove the residual: deep stacks don't train and collapse even faster. Remove the norm: activations and gradients drift with depth and training becomes unstable at scale. Move the norm after the addition: you need warm-up and careful tuning.

The maths

Pre-norm block. For residual stream \(X \in \mathbb{R}^{n \times d}\),

\[ H = X + \operatorname{MHA}\big(\operatorname{Norm}_1(X)\big),\qquad Y = H + \operatorname{MLP}\big(\operatorname{Norm}_2(H)\big), \]

with Norm applied row-wise (per token). \(\operatorname{MLP}(U) = \phi(UW_1 + \mathbf{b}_1)W_2 + \mathbf{b}_2\), \(W_1 \in \mathbb{R}^{d \times d_{ff}}\), \(W_2 \in \mathbb{R}^{d_{ff} \times d}\), or SwiGLU as above.

The model. For token ids \(t_1..t_n\): \(X_0 = E[t_{1:n}] \,(+\, P_{1:n})\), \(X_\ell = \operatorname{Block}_\ell(X_{\ell-1})\), logits \(Z = \operatorname{Norm}_f(X_L)\,W_U \in \mathbb{R}^{n \times |V|}\), and \(p(t_{i+1} \mid t_{\le i}) = \operatorname{softmax}(Z_i)\).

Derivation: the identity path through a residual stack

Write each sub-layer as \(\mathbf{x}_{k+1} = \mathbf{x}_k + f_k(\mathbf{x}_k)\) (in pre-norm, \(f_k\) includes its own normalisation). The Jacobian of one step is \(I + J_k\) with \(J_k = \partial f_k/\partial\mathbf{x}_k\). By the chain rule (see the multivariable chain rule),

\[ \frac{\partial \mathbf{x}_K}{\partial \mathbf{x}_k} = \prod_{m=k}^{K-1}(I + J_m) = I + \sum_{m} J_m + \sum_{m < m'} J_{m'}J_m + \cdots \]

The leading \(I\) means \(\partial L/\partial\mathbf{x}_k = \partial L/\partial\mathbf{x}_K \,(I + \dots)\): the gradient at the top reaches every layer directly, plus correction terms. Without residuals the Jacobian is \(\prod_m J_m\), a product of \(K\) matrices whose norm tends to shrink or explode geometrically with \(K\).

In post-norm, \(\mathbf{x}_{k+1} = \operatorname{LN}(\mathbf{x}_k + f_k(\mathbf{x}_k))\), so each factor becomes \(J_{\text{LN}}(I + J_k)\). The LayerNorm Jacobian \(J_{\text{LN}} = \operatorname{diag}(\boldsymbol\gamma)\,\frac{1}{\sigma}\big(I - \tfrac{1}{d}\mathbf{1}\mathbf{1}^\top - \tfrac{1}{d}\hat{\mathbf{x}}\hat{\mathbf{x}}^\top\big)\) (with \(\hat{\mathbf{x}} = (\mathbf{x}-\mu)/\sigma\)) rescales by \(1/\sigma\) at every layer, so there is no clean identity path; this is the root of post-norm's sensitivity analysed by Xiong et al.

Derivation: parameters and FLOPs per block

With \(d_\text{attn} = d\) and \(d_{ff} = 4d\), ignoring biases and norms:

  • attention: \(W_Q, W_K, W_V, W_O\) are \(d \times d\) → \(4d^2\);
  • MLP: \(W_1\) is \(d \times 4d\), \(W_2\) is \(4d \times d\) → \(8d^2\);
  • block total \(12d^2\), so the non-embedding parameter count is \(N \approx 12\,L\,d^2\) — Kaplan et al.'s Eq. 2.1 (arXiv:2001.08361).

A matrix–vector product with an \(a \times b\) matrix costs \(2ab\) FLOPs (one multiply, one add per weight). So a forward pass costs \(2N\) FLOPs per token for the weight matmuls, plus attention's scores and weighted sums: \(2 \cdot n_\text{ctx} \cdot d\) per layer per token (for \(QK^\top\) and \(AV\), each \(n_\text{ctx} \cdot d\) multiply-adds), giving Kaplan's

\[ C_\text{forward} \approx 2N + 2\,L\,n_\text{ctx}\,d . \]

The backward pass costs about twice the forward, so training costs \(\approx 6N\) FLOPs per token when \(n_\text{ctx} \ll 12d\). (Kaplan's version counts \(n_\text{ctx}\) in full; a causal implementation that skips masked entries does about half the attention work.)

SwiGLU sizing. Equal parameters to a \(4d\) MLP: \(3 d\, d_{ff} = 8d^2 \Rightarrow d_{ff} = \tfrac{8}{3}d\).

LayerNorm vs RMSNorm. If the features already have zero mean, \(\sigma^2 = \tfrac{1}{d}\sum x_i^2\) and LayerNorm (without \(\boldsymbol\beta\)) equals RMSNorm. RMSNorm keeps only the re-scaling invariance (output unchanged if \(\mathbf{x} \to c\mathbf{x}\), \(c > 0\)), dropping re-centring invariance.

Build it

1. Count GPT-2's parameters, and Llama 3 8B's:

# GPT-2 small (124M): count every parameter, layer by layer
d, L, V, ctx = 768, 12, 50257, 1024
ln = 2 * d                                   # LayerNorm gain + bias
attn = (d * 3 * d + 3 * d) + (d * d + d)     # fused QKV projection + output projection, with biases
mlp = (d * 4 * d + 4 * d) + (4 * d * d + d)  # up to 4d, GELU, back down to d
block = ln + attn + ln + mlp
emb = V * d + ctx * d                        # token + learned position embeddings (lm_head tied)
total = emb + L * block + ln
print(f"per block {block:,} (attn {attn:,}, mlp {mlp:,}) | 12 d^2 = {12 * d * d:,}")
print(f"embeddings {emb:,} | blocks {L * block:,} | total {total:,}")

# Llama 3 8B: GQA + SwiGLU + RMSNorm, no biases, untied output (shapes from the Llama 3 paper)
d, L, V, h, kv, dff = 4096, 32, 128_000, 32, 8, 14_336
dh = d // h
attn = d * d + 2 * d * (kv * dh) + d * d     # W_Q, W_K, W_V (8 KV heads), W_O
mlp = 3 * d * dff                            # gate, up, down
block = attn + mlp + 2 * d                   # two RMSNorm gains
total = L * block + 2 * V * d + d            # + embedding, output head, final norm
print(f"Llama 3 8B: per block {block:,} (attn {attn:,}, mlp {mlp:,}) | total {total/1e9:.2f}B")
per block 7,087,872 (attn 2,362,368, mlp 4,722,432) | 12 d^2 = 7,077,888
embeddings 39,383,808 | blocks 85,054,464 | total 124,439,808
Llama 3 8B: per block 218,112,000 (attn 41,943,040, mlp 176,160,768) | total 8.03B

2. A Llama-style block in NumPy — RMSNorm, causal multi-head attention, SwiGLU, pre-norm residuals, small initialisation of the residual writes — stacked eight deep:

import numpy as np
rng = np.random.default_rng(0)

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

def rmsnorm(x, g, eps=1e-6):
    return g * x / np.sqrt((x * x).mean(-1, keepdims=True) + eps)

def attn(x, Wq, Wk, Wv, Wo, h):
    T, d = x.shape; dh = d // h
    q, k, v = (np.moveaxis((x @ W).reshape(T, h, dh), 1, 0) for W in (Wq, Wk, Wv))  # (h, T, dh)
    s = q @ k.transpose(0, 2, 1) / np.sqrt(dh)
    s = np.where(np.tril(np.ones((T, T), bool)), s, -np.inf)
    return np.moveaxis(softmax(s) @ v, 0, 1).reshape(T, d) @ Wo

def swiglu(x, W1, W3, W2):
    a = x @ W1
    return ((a / (1 + np.exp(-a))) * (x @ W3)) @ W2         # SiLU(x W1) * (x W3), then down

def block(x, p, h):
    """Pre-norm block, Llama style: x + Attn(Norm(x)), then + MLP(Norm(.))."""
    x = x + attn(rmsnorm(x, p["g1"]), p["Wq"], p["Wk"], p["Wv"], p["Wo"], h)
    x = x + swiglu(rmsnorm(x, p["g2"]), p["W1"], p["W3"], p["W2"])
    return x

def init(d, d_ff, n_layers):
    s, so = 1 / np.sqrt(d), 1 / np.sqrt(d) / np.sqrt(2 * n_layers)   # shrink residual writes
    return {"g1": np.ones(d), "g2": np.ones(d),
            "Wq": rng.normal(0, s, (d, d)), "Wk": rng.normal(0, s, (d, d)),
            "Wv": rng.normal(0, s, (d, d)), "Wo": rng.normal(0, so, (d, d)),
            "W1": rng.normal(0, s, (d, d_ff)), "W3": rng.normal(0, s, (d, d_ff)),
            "W2": rng.normal(0, so * np.sqrt(d / d_ff), (d_ff, d))}

T, d, h, L = 16, 64, 4, 8
d_ff = int(8 * d / 3)                                     # SwiGLU keeps ~8d^2 MLP params
layers = [init(d, d_ff, L) for _ in range(L)]
x = rng.standard_normal((T, d))
for i, p in enumerate(layers):
    x = block(x, p, h)
    print(f"after block {i+1}: shape {x.shape}, residual-stream RMS {np.sqrt((x**2).mean()):.3f}")
print("params per block:", sum(v.size for v in layers[0].values()), "| 12 d^2 =", 12 * d * d)
after block 1: shape (16, 64), residual-stream RMS 1.025
after block 2: shape (16, 64), residual-stream RMS 1.048
after block 3: shape (16, 64), residual-stream RMS 1.069
after block 4: shape (16, 64), residual-stream RMS 1.098
after block 5: shape (16, 64), residual-stream RMS 1.121
after block 6: shape (16, 64), residual-stream RMS 1.138
after block 7: shape (16, 64), residual-stream RMS 1.153
after block 8: shape (16, 64), residual-stream RMS 1.173
params per block: 49152 | 12 d^2 = 49152

The shape never changes — a block maps \((n, d)\) to \((n, d)\), which is what lets you stack any number of them — and the stream grows slowly as each block adds its write. (With \(d_{ff} = \lfloor 8d/3 \rfloor = 170\) the parameter count happens to land exactly on \(12d^2\) here.)

3. Rank collapse, the experiment quoted in Attention communicates, the MLP computes:

import numpy as np
rng = np.random.default_rng(1)

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

def spread(X):
    """How far the token vectors are from all being identical (1 = no shared part, 0 = rank-1 collapse)."""
    return np.linalg.norm(X - X.mean(0, keepdims=True)) / np.linalg.norm(X)

T, d, L = 32, 64, 24
X0 = rng.standard_normal((T, d))
Ws = [[rng.normal(0, 1 / np.sqrt(d), (d, d)) for _ in range(3)] for _ in range(L)]
for name, skip, alpha in (("attention only               ", False, 1.0),
                          ("attention + residual         ", True, 1.0),
                          ("+ residual, writes / sqrt(2L)", True, 1 / np.sqrt(2 * L))):
    X, row = X0.copy(), []
    for l, (Wq, Wk, Wv) in enumerate(Ws):
        out = alpha * softmax((X @ Wq) @ (X @ Wk).T / np.sqrt(d)) @ X @ Wv
        X = X + out if skip else out
        X = X / np.sqrt((X**2).mean())                    # rescale: only the *shape* matters
        if l + 1 in (1, 2, 4, 8, 16, 24):
            row.append(f"L{l+1}:{spread(X):.3f}")
    print(name, "  ".join(row))

Output is shown above.

Things to try

  • In snippet 2, switch to post-norm (x = rmsnorm(x + attn(x, ...))) and compare the residual-stream RMS across layers.
  • Remove the / np.sqrt(2 * n_layers) from init and stack 48 blocks. How fast does the RMS grow now?
  • Add a random ReLU MLP to the "attention + residual" row of snippet 3. Does it stop the collapse with random weights? (It doesn't much — the theorem says MLPs can prevent collapse, not that random ones will. Trained weights are what keep tokens distinct.)
  • Write the parallel (PaLM-style) block and check its output shape and parameter count are unchanged.
  • Using the FLOPs formula, estimate the forward FLOPs per token of GPT-2 small at \(n_\text{ctx} = 1024\). What fraction is attention scores?

In practice

  • Default recipe (as of 2026) for a new decoder: pre-norm RMSNorm, RoPE, GQA, SwiGLU with \(d_{ff} \approx 2.7\)–\(3.5d\), no biases, \(d_h = 128\). Most labs' published architectures are small departures from this.
  • Width vs depth matters less than total parameters over a broad range (Kaplan et al., Figure 5), so shapes are chosen for hardware: \(d\) a multiple of 128 or larger powers of two, \(d_{ff}\) rounded to tile sizes.
  • Training instability at scale usually shows up as loss spikes from growing attention logits or residual norms. Common fixes: QK-norm, lower learning rate, z-loss on the output logits, gradient clipping; see a recipe for training networks.
  • Interpretability tools read the residual stream: projecting an intermediate \(\mathbf{x}_\ell\) through the final norm and unembedding (the "logit lens") shows which token the model is leaning towards at each layer.

Check yourself

Which sub-layer moves information between positions, and which holds most of the parameters?

Attention is the only sub-layer that mixes positions. The MLP holds most parameters: \(8d^2\) of the \(12d^2\) per block in the classic design (and about 81% of each Llama 3 8B block).

Write the pre-norm and post-norm updates. Which has a clean identity path from output to input?

Pre-norm: \(\mathbf{x} \leftarrow \mathbf{x} + f(\operatorname{Norm}(\mathbf{x}))\). Post-norm: \(\mathbf{x} \leftarrow \operatorname{Norm}(\mathbf{x} + f(\mathbf{x}))\). Pre-norm keeps the residual sum untouched, so \(\partial \mathbf{x}_K/\partial \mathbf{x}_k\) contains an exact identity term; post-norm passes every step through a normalisation Jacobian.

Using N ≈ 12·L·d², estimate the non-embedding parameters of GPT-3 175B (96 layers, d = 12,288).

\(12 \times 96 \times 12{,}288^2 = 12 \times 96 \times 150{,}994{,}944 \approx 1.739 \times 10^{11}\) — about 174B, within 1% of the reported 175B (the embeddings add about 0.6B).

Why does SwiGLU use d_ff ≈ 8d/3 rather than 4d?

SwiGLU has three weight matrices (\(W_1, W_3\) of \(d \times d_{ff}\) and \(W_2\) of \(d_{ff} \times d\)) instead of two. Keeping parameters equal to the \(8d^2\) of a \(4d\) two-matrix MLP requires \(3d\,d_{ff} = 8d^2\), so \(d_{ff} = 8d/3\).

What does RMSNorm drop compared with LayerNorm, and what invariance does it lose?

It drops the mean subtraction and the bias \(\boldsymbol\beta\). Its output is invariant to rescaling the input but not to adding a constant to all features (re-centring).

Why does pure stacked self-attention converge to identical token vectors?

Each layer replaces every token with a convex combination (weighted average) of linearly transformed tokens. Repeated averaging is a contraction towards the common mean; Dong et al. show the distance from rank 1 shrinks doubly exponentially with depth. Residual connections re-inject each token's own vector, and MLPs add per-token nonlinear structure, preventing the collapse.

Hard: the training-compute rule C ≈ 6ND ignores attention. When does that stop being a good approximation?

Per token, attention adds about \(2\,L\,n_\text{ctx}\,d\) forward FLOPs against \(2N \approx 24\,L\,d^2\). The ratio is \(n_\text{ctx}/(12d)\). For GPT-3 (\(d = 12{,}288\), \(n_\text{ctx} = 2048\)) it is about 1.4%; for a long-context run at \(n_\text{ctx} = 128\text{K}\) with \(d = 4096\) it is about 2.7× — attention dominates and \(6ND\) badly underestimates.

Hard: why can't you simply remove all normalisation if you initialise carefully?

Careful initialisation fixes the scale at step 0, but training changes the weights: residual writes grow, attention logits grow, and the scale drifts layer by layer. Normalisation keeps each sub-layer's input scale fixed throughout training. Norm-free training is possible with special schemes but has proved fragile at LLM scale.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Code

  • karpathy/nanoGPT — Block, MLP, CausalSelfAttention in about 100 lines.
  • meta-llama/llama3 — model.py: RMSNorm, SwiGLU FeedForward, GQA, RoPE — the modern block.

Where this leads