Introduction
In our last lesson, we learned to measure and manage the high-water mark of memory usage with torch.cuda.max_memory_allocated() and context managers like torch.no_grad(). This gave us the tools to quantify memory consumption. Now, we'll confront the inevitable consequence of exceeding the GPU's limits: the dreaded RuntimeError: CUDA out of memory.
This lesson focuses on diagnostics. When you encounter an OOM error, how do you determine the root cause? We will investigate the two most common culprits: excessive batch sizes that demand too much memory upfront, and subtle memory leaks from un-released tensor references that accumulate over time. Your background in computer science will be valuable here, as we'll touch on concepts like reference counting and garbage collection in the context of GPU memory management. By the end of this lesson, you'll have a systematic approach to identifying why an OOM error occurred.
The Obvious Suspect: Batch Size and Data Loaders
The most frequent cause of an OOM error is simply trying to fit too much data onto the GPU at once. The batch size is the primary lever controlling this. A larger batch size directly increases the memory required for:
- The input tensors themselves.
- The intermediate activations stored during the forward pass (which are directly proportional to the batch size).
- In some cases, the memory used by specific operators that process the batch.
The num_workers parameter in a DataLoader can also contribute to memory pressure, although this is more related to system RAM and the overhead of pre-fetching data. Pushing num_workers too high can sometimes lead to instability or subtle memory issues that compound on the GPU side.
The image below provides a clear, practical example of this relationship. It shows GPU utilization and memory as an experiment varies the batch_size and num_workers.

When you hit an OOM, the very first thing to check is your batch size. Halving it is a common first step to see if the program can run. While this is a simple fix, it's crucial to understand how the batch size affects the memory profile.
Visualize and understand GPU memory in PyTorch
This blog post from Hugging Face provides an excellent analysis of how different components contribute to memory usage during training.
Please read the section titled Estimating Memory Requirements. Pay close attention to the two memory profile graphs. Notice how changing the batch size from 16 to 2 doesn't just lower the memory usage, but actually changes the shape of the memory profile, causing the peak memory to shift from the forward pass to the optimizer step. This illustrates that batch size has a complex effect on the dynamics of memory allocation.
The key takeaway is that the memory peak can occur at different stages of a training step depending on your configuration. A large batch size tends to make activations the dominant memory consumer (peaking during the forward pass), while a smaller batch size might make the optimizer state and gradients the bottleneck.
The Silent Killer: Un-released Tensor References
If reducing the batch size doesn't solve the OOM, or if the error happens after many iterations instead of on the first step, the likely culprit is a memory leak. In Python and PyTorch, this doesn't mean memory is lost forever; it means references to tensors are being held unintentionally, preventing the memory from being reclaimed by PyTorch's caching allocator.
We touched on this in the last lesson with the losses.append(loss) example. Now let's explore two major categories of this problem.
1. Accumulation via Incorrect Gradient Handling
A classic bug is failing to clear gradients properly between training iterations. If optimizer.zero_grad() is missing or misplaced, the gradients from each backward pass will accumulate, causing memory usage to climb with every step until it inevitably overflows.
Using optimizer.zero_grad(set_to_none=True) instead of the default optimizer.zero_grad() is often preferred. The default behavior zeroes out the memory of the grad tensors, while set_to_none=True releases the memory entirely by setting the .grad attributes to None, which can be more memory-efficient.
The PyTorch team has written an excellent blog post demonstrating how to diagnose this exact issue using a memory snapshot.
Understanding GPU Memory 1: Visualizing All Allocations ...
This official PyTorch blog post introduces the memory snapshot tool for post-mortem debugging of OOMs.
Read the section Debugging CUDA OOMs. Look closely at the "ResNet50 with a bug" snapshot. The climbing memory peaks are a tell-tale sign of a leak. The article then shows the code fix—correctly placing optimizer.zero_grad()—and the resulting stable memory profile. This is a perfect visual representation of diagnosing and fixing this common bug.
This pattern of steadily increasing peak memory per iteration is the primary symptom you should look for when suspecting a leak.
2. Reference Cycles and the Garbage Collector
A more subtle cause of memory leaks involves Python's garbage collection and reference cycles. Your CS background gives you a head start here. Python uses reference counting for most object cleanup, which is fast and deterministic. However, it relies on a slower, periodic garbage collector (GC) to find and break "reference cycles" (e.g., object A refers to B, and B refers to A).
This becomes a problem on the GPU for two reasons:
- The Python GC is not aware of GPU memory pressure. It won't run a collection cycle just because your GPU is nearly full.
- If tensors are part of a reference cycle, their GPU memory will not be freed until the GC runs and breaks the cycle.
This leads to a characteristic memory usage pattern: memory climbs as tensors are trapped in cycles, then drops suddenly when the GC eventually runs. If the memory required by these trapped tensors exceeds the GPU's capacity before the GC kicks in, you get an OOM error.

The following video explains this phenomenon and demonstrates how a simple reference cycle in code can lead to a massive GPU memory leak.
Lightning Talk: Profiling and Memory Debugging Tools for Distributed ML Workloads on GPUs- Aaron Shi
This PyTorch talk provides a great overview of memory debugging tools. We'll focus on the sections that diagnose our two types of leaks.
First, watch the segment from model with a bug. This reinforces the visual diagnosis of the un-cleared gradients problem we just read about. Next, watch from simple memory leak. The speaker provides an excellent explanation of why reference cycles are problematic for GPU memory and shows code that creates a cycle, leading directly to the sawtooth pattern and an OOM.
The key insight is that while your code might look correct from a logic perspective, the way objects refer to each other can have profound implications for GPU memory stability. Avoiding reference cycles involving tensors is a best practice for writing robust PyTorch code.
A First Step Towards Post-Mortem Debugging
When an OOM strikes, the error message itself gives little information about the context of the failure. To get that context, you need a "snapshot" of memory at the time of the crash. PyTorch provides a low-level API for this purpose, which we will use extensively in the next module. For now, let's see how to set it up.
The process involves telling PyTorch to start recording all memory events (allocations and deallocations) and then, in case of an error, dumping that history to a file.
import torch
# Enable memory history recording
torch.cuda.memory._record_memory_history(max_entries=100000)
try:
# Your training loop and model code here...
# for batch in dataloader:
# ...
pass
except Exception as e:
print(f"An error occurred: {e}")
# Dump the memory snapshot to a file upon error
torch.cuda.memory._dump_snapshot("oom_snapshot.pkl")
finally:
# Stop recording
torch.cuda.memory._record_memory_history(enabled=None)
This try...except block is a powerful pattern for OOM diagnosis. By wrapping your training code, you can ensure that if a CUDA out of memory error occurs, a oom_snapshot.pkl file is saved. This file contains a detailed timeline of every memory allocation leading up to the crash.
Conclusion
In this lesson, we established a diagnostic framework for one of the most common problems in deep learning: OutOfMemoryError. We've seen that the cause typically falls into one of two categories: requesting too much memory at once, or failing to release memory that is no longer needed.
Here are the key takeaways:
- Start with Batch Size: The simplest and most common cause of OOM is a batch size that is too large for your GPU. Always check this first.
- Look for Leaks: If the OOM occurs after several iterations, suspect a memory leak. The main symptoms are a steadily climbing memory peak (incorrect gradient clearing) or a sawtooth pattern (reference cycles).
- Audit Your Loop: The most common leaks come from appending tensors with computation history to lists (instead of using
.item()) and failing to calloptimizer.zero_grad(set_to_none=True)at the correct place in your training loop. - Prepare for Post-Mortem: You can instrument your code with
torch.cuda.memory._record_memory_history()to save a detailed memory snapshot when an OOM occurs, enabling deeper analysis.
So far, our diagnostic tools have been relatively high-level. We've identified patterns and common code smells. In the next lesson, we will begin our dive into more powerful tooling by exploring the PyTorch Profiler. We will learn how to configure it to generate a detailed trace with memory information, which can then be visualized in TensorBoard for a fine-grained, operator-by-operator view of your model's memory consumption.