Skip to content

Capture and read an XProf trace

Use this guide when a TorchTPU training or inference loop is correct but slower than you expect, and you need to know where the step time goes before you change anything. You capture a few steady-state steps with torch.profiler and TorchTPU's TpuProfilerConfig, check the capture is trustworthy, open it in XProf, and read it in a fixed order: step time, device idle, top ops, bound type. Chapter 10 explains each view and each trace signature; chapter 11 is what to do with the result. Serving engines (vLLM-TorchTPU, SGLang-TorchTPU) have their own capture paths, covered in the serving guides.

Prerequisites

  • A TPU host with TorchTPU and PyTorch 2.12 or newer (older PyTorch gives no TPU rows).
  • A step that already runs: warm it up and know its unprofiled step time.
  • Optional: this book's code/ch10_profiling/capture.py (source).

Steps

1. Install the viewer

TensorBoard depends on pkg_resources, which setuptools 81 removed, so pin it:

pip install "setuptools<81"
pip install xprof tensorboard

TorchTPU's profiling guide installs the TensorBoard plugin instead (pip install tensorboard-plugin-profile "setuptools<81"); either works with the commands in step 4.

Check: xprof is on your PATH.

2. Capture steady-state steps

Warm up outside the profiler, label each step, and synchronize before prof.step():

import pathlib
import torch
from torch.tpu.profiler import TpuProfilerConfig

log_dir = pathlib.Path("/tmp/profiler_output")
config = TpuProfilerConfig(
    host_tracer_level=2,
    device_tracer_level=1,
    python_tracer_level=0,
    run_dir=log_dir,
)

for _ in range(warmup_steps):          # compiles happen here, outside the trace
    train_step(batch)
torch.accelerator.synchronize()

with torch.profiler.profile(
    activities=[
        torch.profiler.ProfilerActivity.CPU,
        torch.profiler.ProfilerActivity.TPU,
    ],
    experimental_config=config,
    on_trace_ready=torch.profiler.tensorboard_trace_handler(str(log_dir)),
) as prof:
    for i in range(5):
        with torch.profiler.record_function(f"train_step#{i}"):
            train_step(batch)
            torch.accelerator.synchronize()
        prof.step()

print(prof.key_averages().table(sort_by="self_device_time_total", row_limit=8))

Why each line: ProfilerActivity.TPU is what produces device rows; warm-up inside the trace makes one step many times longer than the rest; without record_function there are no step boundaries to find; without the synchronize, a host range ends when Python has queued the work, long before the TPU finishes it. A handful of identical steps is enough for the Trace Viewer; capture more only when you need averages. On a multi-host run, give each process a distinct worker_rank (a string) or its own run_dir. On v7x you can also sample hardware performance counters through experimental_options (chapter 10, "Ironwood counters").

The companion script does the same capture on a small MLP:

python code/ch10_profiling/capture.py --log-dir /tmp/profiler_output --steps 5 --compiled

Check: the key_averages() table prints, ranked by device time.

3. Check the files

List the trace directory and stop if it is empty; TorchTPU's guide does this in Python:

import os

trace_files = os.listdir(log_dir)
print(f"Files found: {len(trace_files)}")

Check: the directory holds an .xplane.pb file (the companion script checks this for you). An empty directory means the profiler never stopped cleanly; let the with block exit.

4. Open the trace

xprof --logdir=/tmp/profiler_output --port=6006
# or, with the TensorBoard plugin, then open the Profile tab:
tensorboard --logdir=/tmp/profiler_output --port=6006

Open http://localhost:6006. Point --logdir at the directory, not at a file. On a TPU VM, VS Code's Remote-SSH forwards the port; otherwise forward it when you connect, ssh -L 6006:localhost:6006 <tpu-vm-host>. To keep traces after the VM is gone, copy them with their plugins/profile/<timestamp>/ structure intact. On GKE, write the trace directory to a Cloud Storage bucket mounted with the Cloud Storage FUSE CSI driver and open it with xprof --logdir=gs://<bucket>/profiler_output.

Check: the viewer lists the run and shows the Overview, Trace Viewer, Op Profile and Memory Profile.

5. Read it in order

  1. Step time. Count the train_step# ranges: the number equals the steps you captured, and no step is far longer than the others (a long first step means warm-up got in). The median should be within the profiler's overhead, about 5 to 10% per step, of the same loop timed without the profiler. If not, fix the capture before reading anything else.
  2. Device idle. In the Trace Viewer, look at the XLA Ops row of TPU:0 across one step. Gaps are idle hardware. Move up to the host rows at the moment a gap starts: a .item() shows as aten::item and aten::_local_scalar_dense, a blocking data loader as time in your input code.
  3. Top ops. Rank ops by total time in the Op Profile (or key_averages() sorted on device time). Click the top one and read its name, shape and source line.
  4. Bound type. Estimate the top op's time from its shape with the roofline, \(\max(T_\text{math}, T_\text{mem})\) (chapter 2). Near the estimate, the op runs at its bound and only fewer FLOPs or fewer bytes help. Far above it, something the roofline does not model is taking time: a copy, padding, a poor layout, a collective wait.

A four-stage reading order drawn as a column of numbered gray boxes on the left, each joined to the next by a downward arrow, with arrows to cards in a right-hand column. Box 1, Step time, train_step# ranges. An arrow labelled outlier step, or not within 5 to 10% leads right to an orange card, Fix the capture; an arrow labelled within 5 to 10% leads down to box 2. Box 2, Device idle, XLA Ops row of TPU:0. An arrow labelled at a gap leads right to a gray card, Read the host rows, aten::item; an arrow labelled no gap leads down to box 3. Box 3, Top ops, Op Profile, by total time. An arrow leads right to a gray card, Click the top op, Name, shape, source line; an arrow leads down to box 4. Box 4, Bound type, Roofline estimate. An arrow labelled far above the estimate leads right to an orange card, Time the roofline misses, Copy, padding, layout, collective wait. An arrow labelled near the estimate leads down from box 4 and then right to a green card of the same size at the bottom of the right column, At its bound, Only fewer FLOPs or fewer bytes help.

Stage 1 is a gate: an outlier step, or a median not within about 5 to 10% of the same loop timed without the profiler, means fix the capture before reading anything else. At a gap in the device row, a .item() shows on the host rows as aten::item; stage 4 ends in one of two verdicts, and only a top op far above its roofline estimate has time the roofline does not model.

Check: you can name one finding (a gap, a copy, a recompile, a slow op) and the stage that found it.

6. Fix one thing and capture again

Change the one thing the profile pointed to, capture again with the same settings, and compare.

Check: the specific finding is gone or smaller, the ranking of what remains has moved, and the unprofiled step time dropped by about what the removed time predicts. If the profile looks the same, the change did not touch the bottleneck. Keep both trace directories with the step times, versions and machine type.

Rehearse on a laptop

python code/ch10_profiling/capture.py --cpu-smoke runs the whole workflow on a CPU: a step with a 5 ms host-side stall, the same step without it, and a compiled model whose compiling step is captured by mistake. It prints the four reading stages for each and ends cpu-smoke: OK. Its lesson carries to a TPU: the top-ops list barely changed when the step got 3.5 times faster, because the step was 70% idle. Idle time comes before top ops.

Troubleshooting

Symptom Cause Fix
ModuleNotFoundError: No module named 'pkg_resources' starting TensorBoard setuptools 81 or newer pip install "setuptools<81"
No TPU rows, only CPU threads ProfilerActivity.TPU missing, or PyTorch older than 2.12 Add the activity; check torch.__version__
Trace directory empty The profiler never stopped cleanly Let the with block exit
Viewer finds no profile --logdir pointed at a file, or traces copied without plugins/profile/<timestamp>/ Point it at the directory above plugins/; copy with the hierarchy
One step many times longer than the rest Warm-up or compilation captured Warm up before entering the profiler
Trace step times far from the wall clock Missing synchronize, heavy tracer levels, or a different program Synchronize before prof.step(); default tracer levels; profile the code you run
Profiled step time reported as the result Profiler overhead, about 5 to 10% per step Measure speed with the profiler off
Ranks overwrite each other's files Same host name, same directory worker_rank per process, or a per-rank run_dir
Trace too large to load Too many steps or too verbose a tracer Fewer steps; host_tracer_level=2, python_tracer_level=0
Large gaps between TPU ops Host-side bottleneck: data loading, Python overhead, a host sync Prefetch data; keep decisions on the device; read values every N steps
Frequent short TPU bursts Graph breaks or recompiles TORCH_LOGS="recompiles"; remove .item() / .cpu() calls; torch.compile
Low MXU utilization on a matmul Dimensions not aligned to the 128 tile Pad dimensions to multiples of 128

References