Lesson 4.2: The feed-forward network and activations
Add the second half of the transformer block: a two-layer network applied to each token. See why it needs a nonlinearity, what GELU is, and how big it is.
By the end of this lesson you will be able to say what the feed-forward layer of a transformer does that attention does not, write it with its gradient, explain why it needs a nonlinear activation, compare ReLU and GELU, and count its parameters and arithmetic against those of attention. You will show that two linear layers in a row equal one (True) and that a nonlinearity between them breaks that (False), that a linear model cannot learn XOR (loss 0.6931, accuracy 50%) while a network with one GELU unit can (loss 0.0506, accuracy 100%) and four units do it almost perfectly (loss 0.0003), and that for a width of 32 the feed-forward layer holds 8,352 of the 12,576 parameters of a block's attention and feed-forward parts, which is 66.4%. You need Python and NumPy. The code of this lesson does not depend on earlier files.
Lesson 4.1 gave us the stream and the norm. A transformer block has two sublayers that read the stream and add to it. We know the first: attention. This lesson builds the second, which is much simpler and, in a typical model, holds about two thirds of the block's parameters.
What attention cannot do
Look at what an attention layer computes. For each position, it takes a weighted average of value vectors, and passes the average through a matrix. The weights depend on the content, but the combination is linear: the output is a sum of the inputs, each scaled by a number. Attention is good at moving information from other positions to this one. It is not good at computing with it.
Computing means combining the pieces of information in ways that are not just sums. Suppose a token has gathered two facts, "the subject is plural" and "the verb is past tense". A sum of the two vectors holds both, side by side. To decide, say, the next word, the model must respond to both together, which a linear readout cannot do for every combination. This is the XOR problem in disguise, and we will test it directly in a moment.
The feed-forward layer, also called the MLP (multi-layer perceptron), does the computing. It takes the vector of one token, passes it through a small two-layer network and returns a vector of the same size. It acts on each position separately, with the same weights at every position. It does not look at other tokens. Attention is the layer where tokens talk to each other. The feed-forward layer is where each token thinks about what it has heard.
The layer
For a token vector x of size d, the feed-forward layer is
FFN(x) = W2 × activation(W1 × x + c1) + c2
where W1 is d by 4d, W2 is 4d by d, and activation acts on each number separately. The first matrix expands the vector to four times the width. The activation introduces the nonlinearity. The second matrix compresses it back. Four is a convention from the original transformer paper, and is used by most models. Models with a different activation sometimes change it.
In the block, it sits on the residual stream just like attention: x = x + FFN(LayerNorm(x)).
Counting parameters: W1 has d × 4d numbers and W2 has 4d × d, so 8 d² together, plus the biases c1 (4d numbers) and c2 (d numbers), so 8 d² + 5 d in all. Attention has four d by d matrices and four bias vectors: 4 d² + 4 d. The feed-forward layer is twice as big as attention.
Why the nonlinearity is essential
Suppose we left out the activation. Then FFN(x) = W2 (W1 x + c1) + c2, which equals (W2 W1) x + (W2 c1 + c2): a single linear layer with a different matrix. The two layers collapse into one, and the expansion to 4d accomplishes nothing. The code below confirms it and then breaks it.
python
import numpy as np
def gelu(x):
return 0.5 x (1 + np.tanh(np.sqrt(2 / np.pi) (x + 0.044715 x 3)))
def gelugrad(x):
c = np.sqrt(2 / np.pi)
t = np.tanh(c (x + 0.044715 x 3))
return 0.5 (1 + t) + 0.5 x (1 - t 2) c (1 + 3 0.044715 x 2)
xs = np.array([-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 3.0])
print("x ", xs)
print("relu ", np.maximum(xs, 0))
print("gelu ", np.round(gelu(xs), 4))
eps = 1e-6
print(np.allclose(gelugrad(xs), (gelu(xs + eps) - gelu(xs - eps)) / (2 eps))) # True
two linear layers in a row are just one linear layer
rng = np.random.defaultrng(0)
x = rng.standardnormal((5, 8)); W1 = rng.standardnormal((8, 32)); W2 = rng.standardnormal((32, 8))
print(np.allclose((x @ W1) @ W2, x @ (W1 @ W2))) # True
# with a nonlinearity in between they are not
print(np.allclose(gelu(x @ W1) @ W2, x @ (W1 @ W2))) # False
The last two lines print:
True
False
Two linear layers equal one. Put a GELU between them and the equality fails: the network now computes something a single matrix cannot.
The activation: ReLU and GELU
An activation function is the nonlinearity applied to each number. The first widely used one was the ReLU: zero for negative inputs, unchanged for positive. It is simple and fast, and it has a flaw: a unit whose input is always negative outputs zero and has a gradient of zero, so it never recovers (a "dead" unit). Transformers mostly use the GELU (Hendrycks and Gimpel, 2016), a smooth version that lets a little of a negative input through:
GELU(x) = x × Φ(x), where Φ is the probability that a standard normal number is below x.
The common approximation, used in the code, is 0.5 x (1 + tanh(√(2/π) (x + 0.044715 x³))). The first lines of the output compare them.
x [-3. -1. -0.5 0. 0.5 1. 3. ]
relu [0. 0. 0. 0. 0.5 1. 3. ]
gelu [-0.0036 -0.1588 -0.1543 0. 0.3457 0.8412 2.9964]
True
For large positive x, GELU is nearly the identity (2.9964 at 3). For large negative x it is nearly zero (−0.0036 at −3). In between it dips slightly below zero (−0.1588 at −1) and then rises. It is smooth everywhere, so the gradient never has a sharp corner, and it has a small gradient for negative inputs, so units do not die. The True is the check that our hand-written gradient of GELU matches a numerical one.
A newer family, the gated activations, such as SwiGLU (Shazeer, 2020), multiply two projections of the input together, and are used in many recent models. They add a third matrix to the layer and usually reduce the expansion factor to keep the size the same. We use plain GELU.
A task that needs it: XOR
XOR is the classic test. Two bits go in, and the answer is 1 if exactly one of them is 1. We encode each input as two one-hot pairs, so four numbers in all, and compare a linear model with networks that have a hidden layer of 1, 2, 4 and 16 GELU units. All use full-batch gradient descent and the same settings.
python
import numpy as np
The task: the two inputs are bits, the answer is their XOR. Each input is one-hot, so a vector of 4 numbers.
X = np.array([[1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0], [0, 1, 0, 1]], dtype=float) # (a, b) = (0,0), (0,1), (1,0), (1,1)
y = np.array([0, 1, 1, 0])
def softmax(z):
e = np.exp(z - z.max(axis=1, keepdims=True))
return e / e.sum(axis=1, keepdims=True)
def gelu(x):
return 0.5 x (1 + np.tanh(np.sqrt(2 / np.pi) (x + 0.044715 x 3)))
def gelugrad(x):
c = np.sqrt(2 / np.pi)
t = np.tanh(c (x + 0.044715 x 3))
return 0.5 (1 + t) + 0.5 x (1 - t 2) c (1 + 3 0.044715 x 2)
def train(hidden, steps=3000, lr=0.5, seed=0):
rng = np.random.defaultrng(seed)
if hidden == 0: # a linear model: scores straight from the inputs
W = rng.standardnormal((4, 2)) 0.5; b = np.zeros(2)
for in range(steps):
P = softmax(X @ W + b)
dz = P.copy(); dz[np.arange(4), y] -= 1; dz /= 4
W -= lr X.T @ dz; b -= lr dz.sum(0)
P = softmax(X @ W + b)
else: # one hidden layer with a GELU
W1 = rng.standardnormal((4, hidden)) 0.5; c1 = np.zeros(hidden)
W2 = rng.standardnormal((hidden, 2)) 0.5; c2 = np.zeros(2)
for in range(steps):
a = X @ W1 + c1; z = gelu(a)
P = softmax(z @ W2 + c2)
dz2 = P.copy(); dz2[np.arange(4), y] -= 1; dz2 /= 4
dz = dz2 @ W2.T gelugrad(a)
W2 -= lr z.T @ dz2; c2 -= lr dz2.sum(0)
W1 -= lr X.T @ dz; c1 -= lr dz.sum(0)
P = softmax(gelu(X @ W1 + c1) @ W2 + c2)
return -np.log(P[np.arange(4), y]).mean(), (P.argmax(1) == y).mean()
for hidden in (0, 1, 2, 4, 16):
loss, acc = train(hidden)
print("hidden units", hidden, " loss", round(loss, 4), " accuracy", acc)
The output:
hidden units 0 loss 0.6931 accuracy 0.5
hidden units 1 loss 0.0506 accuracy 1.0
hidden units 2 loss 0.0005 accuracy 1.0
hidden units 4 loss 0.0003 accuracy 1.0
hidden units 16 loss 0.0001 accuracy 1.0
The linear model's loss is 0.6931, which is the natural log of 2: it is no better than guessing 50:50. That is not a failure to train. No linear function of these inputs can separate XOR, because the answer for "both" must go the opposite way to the answers for "one", and a weighted sum cannot do that. A hidden layer of even one GELU unit can (loss 0.0506), because GELU is not monotonic: it dips below zero and rises again, so one unit can respond to "exactly one input on" and not to "none" or "both". More units make it faster and cleaner (0.0005 with 2, 0.0003 with 4).
The lesson for the transformer is general. After attention has gathered information into a vector, the readout of that vector is linear. If the next token depends on a combination of what was gathered, a linear readout cannot get it, and a nonlinear layer in between can.
How it learns
The backward pass of the layer is three short steps, and the XOR code above does exactly these. Suppose the gradient of the loss with respect to the layer's output arrives as dy.
1. Through the second matrix. The gradient of W2 is the hidden activations, transposed, times dy. The gradient passed back to the hidden layer is dy times the transpose of W2.
2. Through the activation. Multiply, number by number, by the slope of the activation at the point where the forward pass was. For GELU this is the gelugrad of the code, and it is what the True in the activation check verified. Where the slope is near zero (a very negative input), little gradient gets through.
3. Through the first matrix. The gradient of W1 is the input, transposed, times the gradient at the hidden layer. The gradient passed back to the input is the hidden gradient times the transpose of W1.
The biases take the sum of the gradients over all examples. In the transformer the input is a (batch, T, d) array, and the same steps run over the batch and window dimensions at once, with the weight gradients summed over all positions. This is why one set of weights can learn from every position of every sequence.
How wide should the hidden layer be?
The expansion factor of four is a convention, and it is worth knowing why it is a reasonable one. A wider hidden layer gives the layer more units to detect more patterns, and more parameters to pay for. The XOR experiment shows the tension at tiny scale: a single unit suffices, and extra units make training faster and more reliable (loss 0.0506 with one unit, 0.0003 with four), with diminishing returns after that (0.0001 with sixteen). Real models face the same trade at much larger scale. The factor of four was chosen by experiment in the original transformer and has held up well, although models with gated activations use a factor of about 8/3 so as to keep the parameter count the same. If you change the factor, remember that the feed-forward layer's share of the block changes with it: with a factor of 2 it is half the block, with 8 it is four fifths.
What it holds, and what it costs
Every block carries both layers, so the sizes matter.
Parameters. For width d with the standard factor of 4, the feed-forward layer has 8 d² + 5 d parameters and attention has 4 d² + 4 d. For d = 32 that is 8,352 against 4,224. As d grows, the feed-forward layer approaches two thirds of the two together: 66.4% at d = 32 and 66.7% at d = 768.
Arithmetic per token. The feed-forward layer does 2 × 4 × d² = 8 d² multiply-adds for each token, whatever the sequence length. Attention does 4 d² for the projections, plus 2 T d for the scores and weighted sum, which grows with the sequence. At d = 32 and T = 16 that is 8,192 for the feed-forward layer and 5,120 for attention. The attention part overtakes it when 2 T d exceeds 4 d², that is, when T exceeds 2 d.
What the layer might be doing
It is natural to ask what a layer with two thirds of the parameters is for. There is research on this, and it is not settled. One line of work (Geva and colleagues, 2021) argues that the feed-forward layers act like key-value memories: the first matrix detects patterns in the input, and the second adds a corresponding output. Others find facts about the world stored in them. Treat these as findings about trained models, and not as something our small model has shown. What our experiments have shown is the narrower point: the layer lets the model compute nonlinearly on what attention gathered, and it holds most of the block's parameters.
Key takeaways
Attention moves information between positions, and its combination is linear. The feed-forward layer computes on each position separately, with the same weights everywhere.
The layer is FFN(x) = W2 × activation(W1 × x + c1) + c2, expanding d to 4d and back. It has 8 d² + 5 d parameters, twice as many as attention (4 d² + 4 d).
Without an activation, the two layers collapse into one linear layer: True for the product of the matrices, and False once a GELU is put between them.
GELU is a smooth, slightly non-monotonic activation: GELU(−3) = −0.0036, GELU(−1) = −0.1588, GELU(1) = 0.8412, GELU(3) = 2.9964. ReLU is zero for negative inputs and can leave units dead. Gated variants such as SwiGLU are used in many recent models.
On XOR, a linear model has loss 0.6931 and accuracy 50%. One GELU unit gives loss 0.0506 and 100% accuracy, and four units give 0.0003.
At width 32, the feed-forward layer has 8,352 parameters and attention 4,224: 66.4% of the two. At width 768 it is 66.7%.
The feed-forward layer costs 8 d² multiply-adds per token, independent of sequence length. Attention costs 4 d² plus 2 T d, and overtakes it when T exceeds 2 d.
Common mistakes
Leaving out the activation. The layer collapses to one linear map and wastes its parameters.
Applying the feed-forward layer across tokens. It acts on each position alone. Mixing positions is attention's job.
Using ReLU with a large learning rate and expecting no dead units. A big step can push a unit negative for good.
Forgetting the biases when counting. They add 5 d to the feed-forward layer and 4 d to attention.
Changing the expansion factor without recounting. The layer's share of the parameters moves with it.
Taking the memory interpretation as proven. It is a hypothesis from studies of large models.
Using the approximate and the exact GELU interchangeably when comparing with another model. They differ slightly. Use the same one.
Check yourself
1. Why do two linear layers in a row add nothing?
Their product is another matrix, so x times W1 times W2 equals x times (W1 W2). The pair is equivalent to one linear layer.
2. How many parameters does a feed-forward layer have at width 64, with an expansion factor of 4 and biases?
8 × 64² + 5 × 64 = 32,768 + 320 = 33,088.
3. What does a linear model's loss of 0.6931 on a two-class task tell you?
It is ln 2, so the model gives each class probability 0.5 on every example. It has learned nothing that helps.
4. At d = 128 and T = 512, is attention or the feed-forward layer more costly per token, and by how much?
Feed-forward: 8 × 128² = 131,072. Attention: 4 × 128² + 2 × 512 × 128 = 65,536 + 131,072 = 196,608. Attention costs 1.5 times as much.
5. Why is GELU(−3) close to zero but GELU(−1) is not?
For a very negative input, the probability that a normal number is below it is tiny, so x times that probability is almost zero. At −1 the probability is still 0.16, so the product is −0.1588.
6. What is the difference between what attention and the feed-forward layer do to a token?
Attention gathers information from other positions into the token's vector. The feed-forward layer transforms the token's own vector, with the same weights at every position.
Try this
Set aside two hours. You need Python and NumPy.
1. Run the activation table. Add the value of GELU and ReLU at 0.1 and at −0.1 and compare their gradients there.
2. Run the XOR experiment with ReLU in place of GELU. How many hidden units does it take to reach 100% accuracy for three different seeds?
3. Change XOR to three bits (parity of three). How many hidden units does GELU need?
4. Check the gradient of the whole feed-forward layer numerically, as we did for layer norm in Lesson 4.1.
5. Count the parameters of the feed-forward layer for a model you know the width of, and compare it with the model's reported size.
6. Replace the GELU by SwiGLU (two projections multiplied together, one passed through a sigmoid-weighted linear unit) at an expansion of 8/3, and count the parameters. Is it near 8 d²?
A good result is a layer that passes its gradient check, an XOR experiment that shows the gap between linear and nonlinear and a table of parameter shares. The next lesson puts attention and the feed-forward layer together with the residual stream and the norms, and trains a full small GPT.
Read more
Dan Hendrycks and Kevin Gimpel, "Gaussian Error Linear Units (GELUs)" (2016), defines the activation. Noam Shazeer, "GLU Variants Improve Transformer" (2020), compares gated feed-forward layers. Mor Geva, Roei Schuster, Jonathan Berant and Omer Levy, "Transformer Feed-Forward Layers Are Key-Value Memories" (2021), proposes the memory view. Ashish Vaswani and colleagues, "Attention Is All You Need" (2017), defines the block with its factor of four.
Tags: Build an LLM Feed-forward network GELU Activation function Transformer