TensorBoard Integration

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

TensorBoard is a web dashboard for inspecting training runs: loss curves, histograms of weights and gradients, sample images, the model graph, embedding projections and hyperparameter comparisons. PyTorch does not ship the dashboard; it ships a writer, torch.utils.tensorboard.SummaryWriter, that produces the event files TensorBoard reads. This page shows how to wire it into a training loop and how to avoid the usual mistakes. For comparing many runs, hosted trackers and registries, see Experiment Tracking & MLOps.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) and TensorBoard 2.21 on 2026-10-31. TensorBoard is a separate package: neither PyTorch nor TensorFlow 2.21 installs it, so install it explicitly as shown below.

Installation

SummaryWriter needs the separate tensorboard package, plus pillow for images and matplotlib for figures.

pip install torch tensorboard pillow matplotlib

Writing scalars

Create one writer per run, pointing at a log directory, and call add_scalar(tag, value, global_step) from the loop. Tags containing a slash are grouped into sections in the UI, so Loss/train and Loss/val appear next to each other. add_scalars(main_tag, tag_scalar_dict, global_step) plots several series on one chart. Convert tensors to Python numbers with .item() first, and use the global step (not the epoch) as the x axis so curves from different batch counts stay comparable.

import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter

torch.manual_seed(0)
model = nn.Linear(10, 1)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.MSELoss()

writer = SummaryWriter("runs/linear_demo")   # one directory per run

step = 0
for epoch in range(5):
    for _ in range(20):
        x = torch.randn(32, 10)
        y = x.sum(dim=1, keepdim=True)
        loss = loss_fn(model(x), y)
        opt.zero_grad()
        loss.backward()
        opt.step()
        writer.add_scalar("Loss/train", loss.item(), step)
        step += 1
    writer.add_scalars("LR_and_norm", {
        "lr": opt.param_groups[0]["lr"],
        "weight_norm": model.weight.norm().item(),
    }, epoch)

writer.close()

Launching the dashboard

tensorboard --logdir=runs

Open the printed address (by default http://localhost:6006). Pointing --logdir at the parent directory shows every run in subdirectories as a separate colour, which is how you compare experiments; give each run its own subdirectory, for example runs/lr0.1_bs32, or the runs overwrite each other’s curves.

What else can be logged

Method Purpose

add_histogram(tag, values, global_step)

Distribution of weights, activations or gradients over time; useful for spotting vanishing or exploding values.

add_image(tag, img_tensor, global_step) and add_images

One image or a batch, channel-first layout; needs pillow.

add_figure(tag, figure, global_step)

Renders a matplotlib figure, for example a confusion matrix; needs matplotlib.

add_graph(model, input_to_model)

Traces the model with an example input and logs the computation graph.

add_embedding(mat, metadata, label_img, global_step)

Feature vectors for the embedding projector.

add_hparams(hparam_dict, metric_dict)

Hyperparameters with their resulting metrics for the HParams tab.

add_text(tag, text_string, global_step)

Notes and configuration dumps.

add_pr_curve(tag, labels, predictions, global_step)

Precision-recall curve for binary problems.

flush() and close()

Write pending events; call close() at the end of a run.

import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter

model = nn.Sequential(nn.Linear(10, 16), nn.ReLU(), nn.Linear(16, 2))
writer = SummaryWriter("runs/inspection")

# Weight and gradient distributions
for name, p in model.named_parameters():
    writer.add_histogram(f"weights/{name}", p, 0)

# Model graph from an example input
writer.add_graph(model, torch.randn(1, 10))

# Hyperparameters and their final metric
writer.add_hparams({"lr": 0.1, "batch_size": 32}, {"hparam/accuracy": 0.91})

# Embeddings with labels
features = torch.randn(50, 5)
writer.add_embedding(features, metadata=[f"item{i}" for i in range(50)])

writer.close()

Practical advice

  • Log scalars every N steps rather than every step on long runs; event files grow and the UI slows down. Histograms are much larger than scalars, so log them once per epoch.

  • Calling add_graph on a model that is already moved to a GPU requires the example input on the same device. Models with data-dependent control flow may not trace into a faithful graph.

  • Call writer.flush() if you want to watch a run live and the file has not been written yet, and writer.close() when finished.

  • With distributed training (see DistributedDataParallel), create the writer only on rank 0 so that processes do not write duplicate or conflicting event files.

  • Use the logged weight histograms together with the diagnostics in Training Deep Networks and Deep Learning Tuning Playbook to recognize unstable training. For performance traces, the profiler is the right tool: see Profiling.

  • Trainers such as Lightning (see Ecosystem) log to TensorBoard through a built-in logger, so you rarely need to call SummaryWriter yourself there.

The SummaryWriter is a thin convenience over the TensorBoard file format; the dashboard itself is a separate project, and its features (plugins, remote hosting) are governed by the TensorBoard documentation rather than by PyTorch.