PyTorch Profiler TensorBoard Plugin

0.4.3 · active · verified Tue Apr 14

torch-tb-profiler is a TensorBoard plugin that provides rich visualizations and analysis tools for profiling PyTorch models. It parses, processes, and visualizes profiling results dumped by `torch.profiler`, helping users identify performance bottlenecks and receive optimization recommendations. The current version is 0.4.3, with releases often tied to PyTorch updates or major bug fixes.

Warnings

Install

Imports

Quickstart

To use `torch-tb-profiler`, first, you need to set up `torch.profiler` in your training loop to generate profiling data. Use `torch.profiler.tensorboard_trace_handler` as the `on_trace_ready` callback to save the trace files. After your script runs and generates the profiling data, launch TensorBoard from your terminal, pointing to the parent directory of your profiling logs. The plugin will automatically be available under the 'PYTORCH_PROFILER' tab in your TensorBoard UI.

import torch
import torch.nn as nn
import torch.optim as optim
from torch.profiler import profile, record_function, ProfilerActivity, tensorboard_trace_handler
import os

# Create a dummy model and data
model = nn.Linear(10, 10).cuda() if torch.cuda.is_available() else nn.Linear(10, 10)
optimizer = optim.SGD(model.parameters(), lr=0.01)
dummy_input = torch.randn(64, 10).cuda() if torch.cuda.is_available() else torch.randn(64, 10)

# Define log directory for TensorBoard
log_dir = "./runs/profiler_test"

# Run profiler
with profile(
    schedule=torch.profiler.schedule(wait=1, warmup=1, active=3, repeat=2),
    on_trace_ready=tensorboard_trace_handler(log_dir),
    activities=[
        ProfilerActivity.CPU,
        ProfilerActivity.CUDA if torch.cuda.is_available() else ProfilerActivity.CPU,
    ],
    record_shapes=True,
    with_stack=True
) as prof:
    for i in range(10):
        optimizer.zero_grad()
        output = model(dummy_input)
        loss = output.sum()
        loss.backward()
        optimizer.step()
        prof.step() # Advance profiler to next step

print(f"Profiling results saved to {log_dir}.\n")
print("To view in TensorBoard, run: ")
print(f"tensorboard --logdir {os.path.abspath(log_dir.split('/profiler_test')[0])}")

view raw JSON →