Skip to main content

Welcome to a Grasp lesson

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

Lesson 7

Saving Memory Snapshots on OOM Errors

Recommended resources

Introduction

In our last lesson, we explored the PyTorch Profiler's Operator View, which provided a powerful way to identify which operations contribute most to memory usage during a successful training run. However, this tool has a significant limitation: it can't help you if your script crashes with an OutOfMemoryError (OOM) before you even finish a single step. For these situations, we need a different strategy—one that allows for "post-mortem" analysis.

This lesson introduces the tools for just that. We will learn how to configure a PyTorch script to automatically capture a detailed memory snapshot at the exact moment an OOM error occurs. This snapshot contains a complete record of every memory allocation, which we can then analyze offline. By the end of this session, you will be able to instrument your code to save this crucial debugging information, setting the stage for visualizing and pinpointing the root cause of memory failures.


What is a Memory Snapshot?

Before we can capture a snapshot, let's clarify what it is. A memory snapshot is a data structure that records the state of the PyTorch CUDA caching allocator at a specific point in time. When enabled, it logs every memory allocation and deallocation event, and crucially, it records the Python and C++ stack trace for each event. This allows you to trace a block of memory not just to an operation type (like convolution), but to the exact line of code that requested it.

The primary API for this feature is torch.cuda.memory._record_memory_history(). Enabling this tells PyTorch to start collecting this detailed event log.

The following short clip from a PyTorch talk provides a high-level overview of this API.

Lightning Talk: Profiling and Memory Debugging Tools for Distributed ML Workloads on GPUs- Aaron Shi

This video from the official PyTorch channel introduces the memory snapshotting tools.

Watch the segment from the first tool, where the speaker outlines the basic usage of _record_memory_history to collect allocation events and _dump_snapshot to save the file.


The Challenge: Capturing the Moment of Failure

The most critical moment to understand memory usage is often right before an OOM error. A naive approach might be to wrap your training loop in a try...except OutOfMemoryError block and then try to save a snapshot in the except clause. However, by the time the exception is caught, the program stack has already unwound, and some of the crucial context about the allocation that failed might be lost.

We need a way to hook directly into the memory allocator's failure process. PyTorch provides an "OOM observer" for this exact purpose. This is a callback function that you can register with the allocator. When the allocator is about to raise an OutOfMemoryError, it will execute your callback function first. This gives us the perfect opportunity to save a snapshot of the memory state precisely at the point of failure.


The Solution: The OOM Observer

To implement this, we'll use an internal function, torch._C._cuda_attach_out_of_memory_observer(). While its name suggests it's a private API, it's the standard, accepted way to perform this kind of post-mortem debugging.

The process involves two main steps:

  1. Define an observer function: This function will be called by the allocator on OOM. Its job is to generate and save the memory snapshot.
  2. Register the observer: Pass this function to _cuda_attach_out_of_memory_observer().

The following excerpt from a blog post by Zachary DeVito, one of the PyTorch developers who created this tool, provides the canonical implementation.

Debugging PyTorch memory use with snapshots | Zach’s Blog

This section explains exactly how to register a callback that saves a memory snapshot when an OOM error is triggered.

Read the section titled Generating Snapshots when Out of Memory. Pay close attention to the oom_observer function. It takes arguments from the allocator (device, alloc, etc.), but for our purposes, its main job is to call torch.cuda.memory._snapshot() and save the result.

As the reading shows, the implementation is surprisingly concise. You define a function that takes a few arguments (which you can ignore for now) and inside it, you get the snapshot and save it to a file. The pickle module from Python's standard library is used for this serialization.


A Complete Workflow for Post-Mortem Debugging

Let's combine these concepts into a complete, runnable example. Our goal is to create a script that intentionally runs out of memory and, in doing so, automatically generates an oom_snapshot.pickle file.

Here is the full sequence of operations:

  1. Import necessary modules: torch, pickle.
  2. Define the oom_observer function: This function will create and save the snapshot file.
  3. Enable memory history recording: Call torch.cuda.memory._record_memory_history(). It's important to do this before any allocations you want to track.
  4. Register the OOM observer: Call torch._C._cuda_attach_out_of_memory_observer(oom_observer).
  5. Trigger the OOM: Intentionally allocate tensors in a loop until memory is exhausted.

Here is a code snippet you can run in a Colab notebook with a GPU runtime.

import torch
from pickle import dump




# 1. Define the OOM observer function
def oom_observer(device, alloc, device_alloc, device_free):
    print(f"OOM detected on device {device}!")
    print(f"Saving snapshot to oom_snapshot.pickle...")
    



    # Get the snapshot and save it to a file
    snapshot = torch.cuda.memory._snapshot()
    with open("oom_snapshot.pickle", "wb") as f:
        dump(snapshot, f)




# Make sure you have a GPU
if not torch.cuda.is_available():
    print("This script requires a GPU.")
else:



    # 2. Enable memory history recording
    torch.cuda.memory._record_memory_history()




    # 3. Register the OOM observer
    # Note: The API is in torch._C, an internal module
    torch._C._cuda_attach_out_of_memory_observer(oom_observer)




    # 4. Trigger an OOM error
    # We will allocate tensors in a list to hold onto their references
    # and prevent memory from being freed.
    allocations = []
    print("Starting allocations to trigger OOM...")
    try:
        while True:



            # Allocate 100MB of memory on the GPU
            allocations.append(torch.empty(100 * 1024 * 1024, dtype=torch.uint8, device='cuda'))
    except torch.cuda.OutOfMemoryError:
        print("Successfully caught OOM error. Check for 'oom_snapshot.pickle'.")



        # The observer should have already saved the snapshot.
        pass
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

After running this code, you will see the "OOM detected!" message, and a file named oom_snapshot.pickle will appear in your working directory. This file contains all the data needed to generate a visualization of the memory state at the point of failure. The resulting plot will look something like the following image, clearly showing memory usage climbing until it hits a ceiling and triggers the OOM.

An active memory timeline generated from a snapshot file, similar to what we'll create in the next lesson. Notice how memory allocations accumulate in a sawtooth pattern, with each drop corresponding to garbage collection, until the final allocation attempt fails, marked as a CUDA OOM event.

Conclusion

In this lesson, we transitioned from profiling successful runs to preparing for failures. You've learned how to equip your script for post-mortem debugging by automatically capturing a memory snapshot at the precise moment of an OutOfMemoryError.

Here are the key takeaways:

  • A memory snapshot is a detailed log of memory events, including allocation stack traces, enabled by torch.cuda.memory._record_memory_history().
  • Relying on a standard try...except block is insufficient for capturing the state during an OOM event.
  • The OOM observer (torch._C._cuda_attach_out_of_memory_observer) is the correct mechanism for this, allowing you to register a callback function that runs just before the OOM error is raised.
  • The typical workflow is to define an observer that saves a snapshot, register it, enable history recording, and then run your code.

We now have our oom_snapshot.pickle file, but it's just a binary data file. In the next lesson, we will complete the post-mortem debugging process by learning how to upload this file to the pytorch.org/memory_viz tool and interpret the resulting visualization to find the exact line of code that caused our program to fail.