Skip to main content

Welcome to a Grasp lesson

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

Lesson 6

Profiling Memory Allocation in TensorBoard's Operator View

Recommended resources

Introduction

In our previous lesson, we dove into TensorBoard's Memory View, learning how to analyze the memory timeline to pinpoint when peak memory usage occurs during a training step. This gave us a time-centric perspective, allowing us to isolate a specific moment of high consumption. Now, we will shift our focus from "when" to "what."

This lesson introduces the Operator View in the PyTorch Profiler. Instead of looking at a timeline, we will explore an aggregated summary that shows the total resource consumption—including memory—for every type of operation in your model. By the end of this session, you will be able to use this view to identify which specific PyTorch operators are systematically responsible for the most memory allocations, and, crucially, trace them back to the exact lines in your source code that are calling them.


Shifting Perspectives: From Timeline to Aggregated View

While the Memory View is excellent for spotting anomalous spikes, the Operator View is your tool for understanding the fundamental, recurring costs of your model. It answers questions like, "Overall, what percentage of my memory is allocated by convolution operations versus batch normalization?" or "Which operations create the most temporary tensors?"

When you switch to the "Operator" tab in TensorBoard, you are presented with a different layout: a set of pie charts for a quick visual breakdown and a detailed table below. This table is where we will focus our analysis.

The Operator View in TensorBoard. It provides pie charts for a high-level summary and a detailed table that aggregates performance and memory statistics by operator name across the entire profiling window.

The official PyTorch documentation provides a good overview of this interface.

PyTorch Profiler With TensorBoard

This section of the official tutorial describes the Operator view.

Please read the part describing the Operator view. Pay close attention to the distinction between "Self" duration and "Total" duration. This same concept applies to the memory metrics we will discuss next.


Decoding Memory Metrics in the Operator View

When you run the profiler with memory tracking enabled (profile_memory=True), the Operator View table includes several columns related to memory. The most important ones for our analysis are:

  • Allocation Size (KB): This shows the total gross memory allocated by an operator. It's a useful measure of memory "churn" but doesn't tell you the net impact on your memory footprint.
  • Self Size Increase (KB): This is arguably the most critical metric. It represents the net change in memory (allocations minus deallocations) that is directly attributable to the operator itself, not including any other operators it might call internally.

By sorting the table by "Self Size Increase," you can immediately see which operations are leaving the biggest memory footprint after they complete. For example, a forward-pass aten::convolution will have a positive self-size increase because it creates an activation tensor that persists until the backward pass. In contrast, an in-place operation might have a self-size increase of zero.

The official documentation section on the Memory View provides the formal definitions for these metrics, which are consistent across all profiler views.

PyTorch Profiler With TensorBoard

This reading defines the memory statistics columns that appear in both the Memory View and the Operator View.

Focus on the paragraph in the Memory view section that describes the memory statistics table. Read the definitions for the columns, specifically "Size Increase," "Self Size Increase," and "Allocation Size."


From Operator Name to Source Code

Identifying aten::cudnn_convolution as a top memory consumer is insightful, but not fully actionable until you know which convolution in your model it corresponds to. This is where the profiler's call stack tracking becomes invaluable.

As noted in the documentation, the Operator View allows you to expand an operator to see all the unique call stacks that invoked it. By clicking "View Callstack," you can drill down and see the exact sequence of function calls, from the low-level CUDA kernel launch all the way up to the forward method of your specific nn.Module. Given your background in low-level systems, you can appreciate how this connects the high-level Python code to the underlying execution.

The following video demonstrates this principle of tracing an operation back to its source, albeit in the profiler's raw trace view. The concept of walking up the call stack is identical.

Lecture 16: On Hands Profiling

In this clip from the "On Hands Profiling" lecture, the presenter shows how to select an operation in the profiler's output and trace it back to the line of code that generated it.

Watch the segment from aware of the pytorch runtime. The speaker selects a kernel in the trace and shows how the profiler connects it back through the call stack to the specific module and line in the Python script. This is the same process you will use in the Operator View's call stack feature.


From Analysis to Action: A Practical Walkthrough

Let's synthesize this into a concrete workflow.

  1. Generate a Profile: Run your training script wrapped with torch.profiler.profile, ensuring profile_memory=True and with_stack=True are enabled.
  2. Open Operator View: Launch TensorBoard and navigate to the PyTorch Profiler > Operator view.
  3. Identify Top Consumers: Sort the main table by "Self Size Increase" in descending order. The operators at the top are your primary targets for memory optimization.
  4. Trace to Source: For a top operator (e.g., aten::empty or aten::convolution), click "View Callstack". This will show you which part of your model (e.g., MyBigAttentionLayer) is responsible for these allocations.

Once you have identified the operation and its source, you can decide on an optimization strategy. For instance:

  • If aten::cudnn_convolution is the top consumer, this is expected for a CNN. The next step is not to remove it, but to make it more efficient. You might consider using Automatic Mixed Precision (AMP) to run the convolution with float16, which would halve the size of the resulting activation tensor. This was demonstrated in the "Optimization #6" section of the Towards Data Science article we reviewed previously.
  • If you see aten::copy_ high on the list, it indicates a significant memory cost from data transfers between CPU and GPU. This might prompt you to investigate whether you can reduce the size of the data being copied. For example, as shown in "Optimization #4" of that same article, you could perform normalization and type casting on the GPU after the copy, rather than on the CPU before it, to reduce the payload size of the transfer.

This process transforms the profiler from a passive measurement tool into an active guide for optimization, pointing you directly to the areas where your engineering effort will have the most impact.


Conclusion

In this lesson, we've added the profiler's Operator View to our analysis toolkit. You now have a systematic way to move beyond single-point-in-time analysis and understand the aggregated memory costs of your model's operations.

Here are the key takeaways:

  • The Operator View provides an aggregated summary of performance and memory metrics, grouped by operator name.
  • Sorting by "Self Size Increase" is the most effective way to identify the operations that contribute most to your model's peak memory usage.
  • The "View Callstack" feature is essential for tracing an expensive operator back to the specific line of code in your model that is responsible for it.
  • Identifying a costly operator is the first step; the next is to devise a targeted optimization strategy, such as using AMP for compute-bound operations or optimizing data transfers for copy operations.

So far, we have focused on analyzing traces from successful runs. But what happens when your model fails with an OutOfMemoryError before you can even complete a single profiling step? In our next lesson, we will tackle this exact problem by learning how to perform "post-mortem" debugging using a memory snapshot and the pytorch.org/memory_viz tool.