Lesson 10 of 188 min
Training on a GPU
Training holds 16 bytes for every weight, plus values that grow with the batch: so choose the batch that fits, use bf16 to hold a big model in half the room, and save as you go.
After this lesson you can choose a batch size and precision that fit in memory, and save checkpoints.
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.
Put the batch and the model on one device
PyTorch can check for an available accelerator and fall back to CPU. The shorter "cuda" if torch.cuda.is_available() else "cpu" form is common in CUDA tutorials. It falls back to CPU on a Mac. Move the model before you make the optimizer, and move each batch when you use it. PyTorch’s accelerator reference
import torch
from torch import nn
device = (
torch.accelerator.current_accelerator()
if torch.accelerator.is_available()
else torch.device("cpu")
)x = torch.arange(8, dtype=torch.float32).reshape(4, 2) / 8
y = x.sum(dim=1, keepdim=True)
torch.manual_seed(0)
model = nn.Linear(2, 1).to(device)
opt = torch.optim.Adam(model.parameters(), lr=0.01)
loss_fn = nn.MSELoss()
xb, yb = x.to(device), y.to(device)
print(next(model.parameters()).device.type == xb.device.type == yb.device.type)True
Add gradients across four small batches
A batch of four can be four batches of one when you accumulate the gradients before stepping. With four equal-sized pieces and a mean loss, divide each piece’s loss by four. Clear the gradients before the group and step once after it. If their sizes differ, weight each piece by its share of the total examples. PyTorch’s accumulation example
loss_fn(model(xb), yb).backward()
one_batch = [p.grad.clone() for p in model.parameters()]
opt.zero_grad()
for small_x, small_y in zip(xb.split(1), yb.split(1)):
(loss_fn(model(small_x), small_y) / len(xb)).backward()
print(all(torch.allclose(p.grad, expected) for p, expected in zip(model.parameters(), one_batch)))
opt.step()True
Pick the two-byte format your GPU supports
Use FP16 on a T4. A gradient scaler keeps small gradients from rounding down to zero as often. On supported Mac GPUs, this example uses BF16. It keeps the model’s parameters in FP32 and applies autocast around the forward pass and loss. Colab’s GPU availability varies. PyTorch’s AMP examples · NVIDIA T4 specifications · Colab’s FAQ
from contextlib import nullcontext
use_fp16 = device.type == "cuda" and not torch.cuda.is_bf16_supported(
including_emulation=False
)
use_autocast = device.type in {"cuda", "mps"}
dtype = torch.float16 if use_fp16 else torch.bfloat16
scaler = torch.amp.GradScaler("cuda", enabled=use_fp16)opt.zero_grad()
amp = torch.autocast(device.type, dtype=dtype) if use_autocast else nullcontext()
with amp:
loss = loss_fn(model(xb), yb)
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()
print(bool(torch.isfinite(loss)))True
Save enough to resume
Save the optimizer with the weights. This example also saves the CPU random state for the next shuffle. Save other random generators and any scheduler or gradient scaler your run uses. Keep cloud checkpoints in persistent storage. PyTorch’s checkpoint guide
from pathlib import Path
from tempfile import TemporaryDirectory
payload = {
"model": model.state_dict(), "opt": opt.state_dict(),
"epoch": 0, "cpu_rng": torch.get_rng_state(),
"scaler": scaler.state_dict(),
}with TemporaryDirectory() as folder:
path = Path(folder) / "epoch-0.pt"
torch.save(payload, path)
next_order = torch.randperm(len(x))
saved = torch.load(path, map_location="cpu", weights_only=True)model = nn.Linear(2, 1).to(device)
opt = torch.optim.Adam(model.parameters(), lr=0.01)
model.load_state_dict(saved["model"])
opt.load_state_dict(saved["opt"])
scaler.load_state_dict(saved["scaler"])
torch.set_rng_state(saved["cpu_rng"])
start = saved["epoch"] + 1
print(start, torch.equal(torch.randperm(len(x)), next_order))1 True
Measure the peak and decide what to change
On CUDA, measure peak tensor memory around a training step. Total GPU use can be higher. If a smaller batch leaves too little room, activation checkpointing trades computation for memory. A smaller optimizer can help. FSDP can split training state across GPUs. LoRA trains fewer parameters. PyTorch’s CUDA memory reference · Activation checkpointing · FSDP · LoRA paper
if device.type == "cuda":
torch.cuda.reset_peak_memory_stats(device)
opt.zero_grad()
loss_fn(model(xb), yb).backward()
opt.step()
if device.type == "cuda":
peak_bytes = torch.cuda.max_memory_allocated(device)
print(f"{peak_bytes / 1e9:.4f} GB allocated to tensors")Run on Python 3.13.3 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: The training loop
A training loop runs loss.backward(), then opt.zero_grad(), then opt.step(). Nothing crashes. For 30 epochs, the loss prints 2.33. What is wrong?
2 of 3
Your training run stops with "out of memory" at a batch of 8. What do you change first?
3 of 3
You train a model with 3 billion weights, with Adam, its numbers in four bytes. How many gigabytes of memory does it hold before any data goes in?
The ideas in this lesson
- What fills GPU memory
- Training holds 16 bytes for every weight, plus the values the forward pass keeps, which grow with the batch.
- bf16
- A number in 2 bytes instead of 4, with the same range but less exact: a model in bf16 takes half.
- Checkpoint
- Save the weights, the optimizer's numbers and the epoch as you go, so a stopped run goes on exactly where it was.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
Will it still fit?
Here's a question. You can use a model on your graphics card. Now you want to train it on that same card. Will it still fit?
How much more?
Take a model with eight billion weights. Just to use it, it takes thirty-two gigabytes of memory. The lines going across are the memory of the GPUs you can use or rent. How much to train it? About the same, twice as much, or four times?
What a GPU is for
First, why a GPU at all? A GPU is the chip on a graphics card. It can multiply thousands of numbers at once. Take GPT-2 small, a small language model. One training step on four short texts takes over a second on a Mac's CPU. On its GPU, it takes under half a second. But the digits network is too small to gain anything. Its whole run takes half a second on the CPU... and almost two seconds on the GPU. Moving each small batch, and starting the work, takes longer than the work itself.
Moving the work
To use the GPU, one line finds the one you have. On Colab, Google's free notebooks in the browser, it's called cuda. On a Mac, it's mps. Move the model there once. Then, inside the loop, move every batch. Spot what's missing in this loop.
The batch stays on the CPU, and the model is on the GPU. So PyTorch stops with an error.
Four bytes a number
So which GPU do you need? That depends on its memory. If a run doesn't fit, it stops. In this run, each weight takes four bytes. A gigabyte is a billion bytes. GPT-2 small has a hundred and twenty-four million weights. So they take half a gigabyte. We measured it, on the GPU.
Sixteen bytes a weight
Is that all that training holds? No. Every weight also has its slope: four bytes more.
And Adam keeps two numbers for every weight: eight bytes more.
That's sixteen bytes a weight. For GPT-2 small: half a gigabyte, another half, and one more. Two gigabytes in all.
Four times
So the model with eight billion weights needs... a hundred and twenty-eight gigabytes to train. That's four times the thirty-two it takes to use, before a single word goes in.
The values kept for the way back
What else fills it?
The forward pass saves the values it needs for the way back.
Take GPT-2 small, reading texts of a thousand and twenty-four tokens. Tokens are the pieces of words it reads. For each text, the kept values take almost three gigabytes. A batch of one text: almost three. A batch of four keeps about eleven and a half.
Add the two gigabytes from before, and a little room to work: almost fifteen at its peak. The two gigabytes for the weights stay the same. The kept values grow with the batch. Does a batch of eight fit in sixteen gigabytes?
No. PyTorch stops: out of memory.
So when a run doesn't fit, make the batch smaller.
bf16
A model stores each number in four bytes, and training holds sixteen bytes a weight. So can smaller numbers help?
bf16 stores a number in two bytes instead of four. It can hold numbers just as big. But it's less exact. In bf16, pi is only right to three point one four.
So a model you only use takes half the memory in bf16. The model with eight billion weights: sixteen gigabytes, instead of thirty-two.
Mixed precision keeps the sixteen bytes
Now train in mixed precision: the work is done in bf16, and some numbers stay in four bytes. That's why it's called mixed. Is the memory cut in half too?
No. Every weight, its slope and Adam's numbers stay in four bytes. At a batch of four, the kept values drop by only one gigabyte. Mixed precision can speed up the work.
NVIDIA's T4 uses a different two-byte format called fp16. Its rated peak is about eight times as high in mixed precision as it is with four-byte numbers. On this Mac, we measured a training step on two long texts. With bf16 mixed precision, that step took longer.
Which hardware?
So, add it up. The digits network: any laptop's CPU. GPT-2 small: a free GPU with sixteen gigabytes, and a batch of four.
The model with eight billion weights: to use it, one card with twenty-four gigabytes, in bf16. To train all its weights, a hundred and twenty-eight gigabytes before you count the batch.
You could split the work across several GPUs with eighty gigabytes each, rented by the hour.
Save as you go
A long training run will stop. A free GPU's session lasts twelve hours at most, and a rented one is paid by the hour.
So, every epoch, save three things in one file. The weights. The optimizer's numbers: for Adam, its two numbers for every weight. And the epoch, so it knows where to start again. That file is a checkpoint. Take the digits network. Stop it after epoch fifteen, load it, and keep training. It ends at about ninety-five percent. At every epoch, it's the same as the run that never stopped.
The weights alone
Now spot what's missing in this one.
It only saved the weights. So Adam starts its two numbers over, from zero, and it's a different run.
This time it happened to end a little higher. Another time it could end lower. Either way, it isn't the run you stopped, and you can't repeat it.
Its file was a third the size: Adam's numbers were most of it.
In code
In code: the device line, then the model, moved once. In the loop, each batch moves too. Mixed precision takes one line, around the forward pass and the loss. After every epoch, torch dot save writes one dictionary: the weights, the optimizer, and the epoch.
To keep going, load both, and start from the next epoch.
On this Mac, it prints mps, and the same score as before.
Three ideas
So: sixteen bytes a weight, plus what the batch keeps. bf16, to use a model in half the memory.
And a checkpoint that saves the weights, the optimizer and the epoch.
Far more memory
Training needs far more memory than using a model. Now try it on this lesson's page, and take the quiz. Find the biggest batch that fits on a free GPU.
You use this lesson in Lab 4: A training run that checks itself, after Warmup and learning-rate schedules.
Facts last checked on .
