Introduction
In our last lesson, we explored nvidia-smi, the command-line tool that gives you a real-time, ground-truth snapshot of your GPU's state. While invaluable for quick checks, its output is ephemeral. To understand performance trends, diagnose intermittent issues, or compare resource usage across different training runs, we need a way to record these metrics continuously.
This is where Weights & Biases (W&B) comes in. This lesson will show you how to integrate the W&B platform into your PyTorch training script. By the end, you'll be able to automatically log a rich set of system metrics, including GPU memory utilization, providing a complete historical record of your hardware's performance during training, all with just a few lines of code.
From Spot-Checking to Continuous Monitoring with W&B
Weights & Biases is a platform designed to help you track, visualize, and manage your machine learning experiments. Think of it as a centralized dashboard for everything related to your model training: hyperparameters, code versions, model performance metrics, output files, and, most importantly for us, system resource utilization.
While nvidia-smi gives you an instant reading, W&B runs a lightweight agent in the background of your script to sample and record these metrics over time, sending them to a web dashboard for analysis.
Getting Started: Installation and Authentication
Before you can log any data, you need to install the wandb library and authenticate your machine by linking it to your W&B account.
First, you'll need a free Weights & Biases account if you don't have one. You can sign up at wandb.ai.
The following guide provides the simple commands for installation and login.
Weights & Biases - Thunder Compute
This guide from Thunder Compute clearly lays out the initial setup steps for using Weights & Biases.
First, read the Installation section to see the pip command. Then, review the Authentication section. When you run wandb login, it will prompt you for an API key, which you can find in your W&B account settings.
In your Colab notebook or terminal, you will run:
pip install wandbwandb login
After running the login command, you'll be prompted to paste your API key. Once that's done, your environment is ready to communicate with the W&B servers.
Integrating W&B into a Training Script
The magic of W&B lies in its simplicity. To start logging an experiment, you only need to make two small additions to your script. The following video from the Weights & Biases team provides an excellent walkthrough.
🔥 Integrate Weights & Biases with PyTorch
This video tutorial demonstrates how to integrate Weights & Biases with a standard PyTorch training script. It clearly explains the core functions and shows where to find the automatically logged system metrics.
First, watch the segment on initializing a run. Pay close attention to the with wandb.init(...) as run: block. This is the primary function call that starts the experiment tracking. The presenter explains how to pass your hyperparameters via the config dictionary, which is crucial for reproducibility. Next, jump to the section where the presenter tours the system metrics dashboard. This part is key to our lesson. Notice how metrics like GPU utilization, temperature, and I/O are automatically captured and plotted over time without any extra code. This is the core benefit we're focusing on.
As the video explains, the two fundamental steps are:
-
Initialize the Run: You wrap your training logic in a
with wandb.init(...)block. This tells W&B to start a new experiment "run". Inside this function, you specify theprojectname (to group related runs) and pass aconfigdictionary containing your hyperparameters (like learning rate and batch size).import wandb # Define your hyperparameters config = { "learning_rate": 0.001, "batch_size": 128, "epochs": 5, } # Start a new W&B run with wandb.init(project="pytorch-memory-course", config=config): # Your training code goes here... pass -
Automatic System Monitoring: This is the most powerful part. As soon as
wandb.init()is executed, W&B automatically starts a background process that monitors and logs system-level metrics. You don't need to write any code for this.
As detailed in the documentation, this includes:
- GPU and CPU Utilization (%)
- GPU Memory Allocated (%) and Temperature (°C)
- System RAM Usage
- Disk and Network I/O
A Complete, Runnable Example
Let's put this all together. Here is a minimal but complete script you can run directly in a Google Colab notebook. It trains a simple CNN on the Fashion-MNIST dataset.
# 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
config = {
"learning_rate": 0.001,
"batch_size": 128,
"epochs": 3,
"architecture": "SimpleCNN"
}
# Step 4: Start the W&B run
with wandb.init(project="pytorch-memory-course-system-metrics", config=config) as run:
# Make config accessible to the script
config = run.config
# Step 5: Setup data, model, optimizer, and loss function
device = "cuda" if torch.cuda.is_available() else "cpu"
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
model.train()
for epoch in range(config.epochs):
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 metrics to W&B (optional, but good practice)
if i % 100 == 0:
wandb.log({"loss": loss.item()})
print("Training finished.")
After you run this code, wandb will print a link to your project page. Open it in your browser.
Visualizing System Metrics in the Dashboard
On your W&B run page, you'll find a "System" tab on the left-hand navigation panel. Clicking this reveals a dashboard of automatically generated plots showing the hardware metrics collected during your run.

An example of the system metrics dashboard in Weights & Biases. It provides various time-series graphs for GPU metrics like power usage, memory allocation, temperature, and utilization, all logged automatically during a run.
You can analyze these charts to understand your script's behavior:
- Process GPU Memory Allocated (%): This chart shows the percentage of GPU memory your process used over time. Is it stable? Does it spike? A steady increase might indicate a memory leak.
- Process GPU Utilization (%): This shows how effectively you are using the GPU's compute cores. If this number is low, it suggests a bottleneck elsewhere, perhaps in your data loading pipeline. Your goal is usually to get this as close to 100% as possible.
- Process GPU Temp (°C): Monitoring temperature can be important for long training runs on physical hardware to ensure you aren't overheating your device.
By using the W&B dashboard, you can easily compare these system metrics across different experiments. For example, you could run the script above with two different batch_size values and visually compare their GPU memory utilization on the same chart.

The W&B UI allows you to overlay charts from multiple runs, making it easy to compare GPU utilization, temperature, and memory usage between different experiments (e.g., runs with different hyperparameters).
Conclusion
In this lesson, you've learned how to move beyond manual, single-point-in-time hardware checks to a system of continuous, automated monitoring. With just the wandb.init() command, you can unlock a wealth of information about how your code interacts with the underlying hardware.
The key takeaways are:
- Weights & Biases is a tool for comprehensive experiment tracking, including system performance metrics.
- After installing and logging in, adding
with wandb.init(...)to your script is all it takes to start a new experiment run. - W&B automatically launches a background process to monitor and log critical system metrics like GPU memory usage, GPU utilization, and CPU usage throughout your training run.
- The W&B dashboard provides an intuitive interface for visualizing these metrics over time and comparing them across different experiments.
You now have a powerful tool for understanding the resource profile of your training jobs. In our final lesson, we will combine this with our knowledge from earlier modules. You'll learn how to log custom metrics—specifically, the peak PyTorch memory from torch.cuda.max_memory_allocated—to W&B, enabling precise comparisons of memory efficiency across different model architectures or training configurations.