Chapter 8: Feed-Forward and Norms¶
Figure 8.1: With attention built, we now process that context.
While attention (from Chapter 7) lets a token gather information from its neighbors, gathering information is only half the job. The token still needs to process that information and decide what to do with it. In this chapter you will:
- Build a feed-forward network to process context.
- Use a GELU curve to help the model learn smoothly.
- Add Layer Normalization to keep the math stable.
Words to Know
- Feed-Forward: The step after attention, where each token works on its own to process the information it gathered.
- GELU: A smooth curve that replaces negative numbers with near-zero values.
- LayerNorm: A step that resets numbers to a safe size so training stays stable.
Theory¶
Thinking on Your Own¶
Attention is like listening to your team explain their ideas, while feed-forward is going back to your desk and thinking it over yourself.
Figure 8.2: The network expands each token to 512 numbers, then compresses it back to 128.
The feed-forward layer is a small neural network that operates on each token individually. As seen in Figure 8.2 we take each token which is 128 numbers long and increase it to be 512 numbers. We have more room with this 4x expansion to expand the thinking out and give it to the feed-forward network, which will return us to 128 numbers at the end.
The Smooth GELU Curve¶
Inside the feed-forward network, we apply a mathematical curve called GELU.
Figure 8.3: GELU replaces a hard switch with a smooth dimmer.
The neural network has to have some non-linearity (a curved line) to be able to learn complex patterns. An older choice is ReLU. This function is like an on/off switch where anything less than 0 will equal 0 and any number greater than 0 will remain as is.
GELU works more like a dimmer switch (Figure 8.3). Anything with a high negative value will be close to 0. Numbers close to 0 will have a slight decrease and any positive number will remain about the same.
When we train our network we use math (calculus) to work out how to adjust the model's weights. Having an abrupt turn can cause the math to act unstable which the GELU function helps with by having a smoother turn. This is why you see GELU used in most current models.
Keeping Numbers Safe with LayerNorm¶
When you have numbers traveling through many layers of your neural network, they can become too large or too small. Similar to compound interest once numbers start multiplying each other by a lot they can reach absurdly large or small numbers which don't allow our training to work correctly.
This is where Layer Normalization (LayerNorm) comes into play. We take all the numbers that travel through each token and normalize them. After a LayerNorm we will always have an average of 0 and std of 1. These numbers are printed out as mean and std in the cell below.
Figure 8.4: LayerNorm centers messy numbers back around zero.
It's similar to taking a marathon race and having everyone's timer start from zero after each lap (Figure 8.4). The leader doesn't change, it just makes the values smaller. We apply LayerNorm before each major step in modern models, and this will allow our attention and feed-forward layers to receive better inputs.
In Figure 8.1 we take what we learned from our attention layer and run it through our feed-forward network. LayerNorm keeps the math stable before sending the output to the next layer.
Code¶
| src/ch07_feedforward.py (excerpt) | |
|---|---|
Run the script to see the feed-forward layer and LayerNorm in action.
$ python src/ch07_feedforward.py
--- GELU activation ---
GELU is like ReLU (zeros out negatives) but with a smooth curve.
Input : [-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0]
GELU : [-0.004, -0.159, -0.154, 0.0, 0.346, 0.841, 1.954, 2.996]
ReLU : [0.0, 0.0, 0.0, 0.0, 0.5, 1.0, 2.0, 3.0]
--- Layer Normalization ---
LayerNorm re-centers and re-scales values at each position.
Before LayerNorm: mean=5.23, std=9.13
After LayerNorm: mean=0.0000, std=1.0039
What just happened:
- Lines 7 and 9 build a feed-forward network that expands from 128 to 512, then back to 128.
- Line 8 applies GELU, which gently reduces negative numbers instead of snapping them to zero.
- We passed messy numbers through LayerNorm and saw them neatly centered at zero with a standard spread of 1.
Shape Check:
- Input to FeedForward:
[Batch, Time, 128] - Output of FeedForward:
[Batch, Time, 128]
Try It¶
Try It
Open src/ch07_feedforward.py and modify the LayerNorm input to have a very large spread: x_single = torch.randn(config.n_embd) * 1000 + 500. Execute the script again. Note that LayerNorm still normalizes it back to mean 0 with standard deviation of 1.
In Business
Suppose you were trying to train an assistant that would write emails for you in your company's house style. If your ML system was shaky, it might produce nonsense. LayerNorm is like having a manager verifying work in between steps so that the data never gets too out of line before proceeding to the next group.
Key Takeaways¶
- The feed-forward layer processes each token independently to build meaning.
- It expands the token's data 4x to give the model a wider workspace.
- GELU provides a smooth mathematical curve to make training stable.
- LayerNorm resets numbers to a safe size so deep networks do not break.
Check Your Understanding¶
- Why does the feed-forward network expand its input size by 4?
- What happens to a strongly negative number when it passes through GELU?
- What is the average value of a token's numbers immediately after LayerNorm?
Assignment¶
Assignment 8: Dimmer or switch
About 15 minutes. You change one number and write no new code. Work in this chapter's Colab notebook or on your own laptop.
- Run it. Run
src/ch07_feedforward.pyas it is. Copy the three lines it prints underGELU activation: theInput,GELUandReLUlines. - Change one number. Find the line
sample = torch.tensor([-3.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, 3.0]). These are the eight test numbers the script feeds to GELU and to ReLU. Change the first one,-3.0, to-2.0and run the script again. The list now holds-2.0and2.0, two numbers of the same size with opposite signs. - Compare. What does GELU print for
-2.0, and what does it print for2.0? What does ReLU print for the same two numbers? Which of the two, GELU or ReLU, gives-3.0and-2.0exactly the same result? - Explain it. In two or three sentences a manager could follow, say what GELU does to a positive number and to a negative number of the same size, and why the chapter calls GELU a dimmer and ReLU a switch.
Hand in: both sets of three lines, your answers to step 3, and your sentences.
Further Reading¶
The line that keeps training stable. As numbers pass through a deep stack they drift, some growing, some shrinking, until learning stalls. Layer normalization rescales each token's vector back to a standard spread before the next step, using only that token's own numbers, so it works the same whatever the batch size. It is one line in Chapter 8 and one of the reasons deep Transformers train at all.
The smooth switch inside the feed-forward layer. A network needs a non-linear step, or every layer collapses into one. The common choice cut everything negative to zero, a hard switch. GELU fades instead of cutting, which gives the optimizer a gentler surface to work on and is the activation used in GPT-style models, including the one in Chapter 8.
Ba, J. L., Kiros, J. R., & Hinton, G. E. (2016). Layer normalization (arXiv:1607.06450). arXiv. https://doi.org/10.48550/arXiv.1607.06450
Hendrycks, D., & Gimpel, K. (2016). Gaussian error linear units (GELUs) (arXiv:1606.08415). arXiv. https://doi.org/10.48550/arXiv.1606.08415
Next up: Chapter 9: The Transformer Block