Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Measuring and Reducing Peak Memory Usage in PyTorch

Recommended resources

Introduction

In our previous lesson, we established the fundamental distinction between allocated and reserved memory in PyTorch, using torch.cuda.memory_summary() to get a detailed snapshot of the caching allocator's state. This provided a static view of memory usage at a single point in time.

Now, we will shift our focus to a more dynamic and crucial metric: peak memory usage. Understanding the maximum memory your code consumes during execution is essential for preventing OutOfMemoryError (OOM) and for optimizing your models. In this lesson, you will learn how to measure the peak memory allocated by a specific block of code using torch.cuda.max_memory_allocated(). We will then explore how to actively reduce this peak during inference using context managers like torch.no_grad(), a foundational technique for efficient model deployment.


Measuring the High-Water Mark: Peak Allocated Memory

While torch.cuda.memory_allocated() tells you how much memory is in use right now, it doesn't capture the fluctuations that happen within a training or inference step. During a forward pass, for example, memory usage spikes as PyTorch stores intermediate activations. These are then often freed during the backward pass. The most critical number for avoiding OOM errors is the highest point this usage reaches.

PyTorch provides a simple way to track this "high-water mark."

PyTorch Memory Tuning | paulbridger.com

This article from paulbridger.com introduces the concept of breaking down memory consumption and the primary tool for measuring its peak.

Please read the introduction, starting from the beginning down to where the author introduces the primary function for this task. Focus on the four components of memory consumption and the introduction of torch.cuda.max_memory_allocated().

As the article notes, torch.cuda.max_memory_allocated() gives you the peak memory that has been allocated since the beginning of your program's execution. However, for effective profiling, you usually want to measure the peak memory for a specific operation, like a single forward pass. To do this, you need to reset the tracker before you run your code. The pattern is:

  1. torch.cuda.reset_peak_memory_stats(): Resets the peak memory counter to the current allocated memory.
  2. Run the code block you want to measure.
  3. torch.cuda.max_memory_allocated(): Get the peak memory usage recorded during the execution of your code block.

This reset-execute-measure pattern is fundamental to targeted memory profiling.


Reducing Peak Memory During Inference

Now that we can measure peak memory, how do we reduce it? One of the most significant and straightforward ways to save memory is by telling PyTorch when it doesn't need to prepare for a backward pass. This is always the case during inference.

When you run a model normally, PyTorch builds a computation graph and saves the intermediate activations (the outputs of each layer). It needs these activations to calculate gradients during backpropagation. This is essential for training but pure overhead for inference.

PyTorch provides context managers to disable this behavior. The two main ones are torch.no_grad() and torch.inference_mode().

PyTorch Memory Tuning | paulbridger.com

Let's return to the same article to see a practical explanation of how to use these context managers.

Read the section Don’t Forget Inference-Mode. It clearly explains why these context managers save memory and provides a simple code snippet.

Both torch.no_grad() and the newer torch.inference_mode() prevent the allocation of memory for the computation graph and intermediate activations. torch.inference_mode() is slightly more performant as it provides stronger guarantees to the PyTorch dispatcher that no autograd-related work will be needed, but for memory-saving purposes, they achieve the same primary goal.

Let's see a benchmark of this in action.

Inference in PyTorch, what do the wrappers mean? What’s best? – Zach Mueller

This blog post by Zach Mueller provides an excellent, pragmatic benchmark comparing inference with and without these context managers. It also showcases the reset-execute-measure pattern we just discussed.

First, read the section defining the modes to understand the conceptual difference between no_grad and inference_mode. Next, look at the "Making a Baseline" section. Pay close attention to the benchmark_modes function. Notice how it uses this exact pattern to measure the peak memory for each inference call. Finally, review the table in the Examining the Results section and the author's note on memory reduction. See how applying either context manager dramatically cuts memory usage.

The results are clear: simply wrapping your inference code in with torch.no_grad(): or with torch.inference_mode(): can reduce peak memory usage by a factor of 3 or more for a standard ResNet model. This is because you're no longer storing the activations from the forward pass.

This principle is visually summarized in the image below, which contrasts various memory-saving techniques. While some techniques like Gradient Accumulation apply to training, the context managers we've discussed are a key part of optimizing for a single GPU scenario, especially for inference.

This chart illustrates several memory reduction techniques. On the right, for a single GPU, moving from "Full Precision" to techniques that reduce memory shows significant gains. Disabling gradient tracking, as we've done with context managers, is a primary way to reduce the memory footprint of activations.

Memory Leaks from Un-released References

It's important to understand that torch.no_grad() only prevents the memory usage associated with the autograd engine. It does not manage memory for the tensors themselves. If you hold a reference to a tensor in your Python code, its memory will not be freed, regardless of context.

Your CS background in memory management and reference counting is directly applicable here. As long as a Python variable points to a tensor object, PyTorch's caching allocator cannot reclaim its memory because the reference count is greater than zero. If you accidentally accumulate tensors in a list or another data structure without ever clearing it, you will create a memory leak.

Consider this common mistake during a training loop:

losses = []
for batch in dataloader:



    # ... forward pass ...
    loss = loss_fn(outputs, targets)
    



    # Mistake: The 'loss' tensor, which is part of the computation graph,
    # is appended. This keeps the entire graph for that step in memory.
    losses.append(loss) 
    
    loss.backward()



    # ...

In the code above, the losses list holds onto every loss tensor from every step. Because each loss tensor is the endpoint of a computation graph, this prevents the memory for that graph (including all its activations) from being freed.

The correct way is to store only the scalar value:

losses.append(loss.item()) # .item() gets the scalar value, breaking the graph connection.

This might seem like a small detail, but it's a very common source of OOM errors.

7 PyTorch Tips You Should Know

This video from Edan Meyer provides a clear, practical demonstration of this exact issue.

Watch the segment from item number five, where the presenter explains and demonstrates why you should use .detach() or .item() when logging metrics to prevent memory leaks.


Conclusion

In this lesson, we transitioned from static memory snapshots to measuring and controlling the dynamic peak memory usage of your code. This is a critical skill for writing efficient and robust PyTorch programs.

The key takeaways are:

  • Peak memory is the crucial metric for avoiding OOM errors, as it represents the highest memory demand during an operation.
  • You can measure the peak memory of a code block using the torch.cuda.reset_peak_memory_stats() and torch.cuda.max_memory_allocated() pattern.
  • For inference, using the torch.no_grad() or torch.inference_mode() context managers is essential. They prevent the storage of intermediate activations, dramatically reducing peak memory consumption.
  • Holding onto tensor references in Python, such as appending loss tensors to a list, will prevent memory from being freed and is a common cause of memory leaks.

In our next lesson, we will dive deeper into diagnosing OutOfMemoryError conditions. We'll explore how large batch sizes and these very same un-released tensor references are often the culprits, and we'll prepare to use more advanced tools to debug these issues when they arise.