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.
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.
- 1. A profiler tells you…
- 2. If the GPU sits idle waiting for data, a faster GPU…
- 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 launchesGPU 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.
- 1. Why call torch.cuda.synchronize() before stopping a timer?
- 2. cProfile's tottime is…
- 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.
- 1. aten::linear has total 550 µs and its nested aten::matmul calls take 350 µs. Its self time?
- 2. Which tool shows the whole-application timeline with CPU threads, kernels and copies?
- 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.
- 1. 90% of the time is sped up 10×. Overall speed-up?
- 2. Thousands of 4 µs kernels with CPU launch cost 12 µs each: the step is…
- 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.)
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
- PyTorch documentation (pytorch.org/docs): torch.profiler, Profiling to understand torch.compile performance; PyTorch tutorial “PyTorch Profiler with TensorBoard”.
- NVIDIA. Nsight Systems User Guide and Nsight Compute Profiling Guide (docs.nvidia.com).
- G. M. Amdahl (1967). “Validity of the single processor approach to achieving large scale computing capabilities.” AFIPS Conference Proceedings, 30.
- B. Gregg (2016). “The flame graph.” Communications of the ACM, 59(6).
- Python documentation: The Python Profilers (cProfile, pstats).