How to Fix Python CUDA Memory Errors in PyTorch
How to fix 'CUDA out of memory' in PyTorch, on a real Google Colab T4: why lowering the batch size alone can still fail in a notebook (the crashed run keeps its memory until you restart), what fills GPU memory during training (for ResNet-50 at batch 64: weights 91 MiB, gradients 90 MiB, Adam 187 MiB, activations 5.1 GiB), why a validation loop without torch.no_grad() runs out of memory, and three ways to keep a big batch: mixed precision, gradient accumulation and activation checkpointing, each measured.
Out of memory
You run a PyTorch training cell on a GPU, and it stops: CUDA out of memory.

It asked for three hundred and ninety-two more megabytes, and fewer than four were free. The usual fix, a smaller batch, crashes too, for a reason most people miss.
OutOfMemoryError: CUDA out of memory. Tried to allocate 392.00 MiB. GPU 0 has a total capacity of 14.56 GiB of which 3.75 MiB is free. Including non-PyTorch memory, this process has 14.56 GiB memory in use. Of the allocated memory 14.01 GiB is allocated by PyTorch, and 433.26 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://docs.pytorch.org/docs/stable/notes/cuda.html #optimizing-memory-usage-with-pytorch-cuda-alloc-conf)
Which memory ran out
First, which memory ran out? A graphics card has its own memory, separate from the computer's. CUDA is NVIDIA's way for PyTorch to use it.

Everything the model touches while training must fit on the card. The data, here photos, waits in the computer's memory and goes over a few at a time: a batch.

The usual fix
This run is Mary's, on Google Colab, which lends her a graphics card with fifteen gigabytes. She's teaching a model to sort her rose society's flower photos, and the show is Saturday. If it isn't ready, Jim, who runs the show, sorts eight thousand by hand. And Jim has one more wish: sharper photos, almost three times the pixels, on this same card.

The usual fix: a smaller batch, the photos the model studies in one step. Mary drops it from two hundred fifty-six to sixty-four.

Run the cell again. Out of memory, again. Read the numbers this time. It asked for just two megabytes, and fewer than two were free. PyTorch itself holds fourteen gigabytes, and nothing is even training. So something is still holding on to it.
OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 MiB. GPU 0 has a total capacity of 14.56 GiB of which 1.75 MiB is free. Including non-PyTorch memory, this process has 14.56 GiB memory in use. Of the allocated memory 14.02 GiB is allocated by PyTorch, and 431.84 MiB is reserved by PyTorch but unallocated. If reserved but unallocated memory is large try setting PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to avoid fragmentation. See documentation for Memory Management (https://docs.pytorch.org/docs/stable/notes/cuda.html #optimizing-memory-usage-with-pytorch-cuda-alloc-conf)
After a crash, Python keeps the last error around, so you can inspect it later. And that error keeps the crashed step's memory with it. NVIDIA's own tool, nvidia-smi, shows the same: fourteen point six gigabytes in use, with nothing running. And the usual cleanup commands won't free it either: PyTorch still counts that memory as in use. This is the step most people miss: after an out-of-memory crash, restart first. In Colab, that's the Runtime menu, then Restart session. Now: zero megabytes in use.
(cell-4) !nvidia-smi --query-gpu=memory.used,memory.total --format=csvmemory.used [MiB], memory.total [MiB] 14909 MiB, 15360 MiB
(cell-1) !nvidia-smi --query-gpu=memory.used,memory.total --format=csvmemory.used [MiB], memory.total [MiB] 0 MiB, 15360 MiB
From a clean start, batch sixty-four trains. One pass over all seven thousand one hundred and sixty-nine photos, called an epoch, takes sixty-six seconds, and memory peaks at five point five gigabytes. The cell's last line measures that peak, so you can see how much room is left.
(cell-3) model = models.resnet50(weights="IMAGENET1K_V2") model.fc = nn.Linear(2048, 102) model = model.cuda() opt = torch.optim.Adam(model.parameters(), lr=1e-4) loader = DataLoader(TensorDataset(photos, labels), batch_size=64, shuffle=True) start = time.time() for x, y in loader: x, y = x.cuda().float(), y.cuda() loss = F.cross_entropy(model(x), y) opt.zero_grad() loss.backward() opt.step() print(f"one epoch: {time.time() - start:.0f} s, " f"peak {torch.cuda.max_memory_allocated() / 2**30:.1f} GiB")
What fills the memory
But why did two hundred fifty-six photos need more than the whole card? The model here is ResNet-50, a common image model. Measure one training step at batch sixty-four, and four things share the card. Three are small, and one is huge. The weights, the numbers the model learns. Gradients, one correction per weight. And Adam, the optimizer that updates them, keeps two notes per weight. Together, those three take three hundred and sixty-eight megabytes. The fourth is the activations, the in-between results the model keeps for each photo, and for sixty-four photos they take five point one gigabytes. They're the problem.
weights 91 MiB activations 5267 MiB (64 photos) gradients 90 MiB Adam's notes 187 MiB
Now measure the whole peak at each batch size. Sixteen photos: one point seven gigabytes. Thirty-two: three. Sixty-four: five point five. And one twenty-eight? Double: ten point six. So two hundred fifty-six would need around twenty-one: more than the card has.

Here's where they come from. Each photo passes through about fifty layers, and every layer's output is kept, because the backward pass needs it. The backward pass is how a model learns. It starts from how wrong the answers were, called the loss. Then it walks back through the layers and uses those kept outputs to work out each weight's correction. Twice the photos, twice the outputs to keep.

Picture a desk. The textbook stays open: the weights. Beside it, corrections, and Adam's two notebooks. And every photo adds scratch sheets, kept until the corrections are worked out: at two hundred fifty-six photos, they bury the desk.
It came back
Training works. But before Saturday, the model has to prove it can sort photos it has never seen. So you add a check, and score it on them. It learns nothing there, and yet memory climbs with every batch: five point five, ten point six, then out of memory, again.
(cell-5) model.eval() val_loss = 0 val = DataLoader(TensorDataset(val_photos, val_labels), batch_size=64) for i, (x, y) in enumerate(val): x, y = x.cuda().float(), y.cuda() val_loss += F.cross_entropy(model(x), y) print(f"batch {i + 1}: {torch.cuda.memory_allocated() / 2**30:.1f} GiB in use")
Here's why. PyTorch doesn't know you won't learn from these photos, so for every batch it keeps the activations, ready for a backward pass. And each loss isn't just a number. It stays linked to every output that made it. The check adds each loss to a running total, so every batch's outputs stay alive. No backward pass ever comes, so nothing is freed. If you've seen model.eval() in other code: it's not the fix here. It changes how a few layers behave, but it doesn't save any memory.

The fix is two small changes. Wrap the check in torch.no_grad(). In desk terms: no scratch sheets, because no corrections will ever be worked out from this. And add.item() to each loss, which turns it into a plain number, with no links back.

Same check, same photos. Now memory stays at zero point one gigabytes, batch after batch, all the way to the end. The fix was never more memory. It was keeping less.
(cell-3) model.eval() val_loss = 0 val = DataLoader(TensorDataset(val_photos, val_labels), batch_size=64) with torch.no_grad(): for i, (x, y) in enumerate(val): x, y = x.cuda().float(), y.cuda() val_loss += F.cross_entropy(model(x), y).item() print(f"batch {i + 1}: {torch.cuda.memory_allocated() / 2**30:.1f} GiB in use")
Sharper photos
Then Jim's request. The judges look at petals up close, so he wants photos three hundred eighty-four pixels wide, not two hundred twenty-four. That's almost three times the pixels, so almost three times the activations. Batch sixty-four: out of memory.
(cell-1) import time, torch, torch.nn as nn, torch.nn.functional as F from torch.utils.data import DataLoader, TensorDataset from torchvision import models from flowers import load_photos, flower_names photos, labels = load_photos(384) val_photos, val_labels = load_photos(384, "val") print(len(photos), "photos to learn from,", len(val_photos), "to check,", len(labels.unique()), "kinds of flower") 7169 photos to learn from, 1020 to check, 102 kinds of flower
Halving the batch again would fit: thirty-two peaks at eight gigabytes, and one pass takes one hundred and ninety-seven seconds. But each halving bases every correction on fewer photos, so learning gets shakier, and a bigger model might not fit even at one photo.
(cell-3) model = train(32)epoch 1: 197 s, peak 8.0 GiB
So keep sixty-four, and give the training function three switches, each tried for one pass over the same sharp photos.

Switch one: mixed precision. PyTorch normally stores each number in four bytes. This switch runs most of the math on two-byte numbers, called half precision, so the activations take about half the room. PyTorch also scales tiny corrections up, so they don't round down to zero. Batch sixty-four now peaks at eight point three gigabytes. Guess: slower, or faster? Faster. This card, a T4, has parts called tensor cores, built for half precision. The pass takes eighty-six seconds, less than half the time of batch thirty-two.
(cell-4) model = train(64, amp=True)epoch 1: 86 s, peak 8.3 GiB
Switch two: gradient accumulation. Run sixteen photos at a time, add up their corrections, and update the weights once every four rounds. That's almost the same update as a batch of sixty-four, but memory only ever holds sixteen photos' activations: four point three gigabytes. The cost: it's no faster than halving the batch, at one hundred and ninety-eight seconds.
(cell-5) model = train(16, accum=4)epoch 1: 198 s, peak 4.3 GiB
Switch three: activation checkpointing. Keep the activations at just a few points along the model, here four, and throw the rest away. Later, when the backward pass needs them, it simply recomputes them. The cost is time. It fits at nine gigabytes, and the pass takes two hundred and fifty-seven seconds, the slowest of all.
(cell-6) model = train(64, ckpt=True)epoch 1: 257 s, peak 9.0 GiB
Side by side, the rule is simple. Short on memory? Try mixed precision first. Still too big? Accumulate. Checkpointing is the last resort, because it costs the most time.

Saturday
For the real run, one switch: mixed precision, batch sixty-four, sharp photos. Each of the three passes takes about eighty-four seconds, and memory never goes past eight point three gigabytes. Then the check, under no_grad: of the one thousand twenty photos it had never seen, it sorted nine hundred and eighty-three correctly, and all ten of the rose photos.
(cell-7) model = train(64, epochs=3, amp=True)
On Saturday, the members' entries go through the model as they arrive, and Jim's pile of photos to sort by hand stays empty.

Recap
So, in order: after a crash, restart. When you score the model, wrap it in no_grad. A smaller batch is the quick fix, and to keep your batch: mixed precision, then accumulation, then checkpoints.

If your training runs keep dying at the worst moment, a like helps other beginners find this, and subscribing brings the next fix, measured on a real GPU.
Every command in this video ran on one real Google Colab T4, and the lab files are linked in the description. Thanks for watching Cloud Explainers.
Sources
- He, Zhang, Ren, Sun, Deep Residual Learning for Image Recognition (ResNet; 1st place, ILSVRC 2015 classification)
- torchvision, resnet50 (25,557,032 parameters, 97.8 MB of ImageNet weights)
- PyTorch, CUDA semantics: memory management and PYTORCH_CUDA_ALLOC_CONF
- PyTorch, torch.no_grad
- PyTorch, Automatic Mixed Precision (autocast and GradScaler)
- PyTorch, torch.utils.checkpoint
- PyTorch FAQ, My model reports cuda runtime error(2): out of memory
- NVIDIA T4 Tensor Core GPU (16 GB GDDR6, Turing Tensor Cores)
- Oxford 102 Category Flower Dataset (Nilsback and Zisserman)
- Python, sys.last_traceback (the last uncaught error is kept for debugging)
Demos: one Google Colab T4 runtime; the photos are the Oxford 102 Flowers set; Mary, Jim and their rose society are made up. Every command and output was real. Watch the full video on YouTube.