Phase 04/Measure and tune/Nsight Systems and Nsight Compute
PHASE 04 · Measure and tune

Nsight Systems and Nsight Compute

0%
9 h6 subtopics3 lessons · 1 required
In plain English

Guessing why a program is slow usually fails; you have to watch it. NVIDIA ships two watchers. Nsight Systems is a stopwatch on the whole timeline: it shows when the CPU was busy, when the GPU was busy, when each kernel started and stopped, and where the GPU sat idle waiting for instructions. Nsight Compute is a microscope for one kernel: it tells you whether that kernel was limited by arithmetic, memory bandwidth, or poor organization of its threads, and suggests what to fix. Think of a hospital. Nsight Systems is the floor plan with every patient's path through the building, showing where the queues form. Nsight Compute is the detailed audit of one operating room, showing how much of the time the surgeon's hands were actually moving.

Why it matters

Profiling turns optimization from folklore into measurement. An inference engineer uses nsys to find launch gaps, CPU-bound scheduling and synchronization stalls in a serving engine, and ncu to check that an attention or GEMM kernel is near its memory or compute roof. These tools are also the standard evidence in performance PRs to vLLM and SGLang.

Hiring signal

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

Learning objectives

  • Record an nsys timeline of a model running on a GPU and read it to find kernel launch gaps and CPU-side bottlenecks.
  • Use NVTX ranges to label prefill, decode and sampling phases in the timeline.
  • Profile a single kernel with ncu and interpret achieved occupancy, memory throughput and the roofline chart.
  • Diagnose a kernel as memory-bound, compute-bound or latency-bound from its ncu report.
  • Produce a before/after profile that proves an optimization worked.

Key concepts

Nsight Systems (nsys)
System-wide timeline profiler for CPU threads, CUDA API calls, kernels, memcpys and NVTX ranges.
Nsight Compute (ncu)
Kernel-level profiler that replays a kernel to collect hardware counters and produce guided analysis.
NVTX
Lightweight annotation API; torch.cuda.nvtx.range_push/pop labels regions in the nsys timeline.
Launch gap
Idle GPU time between consecutive kernels visible as white space in the CUDA HW row; a sign of CPU-bound or launch-bound execution.
Achieved occupancy
Average active warps per SM divided by the maximum; low values mean too few threads to hide latency.
Memory throughput and compute throughput
ncu's percent-of-peak figures for DRAM bandwidth and SM pipes; whichever is high is the bottleneck.
Kernel replay
ncu reruns the kernel several times with saved and restored memory to collect all counters; it makes profiled runs much slower.
Speed of Light (SOL)
ncu's section comparing achieved throughput to the theoretical maximum of the GPU.
torch.profiler
PyTorch's built-in profiler that emits Chrome traces; a lighter alternative when nsys is unavailable.

Subtopics

  1. 1. Recording a timeline with nsys

    nsys profile with -t cuda,nvtx,osrt, --capture-range for a window, and exporting stats with nsys stats to CSV.

  2. 2. Reading the timeline

    CUDA HW row for kernels, CUDA API row for launches, the gap between them, memcpy rows, and spotting cudaStreamSynchronize stalls.

  3. 3. NVTX annotation of inference phases

    Wrapping prefill, each decode step and sampling in ranges; using emit_nvtx in torch.profiler or torch.cuda.nvtx directly.

  4. 4. Profiling a kernel with ncu

    Selecting a kernel by name or launch index, choosing sections (SpeedOfLight, Occupancy, MemoryWorkloadAnalysis), and reading the report.

  5. 5. Diagnosing the bottleneck

    Memory-bound (high DRAM percent), compute-bound (high SM pipe percent), latency-bound (both low, low occupancy or long dependency chains); what each suggests fixing.

  6. 6. Profiling a serving engine

    Attaching nsys to vLLM with a capture range, finding the scheduler and sampling overhead, and comparing eager versus CUDA Graph timelines.

Resources

Hands-on lessons

L1

nsys timeline of GPT-2 prefill and decode on a T4

Colab T4 · freecli120 minrequired

Goal · Record an annotated nsys profile of a 64-token GPT-2 generation, measure the fraction of GPU idle time during decode, and show it shrinks with CUDA Graphs.

  1. 1Install Nsight Systems on Colab (apt or the .deb from the NVIDIA repo) and confirm nsys --version works.
  2. 2Write gen.py that loads gpt2 in float16 and generates 64 tokens, wrapping prefill and each decode step in torch.cuda.nvtx.range annotations.
  3. 3Run nsys profile -t cuda,nvtx -o eager python gen.py; then nsys stats --report cuda_gpu_kern_sum and --report nvtx_sum eager.nsys-rep.
  4. 4From the stats compute total kernel time inside the decode NVTX ranges versus the total range duration; the difference is GPU idle time.
  5. 5Count the kernels per decode step and the average kernel duration.
  6. 6Repeat with the decode step captured in a CUDA Graph (from the p4-cuda-graphs lesson) and compare the idle fraction.
  7. 7Download the two .nsys-rep files and open them in the Nsight Systems GUI on your Mac; take a screenshot of one decode step from each.
Deliverable
Two .nsys-rep files, the stats CSVs, the idle-fraction numbers and the two screenshots.
Check
Eager decode shows a GPU idle fraction above 30 percent with hundreds of sub-20-microsecond kernels per step; the CUDA Graph run shows the idle fraction cut sharply.
Fallback
Use torch.profiler with record_shapes on CPU and view the Chrome trace in chrome://tracing to measure Python overhead between ops; the structure of the analysis is the same.
L2

Diagnose a memory-bound and a compute-bound kernel with ncu

Colab T4 · freeexperiment90 minoptional

Goal · Profile a large FP16 matmul and an elementwise softmax with Nsight Compute and classify each from its Speed of Light section.

  1. 1Install Nsight Compute on Colab and verify ncu --version; if counter access is denied, follow the ERR_NVGPUCTRPERM note in the docs or fall back to the ncu CLI metrics that are permitted.
  2. 2Write kern.py that runs torch.matmul on (4096, 4096) float16 tensors and torch.softmax on a (4096, 4096) tensor, each once after warmup.
  3. 3Run ncu --section SpeedOfLight --section Occupancy --section MemoryWorkloadAnalysis -k regex:gemm -c 1 python kern.py and save the output; repeat with -k regex:softmax.
  4. 4Record DRAM throughput percent, SM throughput percent and achieved occupancy for both kernels.
  5. 5Classify each kernel as memory-, compute- or latency-bound and write one sentence per kernel on what you would change.
  6. 6Compute the softmax kernel's achieved bandwidth (bytes moved / duration) and compare with the T4 datasheet 320 GB/s.
Deliverable
Two ncu text reports and a short classification table.
Check
The GEMM shows high SM/tensor pipe utilization and the softmax shows high DRAM throughput with low compute; the softmax achieves at least 60 percent of datasheet bandwidth.
Fallback
Read a published ncu report for a GEMM and an elementwise kernel in the Nsight Compute Profiling Guide examples and perform the same classification from the screenshots.
L3

Profile vLLM with a capture range

Colab T4 · freecli90 minoptional

Goal · Capture an nsys trace of a vLLM server handling 16 concurrent requests and locate the scheduler, sampling and kernel time per step.

  1. 1Start vllm serve under nsys profile with --capture-range=cudaProfilerApi and the VLLM_TORCH_PROFILER or the documented profiling environment variables from the vLLM profiling guide.
  2. 2Send 16 concurrent requests from a client and trigger the start and stop profile endpoints.
  3. 3Export nvtx_sum and cuda_gpu_kern_sum with nsys stats; identify the top five kernels by total time.
  4. 4Measure the CPU-side time per step (scheduler and sampling) versus GPU kernel time per step.
  5. 5Write three bullet points on where you would look for the next optimization and why.
Deliverable
The .nsys-rep file, the stats CSVs and the three bullets.
Check
You can name the top attention and GEMM kernels and give the CPU-versus-GPU time split per decode step.
Fallback
Use vLLM's built-in torch.profiler integration on CPU with a tiny model to produce a Chrome trace and perform the same per-step split.

Build your own

Build your own nsys trace analyzer

PythonCPU · your Mac~8 h

A command-line tool that reads Nsight Systems sqlite exports, reconstructs the kernel timeline per NVTX range, finds GPU idle gaps and launch latency, diffs two traces, and emits a Perfetto-compatible timeline, runnable on your Mac.

The real thing: docs.nvidia.com/nsight-systems/UserGuide/index.html ↗

How you know a stage passes

Write tests/test_nsyslite.py first, together with tests/make_trace.py, a generator that writes a small sqlite file with the same tables nsys exports (CUPTI_ACTIVITY_KIND_KERNEL, CUPTI_ACTIVITY_KIND_RUNTIME, NVTX_EVENTS, StringIds) from a list of hand-written kernels and ranges, so every stage has exact expected numbers. Each stage also runs on the two real exports from the p4-nsight-profiling-l1 lesson (eager and CUDA Graph GPT-2 decode, exported with `nsys export --type sqlite`) and compares with `nsys stats` output you saved alongside. `nsyslite <command> trace.sqlite` is the CLI. Run `pytest -q`; a stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01kernel summary
    `nsyslite kernels trace.sqlite --top 10` resolves kernel names through StringIds and prints count, total, mean and max duration per kernel name.
    test · On the synthetic trace the totals equal the generator's constants exactly; on the real eager trace the top kernel's total time matches the saved `nsys stats --report cuda_gpu_kern_sum` within 1 percent.
  2. 02attribute kernels to NVTX ranges
    Kernels are assigned to the NVTX range active on their launching thread at launch time (via correlationId to the runtime call), giving per-range kernel count and GPU busy time.
    test · Synthetic per-range counts are exact; on the real trace the per-decode-step kernel count matches the lesson's number and the per-range busy time matches `nsys stats --report nvtx_kern_sum` within 1 percent.
  3. 03GPU idle gaps
    Within a range, merge overlapping kernel intervals across streams and report total idle time, idle fraction and the ten longest gaps with the kernels on either side.
    test · A synthetic range built with exactly 40 percent idle reports 40.0 within 0.1; on the real traces the eager decode idle fraction is higher than the CUDA Graph one and both numbers are printed.
  4. 04launch latency
    For each kernel, launch latency is the gap from the end of its cudaLaunchKernel runtime call to the kernel's start on the GPU, summarised per range.
    test · Synthetic latencies are recovered exactly; on the real eager trace the median launch latency is reported in microseconds and the test asserts it is positive and below 1 ms.
  5. 05diff two traces
    `nsyslite diff a.sqlite b.sqlite` prints per-kernel-name deltas in count and total time, and per-range deltas in wall time, busy time and idle fraction, sorted by absolute change.
    test · Synthetic deltas are exact; the real eager-versus-graph diff shows the same kernel count per decode step, GPU busy time within 10 percent, and lower wall time per step for the graph trace.
  6. 06export a timeline you can look at
    `nsyslite export trace.sqlite --range decode_step_10 --out step.json` writes Chrome trace-event JSON (kernels as complete events per stream, ranges as a separate track) that opens in ui.perfetto.dev, plus an ASCII waterfall for the terminal.
    test · The JSON parses, has one event per kernel plus one per range in the selected window, and loads in Perfetto; the README contains a screenshot of one eager and one graph decode step rendered from your export.

Knowledge check

QYou see many tiny kernels with white gaps between them in the CUDA HW row. What is the bottleneck and what fixes it?

The run is launch-bound or CPU-bound; CUDA Graphs, kernel fusion or reducing Python overhead fill the gaps.

QIn an ncu report, DRAM throughput is 85 percent of peak and SM throughput is 20 percent. What kind of kernel is this and what would help?

Memory-bound; reduce bytes moved by fusing with neighbors, lowering precision, or improving reuse through tiling.

QWhy does ncu make a program run far slower than nsys does?

ncu replays each profiled kernel many times to collect different hardware counters, saving and restoring memory between passes; nsys only records timestamps.

QWhat does an NVTX range add to a profile?

A named, nested time span on the timeline so you can attribute kernels and gaps to logical phases like prefill, decode step or sampling.

Completion

  • All 6 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 .nsys-rep files and idle-fraction numbers saved with the check passing.
  • Can open an unfamiliar nsys trace and state within ten minutes whether the workload is launch-bound, memory-bound or compute-bound.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →