Sub topic 7
The transformer block: attention, feed-forward layers, and residuals
This chapter assumes you can read basic Python and NumPy. It also assumes you know matrix multiplication and the idea of a neural network layer with weights. You should already know single-head causal self-attention from the previous chapters, and that positional information is added to the token embeddings before the first block.
What a block is for
A transformer block is the unit that a decoder-only model repeats. A small model might stack 12 blocks, and a large one might stack 80 or more. Every block takes a matrix of shape (sequence_length, d_model) and returns a matrix of the same shape. This matching shape is what lets blocks be stacked.
Each block does two jobs:
- Attention moves information between positions. Position 5 can read from positions 1 to 5.
- The feed-forward network (FFN) transforms each position's vector on its own. It does not look at other positions.
Two supporting mechanisms keep deep stacks trainable: residual connections and layer normalization.
Multi-head attention
Single-head attention produces one weighting pattern per position. Multi-head attention runs several smaller attention computations in parallel, so different heads can specialize in different relationships.
With d_model = 16 and 4 heads, each head works in d_head = 16 / 4 = 4 dimensions. The steps are:
- Project the input into queries, keys, and values with
Wq,Wk,Wv, each of shape(d_model, d_model). - Reshape each result into 4 heads of width 4.
- Run causal scaled dot-product attention independently in each head. The scaling uses
sqrt(d_head), notsqrt(d_model). - Concatenate the head outputs back to width
d_model. - Multiply by an output projection
Wo, also(d_model, d_model).
The output projection matters. Without it, each head's result would occupy its own fixed slice of the vector and heads could not mix. Wo lets later layers combine what the heads found.
Splitting into heads does not add parameters or much compute compared with one wide head. The total is still 4 * d_model^2 weights for attention, ignoring biases.
The feed-forward network
The FFN is a two-layer perceptron applied to each position separately:
FFN(h) = GELU(h @ W1 + b1) @ W2 + b2W1 has shape (d_model, d_ff) and W2 has shape (d_ff, d_model). The hidden width d_ff is conventionally 4 * d_model. GELU is a smooth activation similar to ReLU. Some newer models use gated variants such as SwiGLU, which adds a third weight matrix and usually shrinks d_ff to compensate.
The FFN holds most of a block's parameters:
| Component | Weights (no biases) | Share of block |
|---|---|---|
| Attention (`Wq`, `Wk`, `Wv`, `Wo`) | `4 * d_model^2` | about one third |
| FFN with `d_ff = 4 * d_model` | `8 * d_model^2` | about two thirds |
Attention decides where information comes from. The FFN then processes the gathered information with a large nonlinear function. Because the same FFN weights are used at every position, the FFN cannot mix positions. Only attention can.
Residual connections and the residual stream
Each sublayer is wrapped like this:
x = x + sublayer(x)The input is added back to the sublayer's output. This has two effects.
- Gradients flow through the addition unchanged. During backpropagation, the gradient reaches earlier layers directly along the skip path. This is why stacks of dozens of blocks train at all.
- Each sublayer writes a correction, not a replacement. The vector at each position acts as a shared workspace, often called the residual stream. The embedding starts it. Every attention and FFN sublayer reads from it and adds something to it. The final stream is passed to the output layer.
If a sublayer's output is near zero, the block passes its input through almost untouched. A new block therefore starts as a small change to an existing model, not a disruption.
Layer normalization and where it goes
Layer norm rescales each position's vector to zero mean and unit variance across the feature dimension, then applies a learned gain and bias. It works per position, so it does not depend on batch size or on other tokens. This matters for generation, where the sequence length changes at every step.
There are two common placements:
- Post-norm (original 2017 transformer):
x = norm(x + sublayer(x)). - Pre-norm (most modern LLMs):
x = x + sublayer(norm(x)).
Pre-norm keeps the residual path free of any normalization. That makes deep models much easier to train without careful learning-rate warmup. The cost is that the stream's magnitude can grow with depth, so pre-norm models apply one more norm before the output layer. Many recent models also replace layer norm with RMSNorm, which skips mean subtraction and the bias.
A complete block in NumPy
The code below builds a pre-norm block with 4 heads. It then checks the causal property: changing the last token must not change the outputs at earlier positions.
import numpy as np
def layer_norm(x, gain, bias, eps=1e-5):
mean = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True)
return gain * (x - mean) / np.sqrt(var + eps) + bias
def gelu(x):
return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
def multi_head_causal_attention(x, Wq, Wk, Wv, Wo, n_heads):
T, d = x.shape
dh = d // n_heads
def split(m): # (T, d) -> (heads, T, dh)
return m.reshape(T, n_heads, dh).transpose(1, 0, 2)
q, k, v = split(x @ Wq), split(x @ Wk), split(x @ Wv)
scores = q @ k.transpose(0, 2, 1) / np.sqrt(dh) # (heads, T, T)
mask = np.triu(np.ones((T, T), dtype=bool), k=1)
scores = np.where(mask, -np.inf, scores)
scores = scores - scores.max(axis=-1, keepdims=True)
weights = np.exp(scores)
weights = weights / weights.sum(axis=-1, keepdims=True)
heads = weights @ v # (heads, T, dh)
concat = heads.transpose(1, 0, 2).reshape(T, d) # (T, d)
return concat @ Wo
def transformer_block(x, p, n_heads):
h = layer_norm(x, p["g1"], p["b1"])
x = x + multi_head_causal_attention(
h, p["Wq"], p["Wk"], p["Wv"], p["Wo"], n_heads)
h = layer_norm(x, p["g2"], p["b2"])
x = x + gelu(h @ p["W1"] + p["c1"]) @ p["W2"] + p["c2"]
return x
rng = np.random.default_rng(0)
d, d_ff, n_heads, T = 16, 64, 4, 5
p = {
"Wq": rng.normal(size=(d, d)) * 0.2,
"Wk": rng.normal(size=(d, d)) * 0.2,
"Wv": rng.normal(size=(d, d)) * 0.2,
"Wo": rng.normal(size=(d, d)) * 0.2,
"W1": rng.normal(size=(d, d_ff)) * 0.2,
"W2": rng.normal(size=(d_ff, d)) * 0.2,
"c1": np.zeros(d_ff), "c2": np.zeros(d),
"g1": np.ones(d), "b1": np.zeros(d),
"g2": np.ones(d), "b2": np.zeros(d),
}
x = rng.normal(size=(T, d))
y = transformer_block(x, p, n_heads)
print(y.shape)
x2 = x.copy()
x2[-1] = rng.normal(size=d) # change only the last token
y2 = transformer_block(x2, p, n_heads)
print(np.allclose(y[:-1], y2[:-1])) # earlier positions unchanged
print(np.allclose(y[-1], y2[-1])) # last position changedThe output is (5, 16), then True, then False. The shape is unchanged, so this block could feed straight into another copy of itself.
The causality test works because of two facts. Attention masks future positions. Every other operation (layer norm, FFN, residual add) acts on each position independently. Any block that satisfies both is causal.
Stacking blocks
A full model applies the same block structure N times, each with its own weights:
x = embeddings + positional information
for block in blocks:
x = block(x)
x = final_norm(x)
logits = x @ output_matrixEarly blocks tend to capture local and syntactic patterns, and later ones capture more abstract relations. This is a tendency found by probing studies, not a designed split. The next chapter covers the full pipeline from token IDs to probabilities.
Common errors
- Scaling by
sqrt(d_model)instead ofsqrt(d_head). The scores become too small, and the attention weights flatten toward uniform. - Forgetting the output projection
Wo. The model still runs, but heads cannot mix. - Reshaping heads incorrectly. Reshape to
(T, heads, dh)and then transpose. Reshaping straight to(heads, T, dh)scrambles tokens and features together, and it raises no error. - Applying the mask after softmax. Set masked scores to
-infbefore softmax. Zeroing the weights afterward leaves rows that no longer sum to 1. - Using the FFN across positions. If your FFN code reduces or concatenates over the sequence axis, you have leaked information between positions and broken causality.
- Putting normalization on the residual path in a pre-norm design. The norm belongs on the sublayer's input only.
Exercises
Exercise
A model has dmodel = 512, 8 attention heads, and dff = 2048. Ignoring biases and norm parameters, how many weights are in the attention sublayer and in the FFN of one block? What is the d_head value?
Show answer
d_head = 512 / 8 = 64. Attention has 4 512^2 = 1,048,576 weights (Wq, Wk, Wv, Wo). The FFN has 2 512 * 2048 = 2,097,152 weights (W1 and W2). The FFN has twice as many weights as attention.
Exercise
In the code above, you replace x = x + sublayer(norm(x)) with x = norm(x + sublayer(x)) for both sublayers. Is the output shape affected? Is the causal property affected? What changes in training?
Show answer
Neither the shape nor the causal property changes, because norm acts on each position independently and the shapes match. The change is to post-norm, which puts normalization on the residual path. Gradients no longer travel along an unnormalized skip path, so deep stacks become harder to train and usually need learning-rate warmup.