Profiling in PyTorch (Part 1): A Beginner's Guide to torch.profiler
torch.profiler produces two artifacts: a statistical table showing where time goes and a Chrome/Perfetto trace showing when CPU and GPU events happen. A small 64x64 bf16 matmul+add is overhead-bound, with GPU time under 1% of CPU time, while 4096x4096 matrices shift the work to compute-bound GEMM kernels. The trace walkthrough explains a cold-start dead window of about 228 µs before aten::matmul dispatch, a CPU-GPU lane offset, gaps caused by profiler Activity Buffer Requests, and the dispatch chain from Python down to CUDA kernels. The practical advice is to warm up, use profiler schedules, and read Self versus total times carefully before turning to torch.compile.
Related posts
- Profiling TorchNeuron (Part 1): System-level profiling on AWS Trainium.
Hugging Face mediumAdeptA beginner-friendly walkthrough of system-level profiling for PyTorch on AWS Trainium using TorchNeuron. It covers configuring torch.profiler with NeuronConfig and NeuronProfiler, reading the key_averages() table, and tracing a single operation through framework, runtime and hardware lanes in Neuron Explorer. Three RMSNorm implementations are profiled. Naive eager ops take 2,355 µs of device time across 6 dispatches. torch.rms_norm lowers to one fused kernel at 403 µs, and torch.compile discovers the same fusion at 376 µs, roughly one-sixth of the naive cost because gaps between dispatches and intermediate tensors are eliminated.
- Profiling in PyTorch (Part 2): From nn.Linear to a Fused MLP
Hugging Face hardMasterProfiling an nn.Linear on an A100 shows a single cuBLAS/CUTLASS GEMM kernel with the bias folded in as an epilogue via aten::addmm, while aten::t only rewrites strides on the CPU and launches nothing. As a result, torch.compile has little to fuse for a lone Linear; it mainly removes CPU dispatch overhead by hard-coding strides, and the kernel's layout suffix (e.g. tn) shows how the transpose is absorbed. Stacking three Linears into a GeGLU MLP yields five kernels per forward pass: three GEMMs, each preceded by an occupancy query, plus separate GELU and multiply pointwise kernels. Reading kernel names and the profiler table shows which ops actually reach the GPU and where fusion could help.
- Host overhead is killing your inference efficiency
Modal mediumAdept
GPU idle time while the CPU prepares work (host overhead) shows up as low GPU kernel utilization and directly multiplies inference cost; 50% overhead means GPU spend is 2x what it could be. Gaps in CUDA streams visible in PyTorch Profiler or Nsight Systems traces reveal it. Fixes include avoiding synchronous CPU-GPU transfers by constructing tensors where they are needed (e.g. decode-time position embeddings, unit-size KV page lengths), fusing kernels with the Torch compiler (cutting ~20 launches to 3, saving ~30µs and 20% mean latency), and using CUDA Graphs to amortize remaining launch costs, as SGLang and vLLM already do.
- Profiling in PyTorch (Part 3): Attention is all you profile
Hugging Face mediumAdeptProfiling attention variants in PyTorch on an A100 shows how each implementation appears in profiler traces. Naive attention launches matmul, mul, masking, softmax and matmul kernels plus a hidden Memcpy from out-of-place masked_fill; switching to in-place masked_fill_ removes that kernel under no_grad. SDPA's math backend turns out 3.7x slower than the naive version: it launches 20 kernels, upcasts to FP32 sgemm on CUDA cores instead of bf16 Tensor Cores, rebuilds the causal mask every call, and uses a NaN-safe softmax. Fused backends such as the efficient (CUTLASS fmha) backend collapse attention into a single kernel, and kernel names can be read to tell which hardware path each backend takes.
- Visualize and understand GPU memory in PyTorch
Hugging Face mediumAdeptPyTorch's memory snapshot recorder (torch.cuda.memory._record_memory_history plus the memory_viz web tool) makes it possible to see exactly where GPU memory goes during training: persistent parameters, activations that grow in the forward pass and shrink in backward, gradients, optimizer state and transient optimizer intermediates. Profiling a Qwen2.5-1.5B training loop shows the peak can come from either the forward pass or the optimizer step depending on batch size. The resulting estimate is total memory = parameters + optimizer state (2×N×P for AdamW) + the larger of activations or gradients plus optimizer intermediates. Activations per token can be measured with forward hooks or approximated by a linear fit against parameter count (A ≈ 4.69e-4×N + 1.85e6).