Skip to main content

Welcome to a Grasp lesson

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

Lesson 1

Understanding Reserved vs. Allocated GPU Memory in PyTorch

Recommended resources

Introduction

Welcome to your course on PyTorch memory profiling and visualization. Our goal is to move from basic usage to a deep, pragmatic understanding of how to measure, analyze, and optimize memory consumption in your deep learning projects. Given your background in computer science and interest in low-level systems, we will explore not just what tools to use, but why they behave the way they do.

In this first lesson, we'll establish the most fundamental concept in PyTorch memory management: the distinction between allocated and reserved memory. Understanding this is the key to correctly interpreting memory reports and the first step toward diagnosing memory-related issues. We will use torch.cuda.memory_summary() to dissect how PyTorch interacts with the GPU, laying the groundwork for all subsequent profiling techniques.


What Actually Uses GPU Memory?

Before we analyze how PyTorch manages memory, let's briefly review what is being stored. During a typical training loop, GPU memory is consumed by several key components. Understanding this composition is vital because memory usage is not static; it fluctuates significantly during the forward and backward passes.

Complete Guide to GPU Memory Optimization and Mixed Precision ...

This section from a guide by Youngju.dev provides a concise breakdown of the four main consumers of GPU memory during training.

Please read the section titled GPU Memory Composition Analysis. As you read, focus on identifying the four primary components: Model Parameters: The weights and biases. Gradients: Calculated during backpropagation. Optimizer States: Extra data maintained by optimizers like Adam. Activations: Intermediate results from the forward pass, saved for the backward pass.

As you can see, the memory footprint of a model in training is far more than just its parameters. The optimizer states can be surprisingly large (e.g., 12 bytes per parameter for Adam in full precision), and activations are dynamic, growing with batch size and sequence length. This dynamic nature is precisely why PyTorch employs a sophisticated memory management strategy.


The Caching Allocator: Reserved vs. Allocated Memory

When your PyTorch code needs memory for a new tensor on the GPU, it doesn't request it directly from the CUDA driver every single time. Such requests, handled by cudaMalloc(), are computationally expensive as they require synchronization with the GPU.

To avoid this performance penalty, PyTorch uses a caching memory allocator. The logic is simple and efficient:

  1. When you first need GPU memory, PyTorch requests a moderately large block of memory from the GPU driver. This block is now considered reserved.
  2. When you create a tensor, PyTorch carves out a piece from this reserved block. This piece is now considered allocated.
  3. When a tensor goes out of scope and is de-referenced, its memory is not returned to the GPU driver. Instead, it is returned to PyTorch's reserved pool, becoming "free" and available for the next allocation request. This avoids a costly cudaFree() call.

This leads to the core distinction:

  • Allocated Memory: The memory currently occupied by tensors your program is actively using. This is reported by torch.cuda.memory_allocated().
  • Reserved Memory: The total memory pool that the PyTorch caching allocator holds from the GPU. This includes both the allocated memory and the cached, "free" memory waiting to be reused. This is reported by torch.cuda.memory_reserved().

Therefore, you will almost always see that reserved_memory >= allocated_memory.

Let's see this behavior in practice.

Simple GPU memory allocation experiments every ML Engineer should do | by Akhilez | Medium

This article from Medium provides a clear, hands-on experiment to demonstrate the difference between reservation and allocation.

Please read the section Reservation vs Allocation. Pay close attention to the code block and its output, which walks through the lifecycle of a tensor allocation.

Let's analyze the output from that example step-by-step in a Colab notebook (or any environment with PyTorch and a GPU):

  1. Initial State: Both allocated and reserved memory are 0. PyTorch hasn't needed the GPU yet.
  2. x = torch.randn(...): A tensor is created.
    • memory_allocated increases by the size of the tensor (4096 bytes for 1024 floats).
    • memory_reserved increases by a much larger amount (e.g., 2MB). PyTorch requested a whole segment of memory from the GPU to start its cache.
  3. del x: The tensor is deleted.
    • memory_allocated drops to 0. The memory is no longer in use by an active tensor.
    • memory_reserved remains high. The memory was returned to PyTorch's cache, not to the GPU driver. It's now free to be reused by the next tensor you create.
  4. torch.cuda.empty_cache(): This command explicitly tells PyTorch to release any unused cached memory back to the GPU driver.
    • memory_reserved drops back to 0.

This caching mechanism is a classic trade-off: use more memory (by reserving it) to gain speed (by avoiding slow system calls).


A Comprehensive View with torch.cuda.memory_summary()

While calling memory_allocated() and memory_reserved() is useful for quick checks, PyTorch provides a much more powerful tool for a detailed snapshot: torch.cuda.memory_summary(). This function prints a formatted report on the state of the caching allocator.

Complete Guide to GPU Memory Optimization and Mixed Precision ...

We return to the first article to see how memory_summary() presents this information.

Read the section torch.cuda.memory_summary(). Examine the example output table and the interpretation of the key metrics provided.

The output of memory_summary() gives you a clear picture. Let's focus on the most important lines under the Current column:

  • Allocated memory: This is the same value you get from torch.cuda.memory_allocated(). It reflects the memory consumed by all live tensors.
  • GPU reserved memory: This is the same as torch.cuda.memory_reserved(). It represents the total footprint of the PyTorch process on the GPU's memory.

The summary also breaks down memory by block size and status (active vs. inactive), which provides a deeper look into the allocator's internal state. For now, focus on the top-level "Allocated" and "GPU reserved" metrics, as they directly map to the concepts we've discussed.


Visualizing the Memory Lifecycle

These concepts become even clearer when visualized over a training step. The allocated memory (the colored areas in the charts below) fluctuates dramatically, while the reserved memory (the dashed line) acts as a high-water mark.

In this memory profile of a Llama 1B model, the colored stacked chart shows the **allocated** memory, which rises and falls with each training step. The dashed line at the top represents the maximum **reserved** memory, the total pool PyTorch holds from the GPU.

The chart above shows the cyclical pattern of memory allocation. The allocated memory peaks during the forward and backward passes due to activations and gradients, then drops as those temporary tensors are freed.

The next image breaks down the components of the allocated memory at different points in time.

This chart shows a detailed breakdown of the **allocated** memory over several training iterations. You can see how memory usage is composed of parameters (green), activations (red), gradients (blue), and optimizer states (yellow), each contributing to the total at different times.

This visual connects back to our first topic: the components of memory usage. The green "PARAMETER" section is stable, while the red "ACTIVATION" and blue "GRADIENT" sections appear and disappear, causing the fluctuations in total allocated memory.


Conclusion

In this lesson, we've established the foundational concepts of PyTorch GPU memory management. You should now be able to explain the critical difference between allocated and reserved memory and use torch.cuda.memory_summary() to inspect this relationship.

Here are the key takeaways:

  • GPU memory in training is used for more than just model weights; it also holds gradients, optimizer states, and activations.
  • Allocated memory is the portion of GPU memory actively holding tensor data.
  • Reserved memory is the larger pool of memory that PyTorch's caching allocator manages to improve performance by avoiding frequent, slow calls to the GPU driver.
  • torch.cuda.memory_summary() is your primary tool for getting a detailed report on the state of the caching allocator.

In our next lesson, we will build directly on this foundation. We'll move from inspecting memory at a single point in time to measuring the peak memory usage of a specific block of code using functions like torch.cuda.max_memory_allocated() and context managers, which is essential for pinpointing which parts of your model are the most memory-intensive.