Skip to main content

Welcome to a Grasp lesson

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

Lesson 12

Tracking Memory Usage with Custom W&B Metrics

Recommended resources

Introduction

In our previous lesson, we saw how Weights & Biases can automatically monitor your hardware, giving you a continuous view of system-level metrics like overall GPU memory utilization. This is a fantastic way to get a high-level overview of resource consumption. However, this system-level view includes everything the PyTorch process has reserved, including its memory cache, which doesn't always give us the most precise picture of how much memory our tensors are actively using.

This final lesson bridges that gap by combining PyTorch's detailed memory reporting with W&B's powerful experiment tracking. You will learn how to log custom, application-level metrics—specifically the peak tensor memory usage from torch.cuda.max_memory_allocated()—directly to your W&B dashboard. This will enable you to perform precise, quantitative comparisons of memory efficiency across different training runs, completing your toolkit for PyTorch memory analysis.


Custom Metrics: Moving Beyond Automatic Monitoring

The "Process GPU Memory Allocated (%)" chart that W&B automatically generates is derived from NVIDIA's drivers, similar to the output of nvidia-smi. It tells you the total memory footprint of your Python process on the GPU. As we learned in the first module, this includes both the memory actively holding tensor data and the larger pool of cached memory that PyTorch reserves for future allocations.

For optimizing your model, you're often most interested in the peak memory actively used by tensors. This is the metric that is directly influenced by your batch size, model architecture, and operations like gradient computation. Logging this specific value allows for much cleaner and more direct comparisons.

To do this, we'll use the wandb.log() function, which you've already seen used for logging training loss. Instead of just logging loss, we will add our own custom key for peak memory.

Logging metrics & gradients to W&B with PyTorch

This short video clip provides a clear explanation of the wandb.log() function. It's a great refresher on how to send custom data to your W&B dashboard.

Watch the segment from the beginning until the explanation of wandb.log. The key concept is that wandb.log() accepts a dictionary, allowing you to log any key-value pairs you want to track. We will simply add our memory metric to this dictionary.

The process is straightforward:

  1. At a chosen point in our script, we will call a PyTorch function to get a memory statistic.
  2. We will place this value into a dictionary with a descriptive key, like {"peak_gpu_memory_MB": ...}.
  3. We will pass this dictionary to wandb.log().

A Practical Example: Comparing Batch Sizes

Let's modify the training script from our last lesson to track the peak memory usage per epoch. We'll add logic to query torch.cuda.max_memory_allocated() and log it to W&B. This function, which you used in the first module, reports the peak of torch.cuda.memory_allocated() since the last time the peak statistics were reset.

To get a meaningful per-epoch peak, we must call torch.cuda.reset_peak_memory_stats() at the start of each epoch. Then, at the end of the epoch, we can read the peak value that was reached during that epoch's training steps.

Here is the complete script. Notice the new lines in the training loop:

# Step 1: Install and log in to W&B
!pip install wandb -q
import wandb
wandb.login()

# Step 2: Import PyTorch and other libraries
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from tqdm.auto import tqdm

# Step 3: Define hyperparameters and W&B configuration
# TRY CHANGING THIS and re-running to see the effect on memory!
BATCH_SIZE = 128 

config = {
    "learning_rate": 0.001,
    "batch_size": BATCH_SIZE,
    "epochs": 3,
    "architecture": "SimpleCNN"
}

# Step 4: Start the W&B run
# We give the run a name to easily identify it later.
with wandb.init(project="pytorch-memory-course-custom-metrics", config=config, name=f"batch_size_{BATCH_SIZE}") as run:
    # Make config accessible to the script
    config = run.config
    device = "cuda" if torch.cuda.is_available() else "cpu"

    # Step 5: Setup data, model, optimizer, and loss function
    transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])
    trainset = torchvision.datasets.FashionMNIST(root='./data', train=True, download=True, transform=transform)
    trainloader = torch.utils.data.DataLoader(trainset, batch_size=config.batch_size, shuffle=True, num_workers=2)

    model = nn.Sequential(
        nn.Conv2d(1, 16, 3, 1, padding=1), nn.ReLU(), nn.MaxPool2d(2),
        nn.Conv2d(16, 32, 3, 1, padding=1), nn.ReLU(), nn.MaxPool2d(2),
        nn.Flatten(),
        nn.Linear(32 * 7 * 7, 10)
    ).to(device)

    criterion = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=config.learning_rate)

    # Step 6: The training loop with custom metric logging
    model.train()
    for epoch in range(config.epochs):
        # ---> RESET PEAK MEMORY STATS AT THE START OF THE EPOCH <---
        if device == "cuda":
            torch.cuda.reset_peak_memory_stats()

        for i, (images, labels) in enumerate(tqdm(trainloader, desc=f"Epoch {epoch+1}")):
            images, labels = images.to(device), labels.to(device)

            optimizer.zero_grad()
            outputs = model(images)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

        # --- > LOG CUSTOM METRICS AT THE END OF THE EPOCH <---
        metrics_to_log = {"epoch": epoch, "final_loss": loss.item()}
        
        if device == "cuda":
            # Get peak memory in MB
            peak_memory_mb = torch.cuda.max_memory_allocated() / 1024**2
            metrics_to_log["peak_memory_MB"] = peak_memory_mb
        
        wandb.log(metrics_to_log)

    print("Training finished.")


Exercise: Running and Comparing Experiments

Now, put this into practice.

  1. First Run: Run the script above in your Colab notebook as is (with BATCH_SIZE = 128). Let it complete.
  2. Second Run: Change the BATCH_SIZE variable to 256 (or 512 if your GPU has enough memory) and run the script again.

You have now created two distinct experiments within the same W&B project.


Analyzing the Results in the Dashboard

Navigate to your W&B project page (pytorch-memory-course-custom-metrics). You will see your two runs listed, named batch_size_128 and batch_size_256.

  1. On the project dashboard, you can add a new panel to visualize our custom metric. Click "Add panel" and choose a "Line Plot".
  2. For the Y-axis, select peak_memory_MB. W&B will automatically plot this value for both runs on the same chart, distinguished by color.

Your chart will look something like the one below, clearly showing that one run consistently used more peak memory than the other.

An example comparison from a W&B dashboard. While this plot shows the automatic system metric, your custom `peak_memory_MB` plot will look similar, providing a direct comparison of peak tensor memory usage between your different experimental runs.

An example comparison from a W&B dashboard. While this plot shows the automatic system metric, your custom peak_memory_MB plot will look similar, providing a direct comparison of peak tensor memory usage between your different experimental runs.

By looking at this plot, you can now make a precise, quantitative statement: "Increasing the batch size from 128 to 256 increased the peak tensor memory usage from X MB to Y MB." This is a far more powerful insight for model optimization than simply observing that the overall memory percentage went up.


Conclusion and Course Wrap-up

In this lesson, you've mastered the final piece of the puzzle: combining the detailed, application-level memory statistics from PyTorch with the powerful continuous monitoring and visualization capabilities of Weights & Biases.

Key Takeaways:

  • W&B's automatic system metrics provide a high-level view, while wandb.log() gives you the power to track any custom metric you need.
  • Logging torch.cuda.max_memory_allocated() allows for precise measurement of the peak memory consumed by tensors.
  • Remembering to use torch.cuda.reset_peak_memory_stats() is crucial for measuring peaks within specific code blocks, like an epoch.
  • The W&B dashboard makes it trivial to plot and compare these custom metrics across multiple experiments, turning raw data into actionable insights.

Congratulations on completing this course! You have built a comprehensive and pragmatic toolkit for memory profiling and visualization in PyTorch. You began by learning to inspect memory directly within PyTorch using functions like memory_summary() and max_memory_allocated(). You then progressed to deep, operator-level analysis with the torch.profiler and TensorBoard, and learned how to perform post-mortem debugging of OOM errors using memory_viz. Finally, you integrated system-level monitoring with nvidia-smi and W&B, culminating in the ability to track custom performance metrics across all your experiments.

You are now well-equipped to diagnose, debug, and optimize the memory performance of your PyTorch models, a critical skill for any serious machine learning practitioner.