Introduction
In our previous lesson, we developed a high-level diagnostic approach for OutOfMemoryErrors, focusing on common culprits like oversized batches and memory leaks from lingering tensor references. This gave us a way to react to problems after they occur. Now, we'll shift from reactive diagnosis to proactive, fine-grained analysis.
This lesson introduces the torch.profiler, a powerful, built-in tool for creating a detailed timeline of your model's execution. Our focus will be on learning how to configure the profiler to not only track operator execution times but also to record every memory allocation and deallocation. By the end of this lesson, you will be able to generate a memory trace and export it for visualization in TensorBoard, setting the stage for in-depth performance and memory optimization.
From High-Level Metrics to Detailed Traces
The tools we've used so far, like torch.cuda.max_memory_allocated(), provide a single number—the high-water mark. While useful, this doesn't tell us when or why that peak occurred. The PyTorch Profiler fills this gap by recording a chronological sequence of events, offering a much richer dataset for analysis.
Using the PyTorch Profiler for Bottleneck Analysis
This article provides a concise overview of what the PyTorch Profiler measures.
Please read the introductory section, What the Profiler Measures. As you read, note the different types of events it can track, especially the optional Memory Usage, which is our primary focus for this module.
As the article highlights, the profiler can capture a wide range of activities, from CPU/GPU operator times to the Python call stacks that trigger them. The key for us is that it can be configured to add memory allocation and deallocation events to this timeline.
Configuring the Profiler for Memory Analysis
The standard way to use the profiler is through a Python context manager, torch.profiler.profile. You wrap this around the segment of code you wish to analyze. The power of the profiler comes from the arguments you pass to this context manager, which allow you to specify exactly what to record and where to save the results.
Let's break down the essential parameters for generating a memory trace for TensorBoard.
PyTorch Profiler With TensorBoard
The official PyTorch documentation provides the definitive guide to using the profiler. We'll focus on the setup and configuration section.
Please read the section Use profiler to record execution events. Pay close attention to the explanations for the schedule, on_trace_ready, and profile_memory parameters, as these are fundamental to our goal.
Based on that reading, here are the crucial arguments to configure:
activities: This tells the profiler which domains to monitor. For a complete picture of a GPU-bound workload, you should always include bothtorch.profiler.ProfilerActivity.CPUandtorch.profiler.ProfilerActivity.CUDA.schedule: Profiling has overhead, especially during initialization. Thescheduleparameter lets you ignore the initial, unrepresentative steps and focus on the "steady state" of your training loop. A common setup istorch.profiler.schedule(wait=1, warmup=1, active=3, repeat=1), which tells the profiler to:wait: Ignore the first step.warmup: Run the profiler for one step but discard the results to warm up caches.active: Record the next three steps.repeat: Perform this cycle once.
on_trace_ready: This is a callback function that handles the recorded trace data. To create files for TensorBoard, we usetorch.profiler.tensorboard_trace_handler(log_dir), wherelog_diris the directory where you want to save the trace files.profile_memory: This is the critical switch. You must setprofile_memory=Trueto instruct the profiler to record tensor memory allocations and deallocations. Without this, the memory-specific views in TensorBoard will be empty.with_stackandrecord_shapes: These optional arguments add more context.with_stack=Truerecords the Python call stack for each operation, helping you trace an event back to a specific line in your code.record_shapes=Truerecords the input shapes of operators. Both are incredibly useful for debugging but add significant overhead, so you may want to disable them for routine profiling.
Here is a complete code snippet demonstrating how to put this all together around a simple model inference loop. Notice the prof.step() call at the end of the loop, which is essential for signaling to the profiler that an iteration is complete, allowing the schedule to work correctly.
import torch
import torchvision.models as models
from torch.profiler import profile, schedule, tensorboard_trace_handler, ProfilerActivity
# Ensure you have a GPU available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# 1. Setup model and inputs
model = models.resnet18().to(device)
inputs = torch.randn(32, 3, 224, 224).to(device)
log_dir = "./logs/resnet18_memory"
# 2. Define the schedule
# Skips the first 2 steps, warms up for 1, records the next 3.
my_schedule = schedule(wait=2, warmup=1, active=3, repeat=1)
# 3. Use the profiler context manager with memory profiling enabled
with profile(
activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
schedule=my_schedule,
on_trace_ready=tensorboard_trace_handler(log_dir),
profile_memory=True, # This is the key to enable memory tracking
record_shapes=True, # Optional: adds shape info
with_stack=True # Optional: adds source code attribution
) as prof:
# A dummy loop of 10 steps
for step in range(10):
# Your model's forward pass, backward pass, optimizer step, etc. would go here
model(inputs)
# Signal the profiler that a step is complete
prof.step()
print(f"Profiler trace saved to {log_dir}. Run: tensorboard --logdir={log_dir}")
Launching TensorBoard and Finding the Memory View
After running the script above, a directory named ./logs/resnet18_memory will be created. It contains the trace files that TensorBoard reads. To launch the visualizer, run the following command in your terminal:
tensorboard --logdir=./logs
This will start a web server. Open the provided URL in your browser (Chrome or Edge are recommended). You will see the "PyTorch Profiler" plugin page.

This is the overview page for the PyTorch Profiler in TensorBoard. It provides a high-level summary of performance, including GPU utilization and a breakdown of time spent in each step.
This overview is a great starting point, but our goal is to inspect memory usage. On the left-hand side, you'll see a "Views" dropdown. Because we ran the profiler with profile_memory=True, this dropdown will contain an option for "Memory". Selecting it will take you to the memory-specific analysis view.

This is the TensorBoard Memory View, which is generated when profile_memory=True. It shows the allocated vs. reserved memory over time, a table of memory events, and aggregated statistics per operator.
This view is where we will spend most of our time in the next lesson. For now, the key achievement is generating it successfully. It provides three main components:
- Memory Curve: The graph at the top shows the amount of
AllocatedandReservedmemory on the device over time. - Memory Events Table: A detailed log of every allocation and deallocation event, linked to the operator that caused it.
- Memory Statistics Table: An aggregated view showing the total memory allocated by each operator type.
A quick note: The official PyTorch documentation mentions that the TensorBoard integration is being deprecated in favor of other trace viewers like Perfetto or chrome://tracing. While those are powerful tools, the TensorBoard plugin is still highly functional, widely used, and an excellent, integrated environment to start with.
Lecture 16: On Hands Profiling
This hands-on profiling lecture gives a great walkthrough of the profiler's output. While it focuses on the Chrome trace viewer, the concepts are identical to what you see in TensorBoard's trace view.
Watch the segment from chrome trace to see how a raw trace looks. The speaker points out the timeline on the x-axis, the CPU and GPU streams, and the regular, repeating structure of a model in its "steady state"—this is exactly what using a schedule helps us capture.
Conclusion
In this lesson, we made the leap from simple memory counters to a full-fledged profiling workflow. You now have the ability to generate detailed execution traces that include a complete record of memory activity.
Here are the key takeaways:
- The
torch.profiler.profilecontext manager is the primary tool for in-depth performance analysis in PyTorch. - To capture memory information, it is essential to set the
profile_memory=Trueargument. - Using a
scheduleis a best practice to ensure you are profiling the steady-state behavior of your model, free from initialization artifacts. - The
tensorboard_trace_handlerprovides a seamless way to export profiler data into a format that can be visualized and analyzed with TensorBoard.
We have successfully configured the profiler and generated our first memory trace. In our next lesson, we will put this trace to use. We will learn how to analyze the TensorBoard memory view to identify the exact point of peak memory usage and drill down into the operator tables to pinpoint which parts of our model are the most memory-intensive.