Sub topic 7
The Transformer Block: Attention, Feed-Forward Layers, and Residuals
This chapter assumes you can read basic Python and NumPy, multiply matrices, and understand that a neural network is a stack of layers with learned weights. You should also know how causal self-attention works from the previous chapter.
What a block does
A transformer block is one repeatable unit. A decoder-only model stacks many of them, and each one takes a matrix of shape (seq_len, d_model) and returns a matrix of the same shape. Because the shape does not change, blocks can be stacked to any depth.
A block has two sublayers:
- Self-attention mixes information across positions. Each token reads from earlier tokens.
- A feed-forward network (FFN) transforms each position on its own. It does not look at other positions.
Two supporting pieces wrap these sublayers: residual connections and layer normalization.
Residual connections
A residual connection adds a sublayer's input to its output: x = x + sublayer(x). The sublayer only has to learn a change to make, not the whole representation. During training, gradients also flow straight through the addition, which keeps deep stacks trainable.
Layer normalization
Layer normalization rescales each position's vector to zero mean and unit variance, then applies a learned scale and shift. It keeps activations in a stable range. Most current models use the pre-norm layout shown in the diagram, where normalization comes before each sublayer. The original transformer paper used post-norm, which is harder to train at depth.
The feed-forward network
The FFN is two linear layers with a nonlinearity between them. The hidden layer is usually about four times wider than d_model. Attention moves information between tokens, and the FFN processes what each token has gathered. Much of a model's parameter count sits in these layers.
A runnable block
This code builds one block. It reuses the attention function from the previous chapter, and it is written with a single head for clarity.
import numpy as np
def layer_norm(x, eps=1e-5):
mean = x.mean(axis=-1, keepdims=True)
var = x.var(axis=-1, keepdims=True)
return (x - mean) / np.sqrt(var + eps)
def causal_self_attention(x, Wq, Wk, Wv):
q, k, v = x @ Wq, x @ Wk, x @ Wv
scores = q @ k.T / np.sqrt(k.shape[-1])
mask = np.triu(np.ones_like(scores), k=1).astype(bool)
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)
return weights @ v
def gelu(x):
return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x**3)))
def feed_forward(x, W1, b1, W2, b2):
return gelu(x @ W1 + b1) @ W2 + b2
def transformer_block(x, p):
x = x + causal_self_attention(layer_norm(x), p["Wq"], p["Wk"], p["Wv"])
x = x + feed_forward(layer_norm(x), p["W1"], p["b1"], p["W2"], p["b2"])
return x
rng = np.random.default_rng(0)
d_model, d_ff, seq_len = 8, 32, 4
p = {
"Wq": rng.normal(size=(d_model, d_model)) * 0.1,
"Wk": rng.normal(size=(d_model, d_model)) * 0.1,
"Wv": rng.normal(size=(d_model, d_model)) * 0.1,
"W1": rng.normal(size=(d_model, d_ff)) * 0.1,
"b1": np.zeros(d_ff),
"W2": rng.normal(size=(d_ff, d_model)) * 0.1,
"b2": np.zeros(d_model),
}
x = rng.normal(size=(seq_len, d_model))
y = transformer_block(x, p)
print(x.shape, y.shape)The output shape matches the input shape, (4, 8). Two lines in transformer_block do the work, and each has the form x = x + f(norm(x)).
Common errors
- Forgetting the residual add. Without
x +, the block replaces its input instead of refining it. Deep stacks then train poorly. - Normalizing over the wrong axis. Normalize across the feature axis (
axis=-1), not across positions. Otherwise tokens leak information to each other, which breaks causality. - Applying attention to the FFN. The FFN must act on each position independently. If you mix positions there, the causal mask no longer guarantees that a token cannot see the future.
- Mismatched shapes. The attention output and FFN output must both be
(seq_len, d_model), or the residual add fails.
Exercise
In the block above, which sublayer lets position 3 use information from position 1, and which one cannot? Why is the residual connection still useful for the sublayer that cannot?
Show answer
Self-attention can move information from position 1 to position 3, because the causal mask allows each position to see earlier ones. The feed-forward network cannot, since it processes each position separately. The residual connection still helps the FFN because it adds the FFN's output to the existing vector instead of replacing it. That keeps the token's own information and gives gradients a direct path during training.