Profiling with torch.profiler

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

Guessing is the most expensive way to speed up a model. torch.profiler records which operators ran, how long they took on the CPU and on the accelerator, how much memory they allocated and, optionally, which line of Python launched them. This page shows how to take a useful profile of a training loop, how to read the table and the trace, and what the main options cost. Use it before and after every change recommended in the Performance Tuning Guide.

Examples were run on Python 3.13 with PyTorch 2.15 (CPU) on 2026-10-31. Output columns and exact timings depend on your hardware and release, so no sample profiler output is shown.

What the profiler records

torch.profiler.profile is a context manager. It uses the Kineto library to collect:

  • CPU-side operator events (every ATen operator and the autograd functions that call them), with optional input shapes and Python stack traces.

  • Device kernel events and memory copies, collected through CUPTI on NVIDIA GPUs. Other back ends are exposed through the same ProfilerActivity enumeration.

  • Memory allocations and frees of tensors, when memory profiling is enabled.

  • User annotations created with record_function.

ProfilerActivity values include CPU, CUDA and XPU (the 2.15 reference also lists others such as MTIA, HPU and PrivateUse1 for additional back ends). torch.profiler.supported_activities() returns the set available in the current process. If CUPTI is not available, CUDA profiling falls back to a legacy mode that shows CUDA time in tables but not in the exported JSON trace. By default, activities are CPU plus the accelerator when one is present.

A first profile

import torch
import torch.nn as nn
from torch.profiler import profile, record_function, ProfilerActivity

device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Sequential(nn.Linear(512, 1024), nn.ReLU(), nn.Linear(1024, 10)).to(device)
x = torch.randn(256, 512, device=device)

activities = [ProfilerActivity.CPU]
if device == "cuda":
    activities.append(ProfilerActivity.CUDA)

with profile(activities=activities, record_shapes=True) as prof:
    with record_function("model_inference"):
        model(x)

sort_key = "cuda_time_total" if device == "cuda" else "cpu_time_total"
print(prof.key_averages().table(sort_by=sort_key, row_limit=10))

The table has one row per operator name, with its total and average time on each device, the number of calls and (with record_shapes=True and group_by_input_shape=True) one row per distinct input shape. Two vocabulary points matter:

  • Self time excludes time spent in child operators; total time includes it. Sorting by self_cpu_time_total shows where the CPU time is actually spent, while sorting by cpu_time_total shows enclosing operators first.

  • The recipe builds the accelerator sort key from the device name (cuda_time_total, xpu_time_total, and self_ variants). Newer releases may also expose device-neutral names; if a key is rejected, print prof.key_averages()[0] attributes or consult the reference for your release.

record_function("label") adds your own named ranges, which appear as events in tables and traces. Use it around the phases of a step (data, forward, backward, optimizer) to make the trace readable.

Profiling a training loop with a schedule

Profiling every step of a long job produces enormous traces and distorts timing. A schedule selects a few steps. schedule(wait, warmup, active, repeat=0, skip_first=0, skip_first_wait=0) skips the first skip_first steps, then in each cycle idles for wait steps, profiles warmup steps without keeping the result (so the profiler can settle), records active steps and repeats repeat times (0 means keep cycling). Call prof.step() once at the end of each iteration so the profiler knows where steps end.

import torch
import torch.nn as nn
from torch.profiler import profile, schedule, tensorboard_trace_handler, ProfilerActivity

device = "cuda" if torch.cuda.is_available() else "cpu"
model = nn.Linear(512, 10).to(device)
opt = torch.optim.SGD(model.parameters(), lr=0.01)
loss_fn = nn.CrossEntropyLoss()

activities = [ProfilerActivity.CPU] + ([ProfilerActivity.CUDA] if device == "cuda" else [])

prof = profile(
    activities=activities,
    schedule=schedule(skip_first=5, wait=1, warmup=1, active=3, repeat=1),
    on_trace_ready=tensorboard_trace_handler("./log/profile"),
    record_shapes=True,
    profile_memory=True,
    with_stack=True,
)

with prof:
    for step in range(20):
        x = torch.randn(128, 512, device=device)
        y = torch.randint(0, 10, (128,), device=device)
        loss = loss_fn(model(x), y)
        loss.backward()
        opt.step()
        opt.zero_grad(set_to_none=True)
        prof.step()

tensorboard_trace_handler(dir_name, worker_name=None, use_gzip=False) writes one trace file per cycle into a directory that can be used as a TensorBoard log directory. In distributed runs give every rank a unique worker_name (it defaults to host name and process id). Plain on_trace_ready accepts any callable that takes the profiler, so you can print a table or export a Chrome trace yourself:

from torch.profiler import profile, schedule, ProfilerActivity


def trace_handler(p):
    print(p.key_averages().table(sort_by="self_cpu_time_total", row_limit=10))
    p.export_chrome_trace(f"/tmp/trace_{p.step_num}.json")


with profile(activities=[ProfilerActivity.CPU],
             schedule=schedule(wait=1, warmup=1, active=2),
             on_trace_ready=trace_handler) as p:
    for _ in range(8):
        sum(i * i for i in range(10_000))
        p.step()

Per the reference, export_chrome_trace exports only the last schedule cycle when Kineto is enabled.

Options and their cost

Option Effect and caveat

record_shapes=True

Records operator input shapes, required for group_by_input_shape. Adds overhead.

profile_memory=True

Tracks tensor allocations and frees, giving memory columns in tables and a memory timeline. Adds overhead.

with_stack=True

Records the source file and line of each operator, needed for group_by_stack_n and stack views. Noticeably increases overhead and trace size.

with_flops=True

Estimates floating-point operations for matrix multiplication and 2D convolution only; other operators report zero.

with_modules=True

Deprecated. It only affects TorchScript models and does nothing in eager mode; use with_stack=True.

experimental_config

Opt-in extra data (for example hardware counters); consult the reference for your device.

Turn on only what you need. Time the effect of the profiler itself by comparing step times with it off, and never leave it on in production runs: the tuning guide lists the profiler among the debugging tools that must be disabled for normal training.

Reading the results

Tables

key_averages(group_by_input_shape=False, group_by_stack_n=0) aggregates events by operator name. Group by shape to see that, for example, the same aten::mm is cheap for one shape and dominant for another; group by stack (needs with_stack=True) to see which line of your code launches the expensive operators.

print(prof.key_averages(group_by_input_shape=True).table(sort_by="self_cpu_time_total", row_limit=10))
print(prof.key_averages(group_by_stack_n=5).table(sort_by="self_cpu_time_total", row_limit=10))

Timelines

Open an exported JSON trace in Perfetto (https://ui.perfetto.dev) or in Chromium at chrome://tracing. On a GPU run you will see one row per CPU thread and one row per CUDA stream. Things to look for:

  • Gaps between kernels on the GPU rows. The GPU is idle, either waiting for the CPU to launch more work (launch bound, many tiny kernels) or waiting for data or a host synchronisation. Remedies: fusion with torch.compile, CUDA graphs, larger batches, removing .item() calls.

  • A long cudaStreamSynchronize or cudaMemcpy on a CPU thread. An explicit synchronisation or a blocking copy. See "Avoid CPU-GPU synchronisation" in the tuning guide.

  • DataLoader time before the first kernel of a step. The input pipeline is the bottleneck: see Workers, Pinned Memory & Samplers.

  • NCCL kernels that do not overlap with compute kernels. Communication is exposed, a typical problem in DDP and FSDP2 jobs.

  • Few Tensor Core kernels in a model that should use them. Check precision and shapes (see Mixed Precision with torch.amp).

TensorBoard users can view the same traces with the profiler plugin; the integration is described in TensorBoard Integration.

Memory profiling

With profile_memory=True the table gains memory columns (for example cpu_memory_usage and self_cpu_memory_usage sort keys appear in the recipe), showing how much memory each operator allocated. The reference documents export_memory_timeline(path, device=None), which writes an HTML plot or JSON categorising memory use over time; the same reference marks it deprecated, to be removed in a future release, and recommends the allocator snapshot functions torch.cuda.memory._record_memory_history and torch.cuda.memory._export_memory_snapshot instead. Those snapshot tools, which also work without the profiler, are covered in GPU Memory & Activation Checkpointing.

Multi-rank profiling and Holistic Trace Analysis

In a distributed job profile all ranks, or at least two of them, with a unique worker_name per rank. A single rank can look healthy while another straggles. Holistic Trace Analysis (HTA) is an open source library that analyses the traces of a distributed job. According to the official tutorial it offers a temporal breakdown of each rank (idle, compute and non-compute such as communication and memory), an idle-time breakdown (host wait, kernel launch overhead, other), a kernel breakdown, a communication-computation overlap measurement, augmented counters (memory bandwidth, queue length) and CUDA kernel launch statistics.

pip install HolisticTraceAnalysis

Recording dispatched operations with DebugMode

The profiler measures time. When the question is which operators actually ran, or where two runs start to give different numbers, use DebugMode (torch.utils._debug_mode.DebugMode). It is a TorchDispatchMode that logs every dispatched ATen operator with the shapes and dtypes of its arguments, in eager mode and under torch.compile (where it also logs Inductor-generated Triton kernels on the GPU). The official recipe calls it a prototype feature, and the module name starts with an underscore, so pin the PyTorch version when you rely on it.

DebugMode.log_tensor_hashes adds a hash of every input and output to each line (by default the L1 norm, so close numbers give close hashes). Comparing the hashed logs of two runs, for example eager against compiled, shows the first operator whose output differs.

import torch
from torch.utils._debug_mode import DebugMode

torch.manual_seed(0)
model = torch.nn.Sequential(torch.nn.Linear(4, 3), torch.nn.ReLU())
x = torch.randn(2, 4)

with DebugMode() as dm:
    model(x)
print(dm.debug_string())


def ops_with_hashes(fn):
    """Log every op with a hash of its inputs and outputs."""
    with DebugMode(record_output=True) as dm, DebugMode.log_tensor_hashes(hash_inputs=True):
        fn(x)
    return dm.debug_string().splitlines()


eager = ops_with_hashes(model)
compiled = ops_with_hashes(torch.compile(model, backend="aot_eager"))
print(eager[-1])
print(compiled[:len(eager)] == eager)   # True: same ops with the same hashes

Output:

    aten::t(t: f32[3, 4])  ->  t: f32[4, 3]
    aten::addmm(t: f32[3], t: f32[2, 4], t: f32[4, 3])  ->  t: f32[2, 3]
    aten::relu(t: f32[2, 3])  ->  t: f32[2, 3]
    aten::relu(t: f32[2, 3])  ->  t: f32[2, 3]  # {'input_hash': ((3.069667100906372,), {}), 'hash': 0.6151011884212494}
True

Other constructor flags add detail: record_stack_trace=True with debug_string(show_stack_trace=True) prints the source line that issued each operator, record_ids=True labels tensors ($0, $1, …​) so data flow can be followed, and record_nn_module=True marks module boundaries. The compiled log above also contains extra aten::detach lines after the three shared ones, which is why the comparison slices it.

Pitfalls

  • Asynchronous execution. CPU timings of CUDA operators are launch times. Rely on the CUDA columns or the trace, not on wall clock around a call.

  • Profiling warm-up. The first steps include cuDNN autotuning, allocator growth and compilation. Use skip_first or warmup in the schedule.

  • Too many steps. active of a handful of steps is enough; long traces are slow to load.

  • Forgetting prof.step(). Without it a schedule never advances and nothing is written.

  • Stack and shape overhead. Compare timings between a lightweight profile and a heavyweight one before drawing conclusions.

  • Profiling compiled code. Compiled regions show generated kernels instead of ATen operators; compare against an eager profile to confirm what was fused. If compilation looks wrong, see Graph Breaks, Recompilation & Dynamic Shapes.

For the concepts of hardware utilisation see Hardware & Mixed Precision.