Inspect PyTorch GPU launches
Capture a real GPU operation and interpret its launch dimensions and timing boundaries.
See the launch behind a multiplication
The course uses editable CUDA programs to explain GPU execution. This appendix uses the PyTorch expression y = x * 2 to inspect a framework-selected implementation. A profiler records the CPU calls and GPU activity from a real run, so you can inspect which kernels were launched and how their threads were grouped.
Reading this appendix needs no installation. Capturing a CUDA trace requires an NVIDIA GPU, a compatible driver and CUDA-enabled PyTorch with CUDA profiling support. Follow the PyTorch desktop setup first. The browser simulations and our GPGPU-Sim functional checks cannot capture PyTorch’s actual GPU launches.
Definitions
- Trace
- A record of events from one run, including their names and times. A timeline viewer draws these events along a time axis.
- Grid dimensions
- The numbers of thread blocks along the launch’s x, y and z axes.
- Block dimensions
- The numbers of threads along a block’s x, y and z axes.
Start with a timeline, then inspect a kernel’s launch details. These describe the implementation selected for that run; they are not settings guaranteed by the PyTorch API.
1. Capture one PyTorch operation
Download profile-pytorch.py. It keeps this multiplication and uses 4,096 FP32 input values to give PyTorch a larger array. The program checks CUDA availability, prints the PyTorch version and GPU name, and runs five warm-up multiplications before recording one more.
You can copy this complete capture example into a Python file. It shares its imports, calculation, capture and output check with the download; the download also checks the CUDA setup and provides a mode for external profiling tools.
PyTorch · complete capture example
import torch
from torch.profiler import ProfilerActivity, profile, record_function
print("PyTorch:", torch.__version__)
print("PyTorch CUDA build:", torch.version.cuda)
print("GPU:", torch.cuda.get_device_name())
x = torch.arange(
1, 4097, dtype=torch.float32, device="cuda",
)
for _ in range(5):
y = x * 2
torch.cuda.synchronize()
activities = [ProfilerActivity.CPU, ProfilerActivity.CUDA]
with profile(activities=activities) as prof:
with record_function("gpu_lab_multiply"):
y = x * 2
torch.cuda.synchronize()
prof.export_chrome_trace("trace.json")
torch.testing.assert_close(y, x + x)
print("Verified multiplication output")In a terminal in the download folder, run:
Terminal · shell commands
python profile-pytorch.pyThe program writes trace.json and checks the multiplication result. Allocation and warm-up are outside the recorded interval; synchronisation inside it waits for the captured GPU operation to finish. The range also includes CPU overhead and that wait, so its duration is not the kernel’s execution time.
This is an inspection example, not a benchmark. We have checked the trace-reader logic and Python syntax; this capture program has not yet been validated on an NVIDIA GPU.
2. Open the timeline
Open the Perfetto trace viewer (new tab) and choose Open trace file to load your trace.json.
The viewer draws CPU calls and GPU kernels on separate tracks (timeline rows). Our named CPU range, gpu_lab_multiply, encloses the multiplication call and its wait. A kernel’s correlation ID links it to the CPU-side CUDA call that launched it.
Inspect your run
Find the CPU range named gpu_lab_multiply. Expand the CPU and GPU tracks, then select a GPU kernel event. Inspect its name, duration and arguments.
The CPU-side CUDA launch and GPU kernel are separate events; use the viewer’s event links or matching correlation IDs where available to connect them. GPU work can begin after its CPU launch call returns. Do not assign a kernel to an operator solely because the timeline boxes overlap.
Look in a kernel event’s arguments for grid and block. PyTorch’s Kineto trace exporter can include these fields. Field availability and presentation vary with PyTorch, CUDA profiling support and the viewer. key_averages().table() aggregates operator statistics; use the exported trace to inspect individual launches.
One PyTorch operation may launch several kernels. Conversely, torch.compile can combine operations or select a different implementation. The number of Python expressions is not a kernel count.
3. Read grid and block dimensions
Download inspect-pytorch-trace.py beside the trace. This reader needs only Python’s standard library, so you can also inspect a trace copied from another machine without installing PyTorch.
Terminal · shell commands
python inspect-pytorch-trace.py trace.jsonIt lists every kernel event (also accepting Kernel), its name, grid, block and correlation ID. It does not infer which CPU operator owns an event. Missing or unrecognised dimensions are reported as unavailable. No kernel events can mean CUDA activity was not captured; it is not proof that no GPU work ran.
Illustration · lesson 3’s five-input launch, not measured PyTorch output
grid: [2, 1, 1]
block: [4, 1, 1]grid: [2, 1, 1]means 2 × 1 × 1 = 2 blocks.block: [4, 1, 1]means 4 × 1 × 1 = 4 threads per block.- Together they describe 8 launched threads. A bounds check can make extra threads skip array accesses.
Use the dimensions from your trace to do the same calculation. PyTorch need not choose this illustrative launch. Dimensions alone do not reveal which streaming multiprocessor (SM) runs each block, whether threads execute at once, or how fast the calculation is. The scheduling chapter explains how an SM holds and schedules groups of threads.
Check your interpretation
For a new case, interpret grid [3, 2, 1] and block [8, 4, 1]. How many blocks, threads per block and launched threads does that describe?
Compare your answer
There are 6 blocks, 32 threads per block and 192 launched threads. These counts do not establish how many useful array elements are processed or how much parallel execution occurs.
Optional: inspect with NVIDIA Nsight
Nsight Systems shows CPU calls, transfers and GPU kernels on a timeline. Nsight Compute inspects individual kernels and their hardware metrics. Both need a supported NVIDIA setup and separate installation; Compute may also need permission to access GPU performance counters. Use the Nsight Systems and Nsight Compute links in References for installation and command options on your platform.
The download’s --external mode runs the same setup and multiplication without starting the PyTorch profiler. It marks the target multiplication with an NVTX range: a named annotation that NVIDIA’s tools can recognise.
Nsight Systems: follow the timeline
Terminal · shell commands
nsys profile -t cuda,nvtx -o multiply \
python profile-pytorch.py --external
nsys stats --report cuda_gpu_trace multiply.nsys-repOpen multiply.nsys-rep in the Nsight Systems application and find gpu_lab_multiply. The statistics report lists kernels and memory operations; kernel rows include GrdX/Y/Z and BlkX/Y/Z launch dimensions in current versions. This whole-process capture also contains allocation, warm-up and result checking. Use the named range and correlation information to identify the target.
Nsight Compute: inspect one marked operation
Terminal · shell commands
ncu --nvtx --nvtx-include "gpu_lab_multiply/" \
--section LaunchStats --section Occupancy \
python profile-pytorch.py --externalThe NVTX filter selects kernels launched inside the named range; the trailing / identifies a push/pop range. Launch Statistics reports launch configuration and register use. The scheduling chapter introduces registers, warps and residency, which prepare you to interpret the Occupancy section. Occupancy compares resident warps with the SM’s maximum; theoretical occupancy describes what resources permit, while achieved occupancy describes activity during a measurement. It is not a speed score. For CSV output, add --csv --page raw. For a different workload, use the documented kernel-name and launch filters after identifying its target.
Profiler collection adds overhead, and Compute may replay kernels to gather metrics. Do not compare these runs’ wall-clock durations as application benchmarks. Use separate runs for PyTorch profiling and Nsight. Record your tool versions, GPU, input shape and dtype with any conclusion.
If the trace is missing GPU details
- CUDA is unavailable: check the NVIDIA driver and CUDA-enabled PyTorch installation. A CPU-only installation can check values, but cannot record GPU launches.
- The trace has CPU events only: check CUDA profiler support, warnings about CUPTI (NVIDIA’s profiling interface), and whether the capture interval includes the operation. Some setups can report CUDA time in summaries without exporting GPU events.
- A kernel lacks grid or block fields: inspect the original event arguments and tool versions. Try Nsight Systems on supported hardware. Do not substitute the teaching diagram’s dimensions.
- A command or report differs: use the official guide matching the installed tool version.
Return to the first CUDA kernel and launch, or use the matrix-investigation lesson to investigate a workload of your own.