Lesson 7 of 187 min
Normalization layers
With skips, every block adds to the numbers, so they grow block by block; a norm rescales them before each block, so every block reads numbers of the same size.
After this lesson you can say what BatchNorm and LayerNorm keep stable.
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.
Look inside a norm
A norm's learned scale and shift are its weight and bias, one of each for every neuron. They start at 1 and 0, so a new norm only rescales. Training moves them when a different size helps. A LayerNorm for 32 neurons learns 64 numbers. LayerNorm in PyTorch
import torch
from torch import nn
norm = nn.LayerNorm(32)
print(norm.weight.shape, norm.bias.shape)
print(norm.weight[:4].tolist(), norm.bias[:4].tolist())
print(sum(p.numel() for p in norm.parameters()))torch.Size([32]) torch.Size([32]) [1.0, 1.0, 1.0, 1.0] [0.0, 0.0, 0.0, 0.0] 64
BatchNorm at test time
While it trains, BatchNorm uses each batch's own averages and moves its running averages a tenth of the way toward them (momentum is 0.1). After .eval() it uses the running ones, so one picture works. A batch of four gives noisy averages, which is why BatchNorm wants big batches. BatchNorm1d in PyTorch
torch.set_printoptions(precision=2)
x = torch.tensor([[2., 2, 6, 6], [1, 3, 1, 3], [10, 30, 30, 10], [8, 8, 0, 0]])
bn = nn.BatchNorm1d(4)
bn(x) # training mode: this batch's averages
print(bn.running_mean, bn.momentum)
bn.eval()
print(bn(x[:1])) # test mode: one picture is finetensor([0.53, 1.08, 0.93, 0.47]) 0.1 tensor([[0.87, 0.22, 1.11, 3.35]], grad_fn=<NativeBatchNormBackward0>)
RMSNorm, worked
RMSNorm takes no average away. It divides each number by the row's size: the square root of the average square. For 2, 2, 6 and 6 that is the square root of 20, about 4.47. It keeps a learned scale and has no shift. RMSNorm in PyTorch, the RMSNorm paper
row = torch.tensor([[2., 2, 6, 6]])
print(nn.RMSNorm(4)(row))
print(row / row.pow(2).mean().sqrt())tensor([[0.45, 0.45, 1.34, 1.34]], grad_fn=<MulBackward0>) tensor([[0.45, 0.45, 1.34, 1.34]])
Before each part, or after
This lesson and Qwen3 put the norm before each part, inside the skip. The 2017 transformer put it after the sum. Then the numbers the skips carry are rescaled every block too. OLMo 2 puts its norm on each part's output instead. Research such as Dynamic Tanh replaces the norm altogether. Qwen3 source, OLMo 2, Transformers without Normalization
torch.manual_seed(0)
parts = [nn.Linear(32, 32) for _ in range(50)]
norms = [nn.LayerNorm(32) for _ in range(50)]
pre = post = torch.randn(8, 32)
with torch.no_grad():
for part, norm in zip(parts, norms):
pre = pre + torch.relu(part(norm(pre))) # before the part
post = norm(post + torch.relu(part(post))) # after the sum
print(f"{pre.std():.2f} {post.std():.2f}")2.76 1.00
Small batches of pictures
An image network with small batches often uses GroupNorm. It rescales groups of channels inside one picture, so the batch size doesn't matter. Here two groups of two channels each come out with an average of 0 and a spread of 1. GroupNorm in PyTorch
torch.manual_seed(0)
pics = torch.randn(2, 4, 8, 8) * 5 + 3 # 2 pictures, 4 channels of 8 by 8
out = nn.GroupNorm(num_groups=2, num_channels=4)(pics)
print(f"{out[0, :2].mean():.2f} {out[0, :2].std():.2f}")0.00 1.00
Run on Python 3.13.3, PyTorch 2.15.0 and scikit-learn 1.9.1. 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
A model has BatchNorm before its blocks. Still in training mode, you give it one picture, and PyTorch stops with an error. Why?
3 of 3
One picture's numbers at a layer are 2, 4, 4, 4, 5, 5, 7 and 9. Their spread is 2. A norm rescales them, before its learned scale and shift. What does the 9 become?
The ideas in this lesson
- Normalization
- Before each block, rescale its numbers to an average of 0 and a spread of 1, so every block reads numbers of the same size.
- LayerNorm and BatchNorm
- LayerNorm rescales each example's own numbers together; BatchNorm rescales each neuron's numbers across the batch, so it needs a batch.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
What keeps a deep network steady
Here's a puzzle. Skips let a deep network learn. So let's stack many more layers, each with its skip. Before any training, its numbers should be small. Instead, they grow into the thousands. So what keeps a deep network's numbers steady?
Fifty layers
Here's the digits network with a skip around every block. Each block adds its output to the numbers that came in.
Twenty layers? Almost ninety-six percent right.
Now make it fifty layers, and train it the same way. Will it get more right, about the same, or fewer?
Deeper still is worse
After one epoch... about two percent. That's worse than picking a digit at random.
After thirty epochs, about seventy-seven.
And its loss at the start is almost seventeen thousand. A network that hasn't learned anything should start near two point three.
The numbers grow block by block
Where does a loss that big come from?
Look at the numbers on the way up.
Each bar is the spread of what a block reads: how far its numbers sit from their average. Block two reads a spread under zero point two. Block forty, over five hundred. Block fifty, over four thousand.
Each block adds its output to the numbers that came in, and bigger numbers in make bigger numbers out. So the numbers grow at every block. At the top, the scores come out in the thousands, and so does the loss.
One step, very different effects
So why does that stop it from learning?
A block multiplies what it reads by its weights. And Adam moves every weight by about the same small step. Say, a thousandth. Block two reads numbers under zero point two in size. A weight there multiplies one of them, so the output barely moves. Block fifty reads numbers over four thousand in size. How far does the output move there?
About four. That's about twenty-five thousand times more. One learning rate is too big for one block, and too small for another.
Rescale before each block
Can we keep the numbers the same size at every block?
Yes. Before each block, rescale them: shrink or stretch them, so their spread is always one. Take away their average, then divide by their spread.
Here's one picture's four numbers: two, two, six and six.
Their average is four. Each one sits two away from it, so their spread is two. What do they become?
Minus one, minus one, one and one. Each number now says how far it is above or below the average. Then each neuron gets two numbers it learns: a scale and a shift. So the network can still pick a different size on purpose. That's normalization. A layer that does it is called a norm.
Every block reads a steady size
Now put a norm before every block, and one before the last layer, so the scores are steady too. Every block reads numbers with a spread of one, from the first to the last.
The loss at the start is about two point two, close to the two point three of a fair guess.
After one epoch, about eighty-one percent. After thirty... almost ninety-seven.
Rows or columns
A norm rescales numbers to an average of zero and a spread of one, before each block. But which numbers go together?
At one layer, a batch is a grid: a row for each picture, and a column for each neuron. LayerNorm rescales each row: one picture's own numbers, together.
BatchNorm rescales each column: one neuron's numbers, across the batch.
What each one keeps
So with LayerNorm, every picture comes out the same size. With BatchNorm, picture C, the big one, stays bigger than the others, and each neuron's column averages zero.
Both keep what each block reads steady. Fifty layers with BatchNorm get almost ninety-nine percent.
BatchNorm needs a batch
So when do you use each one? Give a model with BatchNorm one picture, in training mode, the mode it learns in. What happens?
PyTorch stops. One picture has nothing to average with. So while it trains, BatchNorm keeps a running average for each neuron, and at test time it uses those. Model dot eval switches it over. LayerNorm only needs one picture's own numbers, and it acts the same in training and at test time. So transformers, the networks behind chatbots, use it in every block. Today's big models use a lighter version, RMSNorm. It only divides by the size, and skips the average. So: BatchNorm where batches are big, like in ResNet and other image networks. LayerNorm where one example has to stand alone, like in transformers.
In code
In code, here's the small batch. LayerNorm, with four neurons, rescales every row to minus one and one. BatchNorm rescales each column.
On one row alone, BatchNorm stops with the error. The block with a skip gets one more call: the norm, before the layer. Fifty layers of these score almost ninety-seven percent.
And a real chatbot model calls a norm before each of its two parts.
Steady, block after block
So, skips make the numbers grow, block by block. A norm rescales them before each block, to an average of zero and a spread of one. LayerNorm does it by rows, one picture at a time. BatchNorm does it by columns, across the batch.
Steady
A deep network learns well when every block reads the same size. Now try it on this lesson's page, and take the quiz. Find out if normalization helps a shorter network too.
You use this lesson in Lab 3: A deep digit reader that doesn't memorize, after Dropout, weight decay and early stopping.
Facts last checked on .
