Lesson 8 of 96 min
The transformer block
A transformer is one block repeated: in each, attention lets the tokens share and an MLP works on each token alone, each part reading a rescaled copy and adding its change to the vector that runs up through them all.
After this lesson you can follow a token through attention, the MLP, the residual and the norm.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
The MLP has a gate
The MLP in Qwen3 has three layers. Two widen the 1,024 numbers to 3,072 side by side. One is bent by SiLU, and the two are multiplied number by number. The third brings them back to 1,024. Three layers of 1,024 × 3,072 are the 9,437,184 weights the video counted. GLU Variants Improve Transformer
import torch
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-0.6B-Base", dtype=torch.float32)
mlp = model.model.layers[0].mlp
print(mlp.gate_proj, mlp.up_proj, mlp.down_proj, mlp.act_fn, sep="\n")
x = torch.randn(1, 5, 1024)
silu = torch.nn.functional.silu
mine = mlp.down_proj(silu(mlp.gate_proj(x)) * mlp.up_proj(x))
print(torch.allclose(mine, mlp(x), atol=1e-5))Linear(in_features=1024, out_features=3072, bias=False) Linear(in_features=1024, out_features=3072, bias=False) Linear(in_features=3072, out_features=1024, bias=False) SiLUActivation() True
Two more norms, inside attention
The block's own two norms are the ones the video showed. Qwen3 also rescales the queries and the keys of every head, 128 numbers each, just before their dot product. These are the q_norm and k_norm you saw in the printed block. Qwen3-0.6B-Base's configuration
attn = model.model.layers[0].self_attn
print(attn.q_norm, attn.k_norm, sep="\n")
c = model.config
print(c.num_attention_heads, c.num_key_value_heads, c.head_dim)Qwen3RMSNorm((128,), eps=1e-06) Qwen3RMSNorm((128,), eps=1e-06) 16 8 128
Older blocks: GPT-2 and the first transformer
GPT-2 (2019) has the same shape: a norm, attention, a norm, the MLP. Its norm is LayerNorm, and its MLP is two plain layers bent by GELU, with no gate. The first transformer of 2017 put the norm after each add, x = norm(x + attn(x)), so the vector itself was rescaled every time. Attention Is All You Need
from transformers import AutoConfig
config = AutoConfig.from_pretrained("openai-community/gpt2")
gpt2 = AutoModelForCausalLM.from_config(config)
block = gpt2.transformer.h[0]
print([name for name, _ in block.named_children()])
print(block.ln_1, block.mlp.act, sep="\n")['ln_1', 'attn', 'ln_2', 'mlp'] LayerNorm((768,), eps=1e-05, elementwise_affine=True, bias=True) NewGELUActivation()
Why the stream keeps growing
Every part adds its change, so the stream's length mostly climbs on the way up. With the norm before each part, each part still reads a copy at one steady size. That is a big reason deep stacks train more steadily with the norm first. On Layer Normalization in the Transformer Architecture
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B-Base")
ids = tok("Penguins live in the", return_tensors="pt").input_ids
with torch.no_grad():
hs = model(ids, output_hidden_states=True).hidden_states
print([round(h[0, -1].norm().item()) for h in hs[:-1]])[1, 10, 12, 12, 16, 17, 21, 23, 38, 26, 32, 44, 51, 54, 57, 49, 58, 72, 94, 115, 141, 193, 242, 312, 375, 450, 528, 565]
Run on Python 3.13, PyTorch 2.15.0, Transformers 5.24.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Vanishing gradients and residual connections
A block works out h + torch.relu(self.layer(h)). On the way back, a slope of 2 reaches the block's output. The path through the layer passes back 0.5 of it. What slope reaches h?
2 of 3
Take one of the model's 28 blocks out, and run the other 27. For most blocks, it still guesses "Antarctic". Why?
3 of 3
Seven tokens' vectors, 1,024 numbers each, go through the second half of a block: a norm, an MLP that widens to 3,072 and comes back, and its change added. What does this print?
import torch
from torch import nn
x = torch.randn(7, 1024)
norm = nn.RMSNorm(1024)
mlp = nn.Sequential(nn.Linear(1024, 3072), nn.ReLU(), nn.Linear(3072, 1024))
x = x + mlp(norm(x))
print(x.shape)The ideas in this lesson
- Transformer block
- Attention, then an MLP on each token alone; each reads a rescaled copy and adds its change back.
- The stack
- The same block repeated, each with its own weights; after the last, a norm and the table give every token a score.
- Residual stream
- The vector each token carries up through every block: each part reads a copy and adds its change to it.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
On the way up
Here's a question. A model reads "Penguins live in the". It guesses the next word: Antarctic. But attention is only one part of the model. So what else happens to a word on its way up?
Twenty-eight blocks
This model is built from twenty-eight blocks, one on top of another. Each token's vector goes up through all of them.
Follow the last word so far, the little word "the". That's our token. After which block does "Antarctic" become its best guess for the next word? After the first few? About halfway? Or only at the very top?
Attention: the tokens share
A model like this is one kind of block, repeated. So what's inside one block? Its first part is attention, where the tokens share with each other. Our token takes in a blend from the tokens before it, and from itself. That blend is attention's change to the token.
The MLP: each token alone
And the second part? A network of neurons, the MLP, from Deep Learning. It's the same network for every token. It takes the token's numbers, makes three times as many, then brings them back down. It works on this token alone. No lines go to the other tokens.
Add, don't replace
So what does each part do with its change? Does it replace the token's vector?
No. The vector goes around the part, and the part's change is added to it. That's the skip from Deep Learning.
So each part only writes a change onto the vector, and the vector keeps what it had.
The vector's length was under one. After this first block, it's nearly ten.
A norm before each part
So where does the norm come in? Before each part, a norm rescales a copy of the vector. The part reads the copy. Today's models use one called RMSNorm.
Every part adds to the vector. So what happens to its length on the way up?
It grows, from under one at the start to about five hundred at the top. The norm rescales only the copy, so the vector keeps everything every part added. So in a block, each part reads a rescaled copy, and adds its change back.
The stack
A block is attention, then an MLP. Each one reads a rescaled copy, and adds its change. This model stacks twenty-eight blocks of this one kind, each with its own weights.
So after the last block, how does the vector become a guess for the next word? First comes one more norm. Then the vector is matched against every row of the table, the rows the tokens started from. A dot product with each row gives every token a score. That norm and that match are the model's last step. Then softmax turns the scores into chances. "Antarctic" gets the biggest, more than a quarter.
The residual stream
In every block, each part reads a copy of the token's vector, and adds its change to it. That vector, running up through every block, is called the residual stream. It's like a notebook passed up a line of people. Each person reads it and adds a few lines. Nobody starts a new notebook. Here, what each part writes is added number by number. Nothing else passes up from block to block.
The answer forms at the top
So when does the stream know the answer?
The stream is the same kind of vector at every height. So the model's last step can read it after any block.
Remember your guess?
After block one, its best guess is "following". After block nineteen: "region". After twenty-two: "cold".
And "Antarctic"... only after the very last block. Each block adds what it found, and the answer forms at the top.
Take one out
So is each block a link in a chain?
Take one block out, and run the other twenty-seven. Will it still say "Antarctic"?
For seventeen of the twenty-eight blocks, yes.
And most of the others still guess something close. Each block only adds its change. So without one block, the stream still carries what the other twenty-seven wrote. But the first three blocks can't go. Without one of them, the guess is nonsense.
In code
Now in real code. Print the model's first block. Like every PyTorch model, it lists its parts by name: attention, the MLP, and two norms.
Now write the block yourself, in two lines, with those parts. Add attention's change. Then add the MLP's.
A check against the model's own block says: True.
Now count the weights in each part. Which part holds more?
The MLP: about nine million, compared to six million for attention. And all twenty-eight blocks together? About four hundred and forty million weights: three quarters of the whole model. The table holds the rest.
Today's chat models are built from blocks like this one, stacked.
Three ideas
So a block is attention, then an MLP. Each reads a rescaled copy, and adds its change. Blocks of one kind are stacked, with the table at the top. And the residual stream carries everything up.
One block, stacked
A transformer is one kind of block, stacked many times. Now try it on this lesson's page, and take the quiz. Read the stream after any block.
You use this lesson in Lab 3: Open up a real transformer, after Encoders and decoders.
Facts last checked on .
