Chapter 9: The Transformer Block¶
Figure 9.1: We combine our pieces into a reusable building block.
We did some information processing with feed-forward and normalized our math in Chapter 8. Now we have all the pieces. Multi-head attention allows tokens to communicate with others. Feed-forward layers allow tokens to have private thoughts. LayerNorm is there to help keep training under control. In this chapter you will:
- Combine these parts into a single Lego brick called a Transformer block.
- Add residual connections so deep networks can learn effectively.
- Stack multiple blocks to build depth.
Words to Know
- Transformer Block: A reusable block of code containing attention, feed-forward, and normalization.
- Residual Connection: A shortcut that lets information skip a step, keeping the original signal intact.
Theory¶
Putting the Pieces Together¶
Transformer blocks glue our tools together into one package. Here are the two lines of code that compute the forward pass of one Transformer block:
x = x + self.attn(self.ln1(x)) # "listen, then add to what I know"
x = x + self.ff(self.ln2(x)) # "think, then update what I know"
Notice the x = x + ... pattern, which is what makes deep neural networks work.
Trick 1: The Residual Connection¶
Instead of overwriting the data in a token with the output of the attention layer, we add new information on top of the original input. We call this technique a residual connection, also known as a skip connection (Figure 9.2).
Figure 9.2: Residual connections provide a direct highway through the block.
Picture a game of telephone. By the time you get to the 10th person they most likely won't know what was said at the beginning. This is where residual connections come into play. You would have a copy of the message written down to help people along the chain.
When backpropagating during training these values need to flow backwards through all the layers. Without residual connections these values can become too big or too small. Because we are adding the original value through the +x highway we can pass values through many layers stacked on top of each other.
Trick 2: Pre-Layer Norm¶
Notice that we apply LayerNorm before each major step: attention(LayerNorm(x)).
This is known as the "pre-norm" convention that most GPT models follow (Figure 9.3). By normalizing our inputs before we perform these operations, we can keep our values nice and stable, allowing us to train with stable values from the start.
Figure 9.3: Normalize the data before the hard work.
Stacking Blocks¶
A single Transformer block is very powerful but we need to have more than one, so we chain many together (Figure 9.4). We will use 4 blocks.
As mentioned before each block will build on what the previous one did for each token's list of numbers. You can think of it as reading through a story many times. You might first learn who all the people are, then you may learn what they want and on your third read through you could figure out what the story is about. Similar idea with each Transformer block learning simpler concepts then moving onto harder ones.
Figure 9.4: Stacking blocks allows the model to find complex patterns.
Stacked Transformer blocks on the overview map in Figure 9.1 are the main component of our engine. Our engine is now ready to convert the embeddings into lists of numbers that represent the context of each token.
Code¶
Run the script to see a block process data and to check the parameter count.
$ python src/ch08_transformer_block.py
One TransformerBlock parameters: 197,888
MultiHeadAttention : 65,664
FeedForward : 131,712
LayerNorms (x2) : 512
Input shape: torch.Size([2, 10, 128])
Output shape: torch.Size([2, 10, 128]) (same as input)
--- Residual connection demonstration ---
The input is never lost -- it always flows through.
Original token norm : 11.470
Attention output norm: 4.599
After residual norm : 12.903 (combined)
--- Stacking multiple blocks ---
Stacking 4 blocks:
Params per block: 197,888
Total params : 791,552 (4 x 197,888)
Input shape: torch.Size([2, 10, 128])
Output shape: torch.Size([2, 10, 128]) (unchanged after 4 blocks)
What just happened:
- Lines 4 through 8 build a block containing attention, feed-forward, and LayerNorm.
- Line 12 shows the residual connection combine the original token data with the attention output. The three
normlines print the overall size of each list of numbers. - We stacked 4 blocks and saw the data flow through smoothly.
Shape Check:
- Input to TransformerBlock:
[Batch, Time, 128] - Output of TransformerBlock:
[Batch, Time, 128]
Each block is shape-preserving. Input and output are the same shape. You can stack blocks together like Lego bricks.
Try It¶
Try It
Edit src/ch08_transformer_block.py and modify the number of layers in the stack from config.n_layers to 12. Execute the script once more. Keep track of how the total number of parameters increases. The output shape stays precisely the same.
In Business
Software should be built with building blocks. A Transformer block is such a building block. Your house-style writing assistant isn't good enough? Add more Transformer blocks and train it longer. Don't try to reinvent the wheel.
Key Takeaways¶
- A Transformer block combines LayerNorm, attention, and feed-forward layers.
- Residual connections (
x + ...) create a direct highway for data, so deep models can learn effectively. - Pre-norm applies LayerNorm before the hard work to stabilize the math.
- Because blocks preserve the shape of the data, we can stack them modularly.
Check Your Understanding¶
- Why do we add the attention output to the original input (
x + attention)? - What does "pre-norm" mean?
- Why does the Transformer block output exactly the same shape it took in?
Assignment¶
Assignment 9: New numbers, same highway
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/ch08_transformer_block.pyas it is. Copy four lines:Original token norm,Attention output norm,After residual normandTotal params. Here a norm is one number that says how large a token's list of numbers is overall. - Change one number. Find the line
torch.manual_seed(42). The seed fixes the random starting numbers, so every run prints the same values. Change42to any whole number you like and run the script again. - Compare. Which of the four lines changed, and which did not? In your new run, which is larger, the original token or the attention output? Is
After residual normcloser to the original token or to the attention output? - Explain it. In two or three sentences a manager could follow, say what the three norm lines show about a residual connection: what the block keeps and what it adds.
Hand in: both sets of four lines, your answers to step 3, and your sentences.
Further Reading¶
The shortcut that makes depth possible. Previously adding more layers made models perform worse, since the learning signal would weaken as it propagated backwards. This paper introduced adding the input of a block onto its output, giving the signal a clear path through. This technique was demonstrated using image models, and every Transformer block uses it now, including Chapter 9's.
The architecture this book builds. Sequential reading (i.e. reading one step at a time) is slow, as step 500 cannot begin until step 499 is complete, and words far away from the current position remain difficult to relate. This paper eliminated sequential reading and retained only attention and positional encoding of each token. All tokens may now be processed simultaneously, allowing training on massive amounts of text to become feasible. The architecture you'll implement in Chapters 6-10 is this architecture, scaled down.
He, K., Zhang, X., Ren, S., & Sun, J. (2015). Deep residual learning for image recognition (arXiv:1512.03385). arXiv. https://doi.org/10.48550/arXiv.1512.03385
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., & Polosukhin, I. (2017). Attention is all you need (arXiv:1706.03762). arXiv. https://doi.org/10.48550/arXiv.1706.03762