Introduction
Welcome to the fourth and final module of our course. In the previous module, we delved into post-mortem debugging, learning how to take a memory snapshot upon an OutOfMemoryError and use the pytorch.org/memory_viz tool to trace the error back to its source code. This is an invaluable skill for fixing crashes after they happen.
Now, we will shift our focus from after-the-fact analysis to proactive, real-time monitoring. This lesson introduces the foundational tool for system-level GPU inspection: nvidia-smi. By the end of this session, you will be able to use this command-line utility to get a direct, device-level view of your GPU's status and, crucially, understand why the memory usage it reports often differs from the numbers provided by PyTorch's own functions like torch.cuda.memory_allocated().
Your Window into the GPU: nvidia-smi
The NVIDIA System Management Interface, or nvidia-smi, is a command-line utility that ships with the NVIDIA drivers. It provides monitoring and management capabilities for your GPU devices, offering a real-time look at what the hardware is actually doing, independent of any specific application like PyTorch. It is the ground truth for device status.
The following video gives a great overview of what nvidia-smi is and how to use its most common commands.
How To Monitor and Manage GPUs with Nvidia-smi Command
This video from Liv4IT introduces nvidia-smi and walks through its main features.
First, watch the brief introduction to understand the tool's purpose from the beginning. Then, jump to the detailed breakdown of the main output table from the default command. Pay close attention to the explanation of the "Memory-Usage" and "GPU-Util" fields. Finally, see how you can run it in a continuous loop from the refresh command, which is useful for live monitoring.
When you run nvidia-smi in your terminal or a Colab cell (!nvidia-smi), you get a detailed report. Let's break down a typical output.
The output is split into two main parts:
-
GPU Status Table: This section provides a per-GPU summary. The most relevant columns for us are:
GPU: The device ID (0, 1, etc.), which corresponds tocuda:0,cuda:1.Name: The model of the GPU.Memory-Usage: This shows[Memory Used] / [Total Memory]. This is the total memory consumed on the device as seen by the driver.GPU-Util: The percentage of time the GPU cores were active over the last sample period.
-
Processes Table: This lists every process that currently has a context on the GPU. You'll see the
GPU ID, the process ID (PID), theType(Cfor Compute,Gfor Graphics), and how muchGPU Memory Usagethat specific process is responsible for. In most ML workloads, you'll see one or morepythonprocesses listed here.
The Discrepancy: PyTorch vs. The Driver
Now for the central question. Let's run a simple experiment. In a Colab notebook, execute the following code to allocate a single tensor and print PyTorch's view of memory.
import torch
# Ensure we're on a clean slate
if torch.cuda.is_available():
torch.cuda.empty_cache()
# Allocate a 200MB tensor on the GPU
# 50 million floats * 4 bytes/float = 200,000,000 bytes
tensor = torch.randn(50 * 1000 * 1000, device='cuda')
allocated_mem_mb = torch.cuda.memory_allocated() / 1e6
reserved_mem_mb = torch.cuda.memory_reserved() / 1e6
print(f"PyTorch reported allocated memory: {allocated_mem_mb:.2f} MB")
print(f"PyTorch reported reserved memory: {reserved_mem_mb:.2f} MB")
You should see an output showing that PyTorch has allocated around 200 MB, and reserved a slightly larger amount.
Now, in the very next cell, run !nvidia-smi. Look at the Memory-Usage figure. You will notice it's significantly higher than the 200 MB reported by PyTorch. It might be 500 MB, 800 MB, or even more. Where did all that "extra" memory go?
The discrepancy arises because torch.cuda.memory_allocated() and nvidia-smi are measuring two different things. PyTorch reports on the memory managed by its own caching allocator, while nvidia-smi reports on all memory allocated on the device by any source.
This article provides an excellent explanation for this difference.
Why PyTorch Wastes Your GPU Memory on Purpose (And ... - Medium
The author of this Medium post walks through the exact scenario we just demonstrated and clearly explains the sources of memory overhead that nvidia-smi sees but PyTorch doesn't directly report.
First, read the author's introduction, where they encounter the same puzzling difference between PyTorch's stats and nvidia-smi's output. Next, read the section The Third Number: nvidia-smi. This is the core of the lesson. It details the three main reasons why the nvidia-smi number is always larger.
To summarize the key points from the article, the gap between PyTorch's allocated memory and nvidia-smi's used memory comes from three main sources:
- CUDA Context: The moment you perform any CUDA operation (even just checking
torch.cuda.is_available()), the NVIDIA driver allocates a large block of memory on the GPU for its own use. This context holds kernel code, manages device state, and sets up resources for your program. This can easily consume 300-800 MB of memory before you've even created a single tensor. - Library Workspaces: When PyTorch calls underlying, highly-optimized libraries like cuBLAS (for matrix multiplication) or cuDNN (for convolutions), these libraries may allocate their own temporary "workspace" memory. This happens outside of PyTorch's caching allocator, so PyTorch isn't aware of it, but
nvidia-smisees it. - Other Processes: If any other programs are using the GPU (e.g., a desktop environment, another user's script on a shared server),
nvidia-smiwill report their memory usage as well.
This leads to a clear hierarchy of memory reporting:
\text{nvidia-smi used memory} > \text{torch.cuda.memory_reserved()} \geq \text{torch.cuda.memory_allocated()}A Pragmatic Approach: Querying nvidia-smi from Python
While running !nvidia-smi in a notebook cell is useful for quick checks, in a real-world script you might want to log this information programmatically. You can do this by using Python's subprocess module to execute the command and parse its output.
The following article demonstrates a handy function for this purpose.
Simple GPU memory allocation experiments every ML Engineer should do | by Akhilez | Medium
This article provides a very practical utility function for querying nvidia-smi from within Python.
In the article, find the section Reservation vs Allocation. Focus on the note that begins "Note that torch.cuda.memory_allocated() will return..." and study the get_gpu_memory_used function that follows. It's a clean example of wrapping a command-line tool for use in a Python script.
Here is the function, adapted slightly for clarity:
import subprocess
def get_gpu_memory_from_smi(gpu_id: int = 0) -> int:
"""
Gets the total memory used on a given GPU in bytes using nvidia-smi.
Args:
gpu_id: The ID of the GPU to query.
Returns:
The used memory in bytes.
"""
try:
result = subprocess.run(
[
"nvidia-smi",
"--query-gpu=memory.used",
"--format=csv,nounits,noheader",
f"--id={gpu_id}",
],
capture_output=True,
text=True,
check=True
)
used_memory_mib = int(result.stdout.strip())
return used_memory_mib * 1024 * 1024 # Convert MiB to bytes
except Exception as e:
print(f"Error querying nvidia-smi: {e}")
return -1
# Let's re-run our experiment using this function
if torch.cuda.is_available():
smi_mem_bytes = get_gpu_memory_from_smi()
print(f"nvidia-smi reported used memory: {smi_mem_bytes / 1e6:.2f} MB")
By integrating this function, you can now capture all three key metrics (allocated, reserved, and smi-used) within a single script, giving you a complete picture for logging and analysis.
Conclusion
In this lesson, we moved our view of memory from the application layer (PyTorch) to the device layer (NVIDIA driver). You now have a powerful tool, nvidia-smi, for getting the ground truth on GPU status.
Here are the key takeaways:
nvidia-smiis the command-line utility for real-time monitoring of NVIDIA GPUs, reporting hardware-level statistics like memory usage, utilization, and running processes.- The memory reported by
nvidia-smiis consistently higher than that reported bytorch.cuda.memory_allocated(). - This discrepancy is expected and is caused by overheads invisible to PyTorch's allocator, primarily the CUDA context, library workspaces (cuDNN/cuBLAS), and any other processes using the GPU.
- Understanding the hierarchy
nvidia-smi used > reserved > allocatedis essential for accurate GPU capacity planning and avoiding OOM errors.
You can now confidently interpret reports from both PyTorch and nvidia-smi and explain why they differ. In our next lesson, we will build on this by learning how to use Weights & Biases to automatically and continuously log these system-level metrics throughout a training run, allowing us to track performance over time and across experiments.