Skip to content
Module 2 ยท Building the Model
Chapter 9 of 17
Run it in your browser

Chapter 9: The Transformer Block

The map with Transformer Blocks highlighted Figure 9.1: We combine our pieces into a reusable building block.

After processing information with feed-forward and normalizing the math in Chapter 8, we now have all the ingredients. Multi-head attention lets tokens talk to each other, feed-forward layers let tokens think for themselves, and LayerNorm keeps training stable. 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

A single Transformer block combines our tools into one unit, and its forward pass is two lines of code:

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

Rather than overwrite the data in a token with the output of the attention layer, we add the fresh information onto the original input. This is known as a residual connection, also called a skip connection (Figure 9.2).

The data flows down a main highway, taking side trips for attention and feed-forward 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 the modern "pre-norm" convention used by GPT models (Figure 9.3). We normalize the data before doing the heavy lifting. This means that attention and feed-forward always operate on well-behaved numbers, stabilizing training early on.

Data passes through LayerNorm before entering the Attention layer 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.

Multiple blocks stacked on top of each other, from simple patterns to more complex 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

src/ch08_transformer_block.py (excerpt)
class TransformerBlock(nn.Module):
    def __init__(self):
        super().__init__()
        self.attn = MultiHeadAttention()
        self.ff   = FeedForward()
        # Layer normalization applied before attention and feed-forward
        self.ln1  = nn.LayerNorm(config.n_embd)
        self.ln2  = nn.LayerNorm(config.n_embd)

    def forward(self, x):
        # The + creates a residual connection, adding new info
        x = x + self.attn(self.ln1(x))
        x = x + self.ff(self.ln2(x))
        return x

Run the script to see a block process data and to check the parameter count.

Terminal
$ 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:

  1. Lines 4 through 8 build a block containing attention, feed-forward, and LayerNorm.
  2. Line 12 shows the residual connection combine the original token data with the attention output. The three norm lines print the overall size of each list of numbers.
  3. 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]

The block is shape-preserving. The input and output have identical shapes, so we can stack blocks 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

You want building blocks when you build software. Things you can plug together and scale up. A Transformer block is a building block. So if your house-style writing assistant isn't smart enough, you just stack more blocks and train longer. No need to invent a new architecture!

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

  1. Why do we add the attention output to the original input (x + attention)?
  2. What does "pre-norm" mean?
  3. 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.

  1. Run it. Run src/ch08_transformer_block.py as it is. Copy four lines: Original token norm, Attention output norm, After residual norm and Total params. Here a norm is one number that says how large a token's list of numbers is overall.
  2. Change one number. Find the line torch.manual_seed(42). The seed fixes the random starting numbers, so every run prints the same values. Change 42 to any whole number you like and run the script again.
  3. 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 norm closer to the original token or to the attention output?
  4. 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. Stacking more layers used to make networks worse, because the learning signal degraded on the way down. This paper added the input of a block back onto its output, which gave the signal a clear path through. It was shown on image models, and every Transformer block, including the one in Chapter 9, uses it.

The architecture this book builds. Reading a sequence one step at a time is slow, because step 500 cannot start until step 499 has finished, and distant words stay hard to connect. This paper removed the step-by-step reading and kept only attention, plus a note of each token's position. Every token can then be processed at once, and that made training on very large amounts of text practical. The model you build in Chapters 6 to 10 is this design, made small.

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

Next up: Chapter 10: The Full GPT Architecture