Phase 02/Writing and measuring kernels/GPU profiling basics
PHASE 02 · Writing and measuring kernels

GPU profiling basics

0%
6 h6 subtopics3 lessons · 2 required
In plain English

A profiler is a stopwatch and a security camera for your program. Instead of guessing why something is slow, you record exactly which kernels ran, when they started and stopped, how long the GPU sat idle waiting for the CPU, and how much of the memory pipe each kernel used. It is like reviewing footage of a restaurant kitchen during a rush: you can see whether the cooks are overloaded, whether they are standing around waiting for ingredients, or whether the manager keeps interrupting them with tiny orders. This topic teaches you to read that footage using the PyTorch profiler and NVIDIA's command-line tools, all from a free cloud GPU.

Why it matters

Performance work without a profiler is guesswork. Knowing how to confirm "this kernel is memory-bound at 70 percent of peak" or "the GPU is idle 40 percent of the time because of Python overhead" is the difference between an opinion and a diagnosis. Phase 4 builds on this with Nsight Systems and Nsight Compute in depth.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Baseten, Cerebras, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Time GPU work correctly with events and explain why wall-clock timing misleads.
  • Capture and read a PyTorch profiler trace, identifying kernel time versus idle gaps.
  • Use nsys from the command line to get a kernel summary for a script.
  • Read achieved occupancy and memory throughput for one kernel and classify it as memory- or compute-bound.
  • Interpret nvidia-smi utilisation and explain its limits.

Key concepts

Wall-clock versus device time
Host timers include launch overhead and asynchrony artefacts; CUDA events measure time between markers on the device.
Warm-up
Discarding the first iterations so that JIT compilation, cuDNN autotuning and allocator growth do not pollute the measurement.
Trace / timeline
A time-ordered record of CPU calls and GPU kernels; gaps between kernels indicate the GPU waiting on the host.
Kernel summary
Aggregated time per kernel name; the first thing to look at to find the top consumers.
Achieved occupancy
Average fraction of maximum resident warps actually active during a kernel, as reported by the profiler.
Memory throughput percentage
Fraction of peak DRAM bandwidth a kernel achieved; near 80 percent or more means memory-bound and near peak.
Launch overhead
The 5-10 microseconds of CPU and driver work per kernel launch that dominates when kernels are tiny.
SM utilisation (nvidia-smi)
Percentage of time at least one kernel was running; says nothing about how busy the SMs actually were.

Subtopics

  1. 1. Correct micro-benchmarking

    torch.cuda.Event and cudaEvent timing, warm-up, repetition, median versus mean, and controlling clocks where possible.

  2. 2. The PyTorch profiler

    torch.profiler.profile with CUDA activities, key_averages tables, exporting Chrome traces and reading them in Perfetto.

  3. 3. Spotting CPU-bound workloads

    Gaps between kernels, many tiny kernels, Python overhead; why small-batch decode is often launch-bound.

  4. 4. Nsight Systems from the command line

    nsys profile --stats=true, the cuda_gpu_kern_sum report, and reading the kernel and memcpy summaries without a GUI.

  5. 5. Per-kernel metrics

    What Nsight Compute reports (achieved occupancy, DRAM throughput percent, compute throughput percent) and how to read the speed-of-light section.

  6. 6. nvidia-smi and what it does not tell you

    Memory used, power, GPU-Util definition, and why 100 percent utilisation can still mean a slow kernel.

Resources

Hands-on lessons

L1

Profile a GPT-2 forward pass with the PyTorch profiler

Colab T4 · freenotebook90 minrequired

Goal · A key_averages table and a Perfetto trace for GPT-2 small on a T4 at batch 1 and batch 32, with the GPU idle fraction computed for each.

  1. 1Load gpt2 in float16 on a T4; run 5 warm-up forward passes on a 128-token input.
  2. 2Wrap 10 forward passes in torch.profiler.profile(activities=[CPU, CUDA], record_shapes=True) and print key_averages().table sorted by cuda_time_total.
  3. 3Export a Chrome trace with prof.export_chrome_trace and open it in ui.perfetto.dev; screenshot one layer's kernels.
  4. 4Sum total CUDA kernel time and divide by wall time of the profiled region to get GPU busy fraction for batch 1.
  5. 5Repeat with batch 32 and compare busy fraction and top kernels.
  6. 6Write three sentences on which kernels dominate at each batch size and whether the workload is launch-bound.
Deliverable
Notebook with both tables, the busy fractions and the trace screenshot.
Check
Batch 1 GPU busy fraction is noticeably lower than batch 32; the top kernel by CUDA time at batch 32 is a GEMM (names containing gemm, cutlass or sgemm/hgemm).
Fallback
Run on Kaggle; or profile on CPU with the same API and compare operator time distribution, noting that the idle-gap analysis needs a GPU.
L2

Classify your own kernels with nsys and ncu

Colab T4 · freecli90 minrequired

Goal · An nsys kernel summary and an ncu speed-of-light report for the saxpy and tiled matmul binaries from earlier lessons, each labelled memory- or compute-bound.

  1. 1On Colab, install the toolkit profilers if missing (apt-get install nsight-systems or use the versions bundled with the CUDA toolkit; !which nsys ncu).
  2. 2Run !nsys profile --stats=true -o saxpy_prof ./saxpy and read the cuda_gpu_kern_sum and cuda_gpu_mem_time_sum tables.
  3. 3Run !ncu --section SpeedOfLight ./saxpy and record DRAM Throughput percent and Compute (SM) Throughput percent.
  4. 4Repeat ncu for the tiled matmul binary at N=4096 and for the naive matmul.
  5. 5Build a small table of the three kernels with both throughput percentages and achieved occupancy.
  6. 6Label each memory-bound or compute-bound and reconcile with the roofline positions you computed in p2-memory-coalescing-bandwidth-l1.
Deliverable
profiling_summary.md with the three ncu rows and the nsys kernel summary pasted in.
Check
saxpy shows DRAM throughput above 60 percent and low SM throughput (memory-bound); tiled matmul shows SM throughput higher than DRAM throughput; the labels agree with the roofline predictions.
Fallback
If ncu is blocked by Colab permissions (ERR_NVGPUCTRPERM), use nsys only plus the bandwidth and FLOP/s numbers you measured with events to classify the kernels.
L3

Micro-benchmark pitfalls on CPU

CPU · your Macscript45 minoptional

Goal · A script demonstrating three timing mistakes (no warm-up, mean instead of median, measuring the wrong region) and the corrected harness you will reuse for GPU work.

  1. 1Write a benchmark harness bench(fn, warmup, iters) that returns median and interquartile range using time.perf_counter_ns.
  2. 2Time torch.matmul on CPU for N=1024 with warmup=0 versus warmup=5 and show the first iteration is an outlier.
  3. 3Inject one artificial 50 ms sleep into 100 iterations and show mean moves by about 0.5 ms while median does not.
  4. 4Show that including tensor allocation inside the timed region inflates the result; move it outside and compare.
  5. 5Add an optional device argument that uses torch.cuda.Event when the device is cuda, so the same harness works in later lessons.
Deliverable
bench.py with the three before/after comparisons printed.
Check
Un-warmed first iteration is at least 2x the median; mean minus median is roughly 0.5 ms with the injected sleep; the harness runs without error on CPU.

Build your own

Build your own kernel profiler report tool

PythonColab T4 · free~6 h

A Python CLI that ingests nsys and ncu CSV exports, computes FLOPs, bytes, busy fraction and launch gaps per kernel, places every kernel on a T4 roofline and writes a one-page markdown verdict.

The real thing: gitlab.com/NERSC/roofline-on-nvidia-gpus ↗

How you know a stage passes

Write tests/test_report.py first against fixture CSVs committed in tests/fixtures/ (nsys stats and ncu --csv exports captured once on a Colab T4 from the saxpy and tiled-matmul binaries of earlier lessons). Each stage adds a test with exact expected numbers computed by hand from the fixtures. The CLI `python kprof.py report --nsys trace.csv --ncu metrics.csv --gpu t4` must exit 0 and write report.md and roofline.png. Parsing and plotting run on any machine; only capturing fresh CSVs needs the T4.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01parse the nsys kernel summary
    Read the `nsys stats --report cuda_gpu_kern_sum --format csv` export into a table of kernel name, instances, total, average and max time, sorted by total.
    test · On the fixture the summed total equals the known total within 1 nanosecond and the top kernel name matches the expected string exactly.
  2. 02launch gaps and GPU busy fraction
    Parse the cuda_gpu_trace export, compute busy fraction as kernel time over wall span, and build a histogram of gaps between consecutive kernels with a launch-bound verdict when the median gap exceeds the median kernel duration.
    test · Fixture busy fraction matches the hand-computed value within 0.1 percent; a synthetic trace of 10-microsecond kernels separated by 20-microsecond gaps is labelled launch-bound.
  3. 03FLOPs and bytes from ncu metrics
    Parse `ncu --csv --metrics dram__bytes.sum,gpu__time_duration.sum,sm__sass_thread_inst_executed_op_ffma_pred_on.sum,sm__sass_thread_inst_executed_op_fadd_pred_on.sum,sm__sass_thread_inst_executed_op_fmul_pred_on.sum` output and compute FLOPs (2 per FFMA) and bytes per kernel.
    test · For the saxpy fixture, FLOPs equal 2 x n within 1 percent and bytes equal 3 x n x 4 within 5 percent.
  4. 04roofline placement and classification
    A GPU spec table (t4 is 8.1 TFLOPS fp32, 65 TFLOPS fp16 tensor, 320 GB/s; a100 and h100 too), arithmetic intensity, attainable versus achieved FLOP/s, percent of the limiting roof and a memory- or compute-bound label per kernel.
    test · saxpy lands left of the T4 ridge point (about 25 FLOP per byte), is labelled memory-bound and shows at least 60 percent of the bandwidth roof; the tiled matmul lands right of the ridge and is labelled compute-bound.
  5. 05plot and report
    A matplotlib roofline with one labelled point per kernel and a report.md containing the kernel table, busy fraction, gap histogram summary and a one-line verdict per kernel.
    test · `python kprof.py report --nsys tests/fixtures/trace.csv --ncu tests/fixtures/metrics.csv --gpu t4` exits 0, writes roofline.png and report.md, and the report has exactly one row per kernel in the fixture.
  6. 06profile your own kernels end to end
    A capture script runs nsys and ncu on the reduction and SGEMM binaries from the earlier builds on Colab, feeds the CSVs to the tool, and falls back to nsys plus event-based FLOP and byte estimates with a warning if ncu is blocked by ERR_NVGPUCTRPERM.
    test · The report labels the reduction memory-bound and the 2D-blocked SGEMM compute-bound, agreeing with the ncu SpeedOfLight section read by hand; in fallback mode the warning is printed and the report is still produced.

Knowledge check

Qnvidia-smi shows 100 percent GPU-Util. Is the GPU necessarily well used?

No; GPU-Util only means a kernel was running during the sample. A single poorly occupied kernel reads as 100 percent.

QIn a trace, you see thousands of 10-microsecond kernels with 20-microsecond gaps between them. What is the bottleneck?

The host; the GPU finishes each kernel faster than the CPU can launch the next, so the workload is launch- or Python-bound. Fusion or CUDA Graphs are the fixes.

QWhat two numbers from Nsight Compute's Speed of Light section tell you whether a kernel is memory- or compute-bound?

DRAM (memory) throughput percent and SM (compute) throughput percent; whichever is higher is the limiting roof.

QWhy run warm-up iterations before timing?

The first calls pay for kernel JIT or module loading, cuBLAS/cuDNN autotuning and allocator growth; these one-off costs would otherwise dominate.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All six subtopics marked completed.
  • Lessons l1 and l2 deliverables saved with busy fractions and throughput percentages recorded.
  • Can look at an unfamiliar trace and state within two minutes whether it is launch-bound, memory-bound or compute-bound.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →