The Transformer Block
A transformer is a stack of identical blocks, each made of two sublayers: multi-head self-attention, which mixes information between positions, and a position-wise MLP, which processes each position on its own. Each sublayer is wrapped in normalization and a residual connection. This lesson assembles the pieces of the previous lessons into one working pre-norm decoder block in NumPy.
The equations
For a sequence of hidden vectors , a pre-norm block computes
with causal multi-head attention, LayerNorm or RMSNorm, and an MLP that expands to (GELU) or uses SwiGLU with hidden size about . The residual connections form a "stream" that every sublayer reads from and adds to.
A full decoder-only language model is: token embedding, blocks, a final norm, and an output projection to vocabulary logits.
import numpy as np
rng = np.random.default_rng(0)
n, d, h, d_ff = 6, 32, 4, 128
dh = d // h
p = {k: rng.normal(0, 0.02, s) for k, s in
[("Wq", (d, d)), ("Wk", (d, d)), ("Wv", (d, d)), ("Wo", (d, d)), ("W1", (d, d_ff)), ("W2", (d_ff, d))]}
g1, g2 = np.ones(d), np.ones(d)
def rmsnorm(x, g): return g * x / np.sqrt(np.mean(x**2, -1, keepdims=True) + 1e-6)
def gelu(x): return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
def attention(x):
q, k, v = (np.reshape(x @ p[w], (n, h, dh)).transpose(1, 0, 2) for w in ("Wq", "Wk", "Wv"))
s = q @ k.transpose(0, 2, 1) / np.sqrt(dh) + np.triu(np.full((n, n), -1e9), 1)
a = np.exp(s - s.max(-1, keepdims=True)); a /= a.sum(-1, keepdims=True)
return (a @ v).transpose(1, 0, 2).reshape(n, d) @ p["Wo"]
def block(x):
x = x + attention(rmsnorm(x, g1))
return x + gelu(rmsnorm(x, g2) @ p["W1"]) @ p["W2"]
X = rng.normal(size=(n, d))
Y = block(X)
print("input", X.shape, "-> output", Y.shape)
print("block parameters:", sum(v.size for v in p.values()) + 2 * d, " (12 d^2 + 2d =", 12 * d * d + 2 * d, ")")
print("small init keeps the block near the identity: relative change", round(float(np.linalg.norm(Y - X) / np.linalg.norm(X)), 4))input (6, 32) -> output (6, 32)
block parameters: 12352 (12 d^2 + 2d = 12352 )
small init keeps the block near the identity: relative change 0.0181
Who does what
- Attention is the only place where positions exchange information. It is linear in the values, with data-dependent weights.
- The MLP acts on each position independently, holds about two thirds of the block's parameters, and is often described as the model's key-value memory of facts.
- Norms keep each sublayer's input well scaled; residuals keep gradients flowing and let each block make small refinements.
Parameter count per block
Ignoring biases and norm gains, attention has parameters and a MLP has , so a block has about . A SwiGLU MLP has three matrices of size , again . A model with blocks has roughly non-embedding parameters (Counting Parameters and FLOPs).
configs = {"GPT-2 small": (12, 768, 50257), "GPT-2 XL": (48, 1600, 50257), "a 7B-class model": (32, 4096, 32000)}
for name, (L, d, V) in configs.items():
blocks = 12 * L * d * d
emb = V * d
print(f"{name:16s}: blocks {blocks / 1e6:8.1f}M + embedding {emb / 1e6:6.1f}M = {(blocks + emb) / 1e6:8.1f}M")GPT-2 small : blocks 84.9M + embedding 38.6M = 123.5M
GPT-2 XL : blocks 1474.6M + embedding 80.4M = 1555.0M
a 7B-class model: blocks 6442.5M + embedding 131.1M = 6573.5M
GPT-2 small comes out at about 124M, matching its published size; the 7B-class estimate is a little below 7B because Llama-style MLPs are slightly wider than and the output matrix is not tied.
Encoders, decoders and both
The block above is a decoder block (causal). Encoder blocks (BERT) drop the mask. The original encoder-decoder transformer adds a third sublayer to each decoder block: cross-attention, whose queries come from the decoder and keys and values from the encoder output. Modern LLMs are decoder-only.
In software
nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward, norm_first=True)is a pre-norm block; LLM codebases write their own in about 50 lines, like the one above.- Llama-style blocks: RMSNorm, RoPE inside attention, GQA, SwiGLU MLP, no biases.
- Activation memory per block is several tensors plus attention weights unless FlashAttention is used.
Go further: Building a Transformer Block writes this block in NumPy and in PyTorch, then the next lesson trains a tiny character transformer.
Exercises
Exercise 1: Parameters per block
How many parameters does one block with have (attention plus MLP, no biases)?
Answer
About 12.6M.
Solution
.
Exercise 2: Where do positions interact?
Which sublayer would you change to stop position 3 from using information from position 1?
Answer
The attention (its mask).
Solution
The MLP and the norms act on each position separately; only attention mixes positions, so masking cuts the information path (in every layer).
Exercise 3: SwiGLU size (code)
A SwiGLU MLP has and . Find that matches the of a GELU MLP for , rounded to a multiple of 256.
Answer
exactly, about or rounded (Llama uses 11,008).
Solution
gives .
d = 4096
f = 8 * d / 3
print(round(f), 256 * int(f // 256), 256 * (int(f // 256) + 1))10923 10752 11008
Test yourself
Which sublayer of a transformer block mixes information across positions?
- The MLP
- Self-attention
- LayerNorm
- The residual addition
Roughly how many parameters does one transformer block of width have?
In a pre-norm block, the normalization is applied…
- after adding the residual
- to the input of each sublayer, leaving the residual path untouched
- only at the end of the model
- to the gradients