Building a Transformer Block
Attention lets every token read from every other token, but on its own it is a weak layer: it only takes weighted averages of value vectors, it has no idea where a token sits in the sequence, and a stack of bare attention layers is hard to train. A transformer block wraps attention with the three things it lacks: a per-token MLP that does the actual nonlinear computation, residual connections and layer normalisation so that dozens of blocks can be stacked, and positional information added to the input. Every large language model, ViT and speech transformer is a stack of this one block.
This lesson builds the block in NumPy, counts its parameters, and then shows that nn.TransformerEncoderLayer computes exactly the same function once our weights are copied into it. The math background is in The Transformer Block and Positional Encodings.
The pre-norm block
A block maps a sequence of shape to the same shape, in two sub-layers:
- Attention mixes across positions; the MLP mixes across features. The MLP is applied to every position independently with the same weights. Its hidden width is usually , and with GELU it holds most of the block's parameters.
- Residuals make each sub-layer learn a correction to rather than a whole new representation, and give gradients an identity path through the whole stack (Residual Connections).
- Pre-norm vs post-norm. The original 2017 transformer normalised after the addition, . Almost every model since normalises the input of each sub-layer and leaves the residual stream untouched, because that version trains stably without a careful learning-rate warm-up. The price is that the stream is never normalised, so a pre-norm stack ends with one extra LayerNorm before the output head. LayerNorm and RMSNorm covers the normalisation itself; many recent models swap LayerNorm for RMSNorm and GELU for a gated variant (SwiGLU) without changing the structure.
Parameter count. With biases everywhere, as in PyTorch:
| Part | Weights | Biases and scales |
|---|---|---|
| attention: | ||
| MLP: and | ||
| two LayerNorms (, ) | ||
| block |
So a block has parameters, independent of the number of heads and of the sequence length. For (GPT-2 small, BERT-base) that is about 7.1 million per block; the compute per token is about twice that many multiply-adds plus the attention scores, which grow with (Parameter and FLOP Counting).
Positions
Attention treats its input as a set: permute the tokens and the outputs are permuted the same way, nothing else changes. Word order has to be injected, and the simplest way is to add a position vector to the token embedding before the first block. Two classic choices:
- Sinusoidal (fixed, no parameters). Pair up the dimensions; pair is a sine and a cosine of the position at frequency :
Fast pairs change every position, slow pairs over thousands of positions, like the hands of a clock. Because , the dot product depends only on the distance .
- Learned (an
nn.Embedding(max_len, E)table, or annn.Parameterof shape(max_len, E), trained with the rest). Simple and works well, used by BERT, GPT-2 and ViT; but it has no row for positions beyondmax_lenseen in training.
Modern LLMs mostly use rotary embeddings (RoPE), which rotate the query and key vectors by a position-dependent angle inside every attention layer instead of adding anything to the input; the same "depends only on the distance" property then holds for the attention scores themselves. The example checks the properties above and that positions break the permutation symmetry.
import numpy as np
def sinusoidal(T, E):
pos = np.arange(T)[:, None] # (T, 1)
i = np.arange(0, E, 2)[None, :] # even dimensions 0, 2, 4, ...
angle = pos / 10000 ** (i / E) # (T, E/2)
pe = np.zeros((T, E))
pe[:, 0::2] = np.sin(angle)
pe[:, 1::2] = np.cos(angle)
return pe
pe = sinusoidal(64, 16)
print("PE[1, :6]:", np.round(pe[1, :6], 3).tolist())
print("every row has norm sqrt(E/2):", np.allclose(np.linalg.norm(pe, axis=1), np.sqrt(8)))
# similarity depends on the distance only, not on the position itself
print("PE[5].PE[8] =", round(float(pe[5] @ pe[8]), 4), " PE[40].PE[43] =", round(float(pe[40] @ pe[43]), 4))
print("dot with position 10, distances 0..5:", [round(float(pe[10] @ pe[10 + k]), 2) for k in range(6)])
# Without positions, self-attention is permutation equivariant.
def softmax(z):
e = np.exp(z - z.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def self_attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
return softmax(q @ k.T / np.sqrt(q.shape[1])) @ v
rng = np.random.default_rng(0)
T, E = 6, 16
x = rng.normal(size=(T, E))
Wq, Wk, Wv = (rng.normal(0, E ** -0.5, (E, E)) for _ in range(3))
perm = np.array([3, 0, 5, 1, 4, 2])
out = self_attention(x, Wq, Wk, Wv)
print("no positions: f(x[perm]) == f(x)[perm]:", np.allclose(self_attention(x[perm], Wq, Wk, Wv), out[perm]))
xp = x + pe[:T]
outp = self_attention(xp, Wq, Wk, Wv)
print("with positions:", np.allclose(self_attention(x[perm] + pe[:T], Wq, Wk, Wv), outp[perm]))PE[1, :6]: [0.841, 0.54, 0.311, 0.95, 0.1, 0.995]
every row has norm sqrt(E/2): True
PE[5].PE[8] = 5.5431 PE[40].PE[43] = 5.5431
dot with position 10, distances 0..5: [8.0, 7.49, 6.37, 5.54, 5.56, 6.14]
no positions: f(x[perm]) == f(x)[perm]: True
with positions: False
Each row has norm because every sine-cosine pair contributes . The dot product of positions 5 and 8 equals that of 40 and 43 (5.5431): only the distance 3 matters. It falls from 8 at distance 0 but not monotonically (5.54 at distance 3, 5.56 at distance 4), so it is a rough similarity, not a clean distance measure. Without positions, permuting the input permutes the output exactly; with them added, it doesn't.
The block in NumPy
The block below follows the equations line by line: layer norm with the biased variance and (as PyTorch), multi-head attention with biases on all four projections, and the exact GELU written with scipy.special.erf. The optional memory argument turns self-attention into cross-attention: queries from x, keys and values from another sequence. That is all a decoder needs beyond the encoder block.
import numpy as np
from scipy.special import erf
def softmax(z):
e = np.exp(z - z.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def layer_norm(x, g, b, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True) # biased variance, as PyTorch
return g * (x - mu) / np.sqrt(var + eps) + b
def gelu(x): # exact GELU: x * Phi(x)
return 0.5 * x * (1 + erf(x / np.sqrt(2)))
def mha(x, p, h, mask=None, memory=None):
B, T, E = x.shape
src = x if memory is None else memory # cross-attention: keys/values from memory
split = lambda z: z.reshape(B, -1, h, E // h).transpose(0, 2, 1, 3)
q, k, v = split(x @ p["Wq"] + p["bq"]), split(src @ p["Wk"] + p["bk"]), split(src @ p["Wv"] + p["bv"])
s = q @ k.transpose(0, 1, 3, 2) / np.sqrt(E // h)
if mask is not None:
s = np.where(mask, s, -np.inf)
o = (softmax(s) @ v).transpose(0, 2, 1, 3).reshape(B, T, E)
return o @ p["Wo"] + p["bo"]
def block(x, p, h, mask=None):
x = x + mha(layer_norm(x, p["g1"], p["b1"]), p, h, mask) # attention sub-layer
return x + gelu(layer_norm(x, p["g2"], p["b2"]) @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"] # MLP sub-layer
def init_block(E, rng, hidden=None):
hidden = hidden or 4 * E
n = lambda *s: rng.normal(0, 0.1, s)
return {"Wq": n(E, E), "Wk": n(E, E), "Wv": n(E, E), "Wo": n(E, E),
"bq": n(E), "bk": n(E), "bv": n(E), "bo": n(E),
"g1": 1 + n(E), "b1": n(E), "g2": 1 + n(E), "b2": n(E),
"W1": n(E, hidden), "c1": n(hidden), "W2": n(hidden, E), "c2": n(E)}
rng = np.random.default_rng(0)
B, T, E, h = 2, 5, 16, 4
p = init_block(E, rng)
x = rng.normal(size=(B, T, E))
y = block(x, p, h)
print("in", x.shape, "-> out", y.shape)
print("y[0, 0, :5]:", np.round(y[0, 0, :5], 4).tolist())
n_params = sum(v.size for v in p.values())
print("parameters:", n_params, " 12E^2 + 13E =", 12 * E * E + 13 * E)
# A causal block: changing the last token cannot change earlier outputs.
causal = np.tril(np.ones((T, T), dtype=bool))
x2 = x.copy(); x2[:, -1] += 5.0
ya, yb = block(x, p, h, causal), block(x2, p, h, causal)
print("causal: first 4 positions unchanged:", np.allclose(ya[:, :4], yb[:, :4]), " last changed:", not np.allclose(ya[:, 4], yb[:, 4]))
# Cross-attention: 3 decoder positions attend to 7 encoder positions.
memory = rng.normal(size=(B, 7, E))
z = rng.normal(size=(B, 3, E))
print("cross-attention output:", mha(z, p, h, memory=memory).shape)in (2, 5, 16) -> out (2, 5, 16)
y[0, 0, :5]: [-2.5923, 0.2019, 1.3822, 0.4116, 0.5268]
parameters: 3280 12E^2 + 13E = 3280
causal: first 4 positions unchanged: True last changed: True
cross-attention output: (2, 3, 16)
The parameter count agrees with the formula: . With a causal mask, perturbing the last token changes only the last output: no information flows backwards in time, which is the property a language model's training relies on. The cross-attention call returns one vector per decoder position (3), each a mixture of the 7 encoder positions.
The same block in PyTorch
nn.TransformerEncoderLayer is this block, but its defaults are not the ones above: it is post-norm unless norm_first=True, uses ReLU unless activation="gelu", has dropout 0.1 (on the attention weights, inside the MLP and on both residual branches), a hidden width of 2048 whatever is, and expects (T, B, E) unless batch_first=True. The recorded example (CPU, float64) sets all five, copies the NumPy weights in (nn.Linear stores weights as (out, in), so every matrix is transposed; the attention's in_proj_weight stacks , , by rows) and compares, with and without a causal mask.
import numpy as np
from scipy.special import erf
import torch
from torch import nn
def softmax(z):
e = np.exp(z - z.max(axis=-1, keepdims=True))
return e / e.sum(axis=-1, keepdims=True)
def layer_norm(x, g, b, eps=1e-5):
mu = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True) # biased variance, as PyTorch
return g * (x - mu) / np.sqrt(var + eps) + b
def gelu(x): # exact GELU: x * Phi(x)
return 0.5 * x * (1 + erf(x / np.sqrt(2)))
def mha(x, p, h, mask=None, memory=None):
B, T, E = x.shape
src = x if memory is None else memory # cross-attention: keys/values from memory
split = lambda z: z.reshape(B, -1, h, E // h).transpose(0, 2, 1, 3)
q, k, v = split(x @ p["Wq"] + p["bq"]), split(src @ p["Wk"] + p["bk"]), split(src @ p["Wv"] + p["bv"])
s = q @ k.transpose(0, 1, 3, 2) / np.sqrt(E // h)
if mask is not None:
s = np.where(mask, s, -np.inf)
o = (softmax(s) @ v).transpose(0, 2, 1, 3).reshape(B, T, E)
return o @ p["Wo"] + p["bo"]
def block(x, p, h, mask=None):
x = x + mha(layer_norm(x, p["g1"], p["b1"]), p, h, mask) # attention sub-layer
return x + gelu(layer_norm(x, p["g2"], p["b2"]) @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"] # MLP sub-layer
def init_block(E, rng, hidden=None):
hidden = hidden or 4 * E
n = lambda *s: rng.normal(0, 0.1, s)
return {"Wq": n(E, E), "Wk": n(E, E), "Wv": n(E, E), "Wo": n(E, E),
"bq": n(E), "bk": n(E), "bv": n(E), "bo": n(E),
"g1": 1 + n(E), "b1": n(E), "g2": 1 + n(E), "b2": n(E),
"W1": n(E, hidden), "c1": n(hidden), "W2": n(hidden, E), "c2": n(E)}
rng = np.random.default_rng(0)
B, T, E, h = 2, 5, 16, 4
p = init_block(E, rng)
x = rng.normal(size=(B, T, E))
layer = nn.TransformerEncoderLayer(d_model=E, nhead=h, dim_feedforward=4 * E, dropout=0.0,
activation="gelu", batch_first=True, norm_first=True, dtype=torch.float64)
t = lambda a: torch.tensor(a, dtype=torch.float64)
with torch.no_grad(): # nn.Linear stores W with shape (out, in): transpose
layer.self_attn.in_proj_weight.copy_(t(np.concatenate([p["Wq"].T, p["Wk"].T, p["Wv"].T])))
layer.self_attn.in_proj_bias.copy_(t(np.concatenate([p["bq"], p["bk"], p["bv"]])))
layer.self_attn.out_proj.weight.copy_(t(p["Wo"].T)); layer.self_attn.out_proj.bias.copy_(t(p["bo"]))
layer.linear1.weight.copy_(t(p["W1"].T)); layer.linear1.bias.copy_(t(p["c1"]))
layer.linear2.weight.copy_(t(p["W2"].T)); layer.linear2.bias.copy_(t(p["c2"]))
layer.norm1.weight.copy_(t(p["g1"])); layer.norm1.bias.copy_(t(p["b1"]))
layer.norm2.weight.copy_(t(p["g2"])); layer.norm2.bias.copy_(t(p["b2"]))
layer.eval()
with torch.no_grad():
y_t = layer(t(x)).numpy()
mask = nn.Transformer.generate_square_subsequent_mask(T, dtype=torch.float64)
y_tc = layer(t(x), src_mask=mask, is_causal=True).numpy()
causal = np.tril(np.ones((T, T), dtype=bool))
print("encoder layer matches NumPy block:", np.allclose(y_t, block(x, p, h), atol=1e-10))
print("with causal mask:", np.allclose(y_tc, block(x, p, h, causal), atol=1e-10))
print("causal mask row 2:", mask[1].tolist())
print("parameters:", sum(q.numel() for q in layer.parameters()), "(NumPy:", sum(v.size for v in p.values()), ")")
default = nn.TransformerEncoderLayer(d_model=E, nhead=h, batch_first=True)
print("defaults: activation =", default.activation.__name__, " dropout =", default.dropout.p,
" dim_feedforward =", default.linear1.out_features, " norm_first =", default.norm_first)
E = 512
enc = nn.TransformerEncoderLayer(E, 8, dim_feedforward=4 * E, batch_first=True)
dec = nn.TransformerDecoderLayer(E, 8, dim_feedforward=4 * E, batch_first=True)
count = lambda m: sum(q.numel() for q in m.parameters())
print(f"E = 512 encoder layer: {count(enc):,} (12E^2 + 13E = {12 * E * E + 13 * E:,})")
print(f"E = 512 decoder layer: {count(dec):,} (16E^2 + 19E = {16 * E * E + 19 * E:,})")
torch.manual_seed(0)
memory = torch.randn(2, 7, E)
tgt = torch.randn(2, 3, E)
print("decoder output:", tuple(dec(tgt, memory).shape))encoder layer matches NumPy block: True
with causal mask: True
causal mask row 2: [0.0, 0.0, -inf, -inf, -inf]
parameters: 3280 (NumPy: 3280 )
defaults: activation = relu dropout = 0.1 dim_feedforward = 2048 norm_first = False
E = 512 encoder layer: 3,152,384 (12E^2 + 13E = 3,152,384)
E = 512 decoder layer: 4,204,032 (16E^2 + 19E = 4,204,032)
decoder output: (2, 3, 512)
The layer and the NumPy block agree to , with and without the mask, and both have 3280 parameters. generate_square_subsequent_mask builds the float version of the causal mask (0 where allowed, above the diagonal); passing is_causal=True as well is a hint that lets PyTorch use a faster kernel. The last lines confirm the formulas at the classic size : 3,152,384 parameters per encoder layer, and 4,204,032 per decoder layer, which adds a cross-attention sub-layer () and a third LayerNorm (), giving .
Encoder, decoder, decoder-only
| Stack | Blocks contain | Mask | Used for |
|---|---|---|---|
| Encoder | self-attention + MLP | padding only: every token sees the whole input | understanding a whole input: BERT, ViT, sentence embeddings |
| Decoder (encoder-decoder) | causal self-attention + cross-attention to the encoder output + MLP | causal (and padding) | sequence to sequence: the original translation model, T5, Whisper |
| Decoder-only | causal self-attention + MLP (an encoder block with a causal mask) | causal | language models: GPT, Llama; the next lesson trains one |
In cross-attention the decoder's states provide the queries and the encoder's output (called the memory) provides keys and values, so the weight matrix has shape . A decoder-only model is built with nn.TransformerEncoderLayer plus a causal mask, not with nn.TransformerDecoderLayer, which always expects a memory. Tokenizers, pretraining objectives and large-model fine-tuning belong to NLP, Transformers & LLM Fine-Tuning.
Pitfalls
- Library defaults are not the modern recipe. Post-norm, ReLU, dropout 0.1 and
dim_feedforward=2048are PyTorch's defaults for backwards compatibility. A model compared with a paper, or with your own NumPy code, must set them explicitly, as above. - Dropout makes outputs random in training mode. With the default dropout, two forward passes in
model.train()give different results; comparisons and inference needmodel.eval()(ordropout=0.0). - No final LayerNorm after a pre-norm stack.
nn.TransformerEncoder(layer, num_layers, norm=nn.LayerNorm(E))adds it; forgetting it leaves the head reading an unnormalised residual stream whose scale grows with depth. - Positions added twice, or not at all. Add them once, to the input embeddings (for RoPE: inside attention, never to the input). A model without them runs fine and simply cannot tell "dog bites man" from "man bites dog".
- Learned positions beyond
max_len. Indexing the table at positionmax_lenraises an index error; feeding longer sequences needs a bigger table (and training on such lengths). - The hidden width is not by default in
nn.TransformerEncoderLayer: passdim_feedforward=4 * Eif you want the standard ratio, otherwise a small model gets a huge MLP.
Practice
- How many parameters does a 12-block encoder with have, without embeddings? And how many does one extra cross-attention sub-layer add per block?
Answer
Per block ; times 12 is , about 85 million (BERT-base has about 110 million with its embeddings). A cross-attention sub-layer adds plus a LayerNorm of .
- In the NumPy block, replace pre-norm by post-norm. Write the two lines of
block.
Answer
x = layer_norm(x + mha(x, p, h, mask), p["g1"], p["b1"])
return layer_norm(x + gelu(x @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"], p["g2"], p["b2"])With norm_first=False in PyTorch this matches nn.TransformerEncoderLayer too.
- The sinusoidal dot product was 8.0 for . Why exactly 8, and what would it be for ?
Answer
At distance 0 every pair contributes , and there are pairs: 8 for , 32 for .
- You train a learned-position model on sequences of length 128 and want to run it on length 200. What breaks, and what are your options?
Answer
The position table has 128 rows, so positions 128 to 199 have no vector (an index error, or garbage if you pad the table with untrained rows). Options: truncate or slide a window of 128; extend the table (for example by interpolating the learned vectors) and fine-tune on longer sequences; or use a scheme that extrapolates better, such as RoPE or ALiBi, from the start.
Test yourself
In a pre-norm block, what is the first sub-layer's output?
How many parameters does a transformer block with , a MLP and biases everywhere have?
- 3280
- 4096
- It depends on the number of heads
Which setting is NOT a default of nn.TransformerEncoderLayer?
dropout=0.1activationReLUnorm_first=Truedim_feedforward=2048
What does cross-attention take from the encoder?
- The queries
- The keys and the values
- Only the values
- The causal mask
Why does a transformer need positional information?
- Without it the softmax overflows
- Self-attention is permutation equivariant: reordering the tokens just reorders the outputs
- To reduce the number of parameters
- Because LayerNorm removes the order