Foundations to Frontier
Tests
C. Programming, Tools and HPC › C5 High-Performance Computing

Profiling: PyTorch Profiler, Nsight and Friends

Optimization without measurement is guesswork. This topic covers how to find where time and memory go: correct timing of asynchronous GPU code, Python profilers (cProfile, py-spy), the PyTorch profiler (operator tables with self and total time, traces viewed in TensorBoard or Perfetto, memory profiling), Nsight Systems for whole-application timelines (CPU threads, CUDA API calls, kernels, copies, NVTX ranges) and Nsight Compute for per-kernel analysis (throughput against the roofline, occupancy, stall reasons). It also covers reading common timeline patterns (input-bound, launch-bound, compute-bound, synchronization stalls) and Amdahl's law for deciding what is worth fixing. In the exercises you compute self and total time from a Chrome trace, GPU utilization and idle gaps, and profile Python with cProfile; then you generate traces for three classic bottlenecks, diagnose them from metrics alone, and check which fix helps each, as Amdahl's law predicts.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Find the slow part first

If a trip takes too long, you’d first check which part is slow: the drive, the traffic jam or the hour spent looking for the car keys. Buying a faster car doesn’t help if the problem is the keys. A profiler is a stopwatch that times every part of a program at once and shows a timeline, so you fix the real bottleneck instead of guessing.

Reading a profiler timeline
fixes:
CPU threadGPU stream0 ms120.0 ms (3 steps, no fixes)
orange: waiting for the DataLoader · purple: launching kernels · blue: GPU busy · dashed line: end of 3 steps
step time 40.0 ms
speed-up 1.00×
GPU utilization 25%
Long gaps while the main thread waits for data: input pipeline bound. Use DataLoader workers, pinned memory, prefetching.
Profile before optimizing: a fix aimed at the wrong bottleneck changes nothing (Amdahl's law). In the data-bound run, mixed precision only shortens the 25% of the step the GPU was busy.
Why engineers care

GPU hours on clusters are expensive and limited, real-time loops on robots have hard deadlines, and onboard processing must fit a power budget. Profiling routinely finds 2–10× speed-ups in research code: a data loader starving the GPU, a hidden synchronization, a Python loop over tensors, a copy to the CPU on every step.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A profiler tells you…
  2. 2. If the GPU sits idle waiting for data, a faster GPU…
  3. 3. In the demo's data-bound run, which fix helps most?

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Timing correctly

import time, torch
torch.cuda.synchronize(); t0 = time.perf_counter()
for _ in range(100): y = model(x)
torch.cuda.synchronize(); dt = (time.perf_counter() - t0) / 100     # without synchronize you time only the launches

GPU work is asynchronous: Python returns as soon as a kernel is queued. Time with synchronization (or CUDA events), warm up first (the first iterations include compilation, cuDNN autotuning and allocation), and repeat to average out noise. Operations that read a GPU value on the CPU (.item(), .cpu(), print(tensor), Python if on a tensor) force a synchronization and can silently serialize a training loop.

Python-level profilers

python -m cProfile -s tottime script.py counts calls and time per function (tottime = self time, cumtime = including callees); py-spy samples a running process with low overhead (py-spy top --pid, py-spy record -o flame.svg); line_profiler times individual lines.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Why call torch.cuda.synchronize() before stopping a timer?
  2. 2. cProfile's tottime is…
  3. 3. Which of these forces a CPU-GPU synchronization?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

The PyTorch profiler

from torch.profiler import profile, ProfilerActivity, schedule, record_function, tensorboard_trace_handler
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
             schedule=schedule(wait=1, warmup=1, active=3),
             on_trace_ready=tensorboard_trace_handler("./log"),
             record_shapes=True, profile_memory=True, with_stack=True) as prof:
    for step, (x, y) in enumerate(loader):
        with record_function("train_step"):
            loss = loss_fn(model(x.cuda()), y.cuda()); loss.backward(); opt.step(); opt.zero_grad()
        prof.step()
print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=15))

The table lists each operator’s calls, self time (excluding nested operators) and total time (including them), on CPU and GPU. The exported trace is a Chrome/Perfetto JSON timeline of complete events (name, start, duration, thread or stream), which you can open in TensorBoard, chrome://tracing or ui.perfetto.dev, or analyze in code.

Nsight Systems and Nsight Compute

Nsight Systems (nsys profile -t cuda,nvtx,osrt python train.py) records a system-wide timeline: CPU threads, CUDA API calls, kernels, memory copies, NCCL communication, with your own NVTX ranges (torch.cuda.nvtx.range_push("forward")). Use it first to see where time goes and what overlaps. Nsight Compute (ncu --set full) then analyzes individual kernels: achieved memory and compute throughput (its roofline, C5.3), occupancy (C5.2), cache hit rates and warp stall reasons.

🐍 Exercise 1: analyzing a profiler trace
Load complete events from a Chrome-trace JSON; compute self time for nested CPU operators on each thread; build an operator table (count, total, self) sorted by self time; compute GPU utilization from the union of kernel intervals and list idle gaps; profile a Python call with cProfile and read call counts with pstats.
📝 Quick check (Level 2)
0/3 answered
  1. 1. aten::linear has total 550 µs and its nested aten::matmul calls take 350 µs. Its self time?
  2. 2. Which tool shows the whole-application timeline with CPU threads, kernels and copies?
  3. 3. GPU utilization from a trace is best computed from…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Reading timelines

Pattern on the timeline Diagnosis Typical fixes
GPU idle at the start of every step while the main thread is in the DataLoader input-bound num_workers, pin_memory, prefetching, faster decoding, sharded datasets (C4.1)
thousands of microsecond kernels with gaps between them, CPU busy launching launch-bound CUDA graphs, fusion / torch.compile (C5.8), larger batches
GPU continuously busy compute-bound mixed precision (C5.5), better kernels, less work
GPU idle around .item(), .cpu(), logging synchronization stalls log less often, keep values on the GPU
copies not overlapping kernels transfer-bound pinned memory with non_blocking=True, keep data resident
NCCL kernels dominating communication-bound gradient bucketing, overlap, fewer/larger all-reduces (C5.10)

Amdahl’s law

If a fraction p of the time is accelerated s times, the overall speed-up is 1/((1 − p) + p/s), never more than 1/(1 − p). Optimize the largest fraction first, and re-profile after every change: the bottleneck moves.

📝 Quick check (Level 3)
0/3 answered
  1. 1. 90% of the time is sped up 10×. Overall speed-up?
  2. 2. Thousands of 4 µs kernels with CPU launch cost 12 µs each: the step is…
  3. 3. After fixing the input pipeline, what should you do?

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Diagnosing three training runs

Exercise 1. In a hand-built trace, aten::linear (2 calls, 550 µs total) has 200 µs self time because its nested aten::matmul calls account for 350 µs; the top self-time entry is the DataLoader; the GPU is busy 36% of the 1 ms step, with idle gaps from 300 to 450 µs and from 470 to 650 µs. cProfile counts exactly 50 calls of slow_norm and 10 000 calls of its inner sq.

Exercise 2: three bottlenecks, three fixes. A simulator generates five steps of CPU and GPU events for three runs, and the metrics alone identify each:

Run GPU utilization data wait launch time mean kernel diagnosis
A 25% 75% 1% 200 µs data-bound
B 33% 0% 100% 4 µs launch-bound
C 100% 0% 1% 1000 µs compute-bound

Step time (ms) after each fix:

Run none 4 DataLoader workers CUDA graphs mixed precision
A (data-bound) 40.0 11.5 40.0 35.0
B (launch-bound) 36.0 36.0 12.0 36.0
C (compute-bound) 40.0 40.0 40.0 20.0

Each run improves 2–3.5× with the matching fix and barely changes otherwise. Mixed precision on run A gives exactly what Amdahl’s law predicts from its 25% GPU fraction: 1/(0.75 + 0.25/2) = 1.14×. (Run A’s 11.5 ms average includes the first step, which has nothing prefetched; the steady state is 10 ms.)

🐍 Exercise 2 (research): diagnose three training runs
Simulate CPU and GPU events for data-bound, launch-bound and compute-bound training steps; compute utilization, data-wait and launch fractions and mean kernel duration from the events; diagnose each run from the metrics; apply DataLoader workers, CUDA graphs and mixed precision to each and compare step times; check a non-matching fix against Amdahl's law.

Profiling in AI, robotics and aerospace

  • Training efficiency: model FLOP utilization (MFU) dashboards built from profiler traces; finding stragglers in multi-GPU jobs (C6).
  • Robotics: NVTX ranges around perception, planning and control stages to verify loop deadlines on Jetson with Nsight Systems.
  • Scientific codes: Nsight Compute and VTune roofline analysis of solver kernels before porting to GPUs.
  • Flight software: worst-case execution time analysis is the hard real-time counterpart of profiling.

References

  1. PyTorch documentation (pytorch.org/docs): torch.profiler, Profiling to understand torch.compile performance; PyTorch tutorial “PyTorch Profiler with TensorBoard”.
  2. NVIDIA. Nsight Systems User Guide and Nsight Compute Profiling Guide (docs.nvidia.com).
  3. G. M. Amdahl (1967). “Validity of the single processor approach to achieving large scale computing capabilities.” AFIPS Conference Proceedings, 30.
  4. B. Gregg (2016). “The flame graph.” Communications of the ACM, 59(6).
  5. Python documentation: The Python Profilers (cProfile, pstats).