Lesson 7 of 87 min
Stochastic gradient descent
Take many cheap steps, each on a few examples picked at random: their arrows are a little off, but right on average, and they get there sooner.
After this lesson you can explain why training uses small random batches.
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.
Why a batch of 32 costs little more than 8
A computer works out the examples of a batch side by side, so four times the examples does not take four times as long. Here one layer of a network runs on batches of 8, 32 and 128 on a Mac's processor. A graphics chip (a GPU) does even more side by side, until its memory is full.
import time
layer = torch.nn.Linear(1024, 1024)
for size in [8, 32, 128]:
batch = torch.randn(size, 1024)
layer(batch)
start = time.perf_counter()
for _ in range(200):
layer(batch).sum().backward()
print(size, round((time.perf_counter() - start) / 200 * 1000, 2), "ms")8 0.77 ms 32 0.93 ms 128 1.43 ms
The loss your script prints
The loss inside the loop is the last batch's, not the loss on every example. It jumps up and down, even when training goes well. Here, after each epoch, is the last batch's loss beside the loss on all 342 penguins. x and mass are the video's penguins, and data = TensorDataset(x, mass).
torch.manual_seed(0)
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=0.1)
for epoch in range(3):
for xb, mb in DataLoader(data, batch_size=32, shuffle=True):
loss = ((w * xb + b - mb) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
print(epoch + 1, round(loss.item(), 3), round(((w * x + b - mass) ** 2).mean().item(), 3))1 0.361 0.274 2 0.147 0.157 3 0.204 0.155
The short last batch
342 penguins in batches of 32 leave 22 at the end, so the last batch is smaller. Most of the time that is fine. If your code needs every batch the same size, drop_last=True leaves the short one out, and those examples wait for the next epoch's shuffle.
print(len(DataLoader(data, batch_size=32)))
print(len(DataLoader(data, batch_size=32, drop_last=True)))
print([len(xb) for xb, mb in DataLoader(data, batch_size=32)][-2:])11 10 [32, 22]
A bigger batch, a bigger learning rate
A bigger batch takes fewer steps an epoch, and its arrow is closer to the full one, so it can take a bigger share of it. Batches of 128 at 0.1 are still far from the bottom after three epochs; at 0.3 they get there. Large models also start small and raise the learning rate for a while: a warmup.
for size, lr in [(32, 0.1), (128, 0.1), (128, 0.3)]:
torch.manual_seed(0)
w = torch.tensor(0.0, requires_grad=True)
b = torch.tensor(0.0, requires_grad=True)
opt = torch.optim.SGD([w, b], lr=lr)
for epoch in range(3):
for xb, mb in DataLoader(data, batch_size=size, shuffle=True):
loss = ((w * xb + b - mb) ** 2).mean()
opt.zero_grad(); loss.backward(); opt.step()
print(size, lr, round(((w * x + b - mass) ** 2).mean().item(), 3))32 0.1 0.155 128 0.1 0.462 128 0.3 0.155
Three older names
Older courses give three names. Steps on every example are "batch gradient descent". Steps on one example are "stochastic gradient descent". Steps on a few are "mini-batch gradient descent". Today "SGD" means steps on mini-batches, and in code they are the same loop with another batch size.
for size in [342, 32, 1]:
print(size, len(DataLoader(data, batch_size=size)))342 1 32 11 1 342
Run on Python 3.13, PyTorch 2.15.0, pandas 3.1.1 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: Gradient descent and the learning rate
Your training code has torch.optim.SGD([w, b], lr=1.0), and the loss it prints climbs at every step. What do you change?
2 of 3
The same work, two ways: one step on all 1,000 examples, or 20 steps on batches of 50 picked at random. Which usually ends lower?
3 of 3
Your data holds 1,000 examples, and your code has DataLoader(data, batch_size=64, shuffle=True). How many times does opt.step() run in one epoch?
The ideas in this lesson
- Mini-batch
- A few examples picked at random: their arrow is close to the full one, right on average, and far cheaper to work out.
- Stochastic gradient descent
- Take each step on a fresh random mini-batch: a wobbling path, and many cheap steps that get there sooner.
- Epoch
- One pass through every example, in mini-batches; training shuffles them and runs for many.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
The same work, two ways
Here's a bet. Each step, the model looks at all its examples. Say you can look at each one once. One careful step, using them all? Or many quick steps, each using a few picked at random? Which way ends up lower?
Every penguin pulls
Here's the penguins' bowl again. The walker stands at zero, zero: a line that knows nothing, with a loss of eighteen point three.
So where does its arrow come from? Each penguin's miss has its own chain, and gives its own small arrow.
That's the penguin's pull on the line.
And every penguin pulls a different way.
The uphill arrow at zero, zero is minus two point seven three, minus eight point four.
It's the average of all three hundred and forty-two pulls.
So every step works out every one of them.
Real data is big
Three hundred and forty-two is easy. ImageNet is a set of photos that a lot of image recognition models learned from. It has more than a million.
One step would look at every one of them.
A mini-batch
So only look at a few. Pick thirty-two penguins at random, the way you'd ask a few dozen people what a whole town thinks.
Their arrow is the average of their thirty-two pulls.
Will it point the same way as the full arrow?
Nearly. Minus four point nine, minus eight point six five: about eleven degrees off. Close, but not exact.
A few examples picked at random like this... are called a mini-batch.
Right on average
Another thirty-two give another arrow. Cut all three hundred and forty-two into eleven batches, and you get eleven arrows. Some point to one side of the full arrow, some to the other. Together, the batches hold every penguin once. So add up all their pulls, divide by three hundred and forty-two... and you get the full arrow exactly. A batch's arrow is a little off. But it's not off in any one direction.
A fresh batch every step
So can you walk downhill on arrows that are a little off?
Take each step against a new random batch's arrow. The path zigzags a little, and it heads for the bottom.
The batches' errors point in all directions, so over many steps, they cancel out.
Taking steps on random mini-batches... is called stochastic gradient descent.
Stochastic means random.
Many quick steps win
Now the bet. The same work: each penguin looked at once.
One careful step takes the loss from eighteen point three... to eleven point four.
And eleven quick steps?
Zero point two seven... near the bottom, which is zero point one five five.
If you picked the careful step: its arrow is exact. But a step only goes a share of the arrow, the learning rate. Here, a tenth.
And you can't just make that one step bigger: too big a step leaps past the bottom. So eleven nearly-right steps go much further than one exact step.
A batch of one
Then why not one penguin per step? That's three hundred and forty-two steps for the same work.
Will the path get smoother, or wilder?
Wilder. One penguin gives one pull, with nothing to average, and it can point almost at a right angle to the full arrow. The path races down, then jumps around the bottom and never comes to rest. On its loss curve, the loss jumps between the bottom and zero point eight eight.
Again, and how many
Back to batches of thirty-two. After those eleven steps, every penguin has been looked at once. So what happens next?
An epoch
Shuffle the penguins, and go again.
One pass through every example... is called an epoch.
Here, an epoch is eleven batches: ten of thirty-two, and one of the twenty-two left over.
Training runs for many epochs. After one, the loss is zero point two seven. After two, it's at the bottom.
How big a batch
So how many penguins should a batch hold?
Somewhere between one and all of them.
One penguin per step is wild. All three hundred and forty-two makes every step slow. And with a million pictures, very slow.
In real code, start from a common number, like thirty-two, which is what Keras uses. Then only change it if you have a reason. If the loss curve jumps around, make the batch bigger: it averages more pulls. If a batch doesn't fit in the computer's memory, make it smaller.
In code
Now in real code. The penguins go into PyTorch's DataLoader, with a batch size of thirty-two, and shuffle set to true. It cuts them into eleven batches, in a new order every epoch. Then two loops. One goes over the epochs. Inside it, there's one step for each batch. It's the four lines of gradient descent, on that batch's penguins. The last line, step, is the rule itself. Three epochs. How many steps is that?
Thirty-three. And the line lands through the penguins. So always set the batch size. Without it, DataLoader hands out one example at a time.
The idea
So here's the idea. A mini-batch is a few examples, picked at random. Stochastic gradient descent takes each step on a fresh one: many cheap steps, each a little off, but right on average. And one pass through every example is an epoch.
Many quick steps
So take many quick steps, each on a few at random. Now try it on this lesson's page, and take the quiz. Find a batch size that beats the one we used.
You use this lesson in Lab 3: Batches, momentum and Adam, written by hand, after Momentum and Adam.
Facts last checked on .
