Pidoku

GPU Profiling with Nsight

Module 22 Lesson 22.h 1h 30m Difficulty 4/5

Prerequisites 6.d, 22.a

6.d teaches the tools: how to read a Nsight Systems timeline and a Nsight Compute kernel report. This lesson is a recipe book for inference: profiling a live engine, finding the gaps in a decode step, seeing inside CUDA graphs, one kernel in depth, and many GPUs at once.


Before you start: words you need#

WordPlain meaning
nsysThe Nsight Systems command line: records a timeline of CPU threads, CUDA calls, kernels, copies and NVTX ranges. Low overhead.
ncuThe Nsight Compute command line: replays individual kernels many times to read every hardware counter. High overhead.
NVTX rangeA named span you put in code (“decode_step”) that shows up as a labelled bar in the timeline.
Capture rangeTelling nsys to record only between a start and stop signal, so the trace holds the steps you care about and not start-up.
CUDA graphA recorded sequence of kernels launched with one call (5.f). By default a profiler shows it as one block.
GPU busy %Share of wall-clock time during which at least one kernel was running. The first number to get from any timeline.
RankOne GPU’s process in a multi-GPU job.
RecipeA ready-made nsys analysis script (nsys recipe <name>) that computes a summary from one or many reports.

1. What is it?#

Six recipes that cover most inference profiling:

RECIPE 1  Profile a live vLLM server for a few seconds           nsys + capture range
RECIPE 2  Profile your own decode loop with NVTX                 nsys + cudaProfilerApi
RECIPE 3  Compute GPU busy % and find the gaps                    nsys stats / recipes / SQLite
RECIPE 4  One kernel in depth                                      ncu on a microbenchmark
RECIPE 5  Many GPUs: tensor parallelism and collectives           nsys + NCCL tracing
RECIPE 6  The PyTorch profiler, when Nsight is too heavy          torch.profiler / vLLM endpoints

Current versions: Nsight Systems 2026.6.1 (CUDA 13.5 support, NCCL operations shown as one range per operation, a new nccl_pace recipe) and Nsight Compute 2026.4 (4 November 2026, CUDA 13.5). Facts checked on 12 November 2026.


2. Why does it matter?#

Because steps 3 to 5 of the method (22.a) need evidence that only a profiler gives: whether the GPU is idle between kernels, which kernels dominate, and why one of them is slow. And inference engines are awkward to profile: they run several processes, launch most kernels from CUDA graphs, and run for hours, so the naive nsys profile python serve.py produces a huge trace of start-up and one opaque block per decode step.


3. Simple analogy#

A security camera system. You do not record a whole year and watch it. You set the cameras to record when something triggers them (capture range), you label the rooms (NVTX), you switch on the camera inside the vault when the vault matters (graph node tracing), and when one room looks wrong you send an investigator in person (Nsight Compute). Recording everything all the time just buries the event you need.


4. Tiny example: one number from one trace#

Shell
nsys profile -t cuda,nvtx --cuda-graph-trace=node \
  --capture-range=cudaProfilerApi -o decode python bench_decode.py
nsys recipe cuda_gpu_time_util_map --input decode.nsys-rep

Ten decode steps, 95 ms of wall clock, 41 ms with a kernel running: GPU busy 43%. The GPU is idle more than half of every step. The answer is not in any kernel; it is in the CPU rows and the gaps (22.c host-bound, 22.i). That one number decides what to do next.


5. Technical explanation#

Recipe 1: a live vLLM server#

vLLM’s profiling guide gives this command (check it against your version’s guide):

Shell
VLLM_WORKER_MULTIPROC_METHOD=spawn nsys profile \
    --trace-fork-before-exec=true \
    --cuda-graph-trace=node \
    --capture-range=cudaProfilerApi \
    --capture-range-end repeat \
    -o vllm_trace \
    vllm serve meta-llama/Llama-3.1-8B-Instruct --profiler-config.profiler cuda

Then trigger capture from the client, with a handful of requests:

Shell
vllm bench serve --model meta-llama/Llama-3.1-8B-Instruct \
  --dataset-name random --random-input-len 1024 --random-output-len 128 \
  --num-prompts 16 --profile

What each part does:

  • spawn and --trace-fork-before-exec make nsys follow the engine-core and worker processes.
  • --cuda-graph-trace=node shows the kernels inside each CUDA graph instead of one block per replay. Without it, a decode step looks like one long kernel.
  • --capture-range=cudaProfilerApi with repeat records only while the server’s profiler is started (by --profile or POST /start_profile and /stop_profile), and allows several windows.

vLLM’s documentation adds that profiling is for developers; do it on a test replica, not one taking production traffic.

Recipe 2: your own decode loop#

Python
import torch
import torch.cuda.nvtx as nvtx

for _ in range(20):                      # warm up: compilation, graph capture, autotuning
    engine.step()
torch.cuda.synchronize()

torch.cuda.profiler.start()              # capture starts here
for i in range(10):
    with nvtx.range(f"step_{i}"):
        with nvtx.range("schedule"):  plan = engine.schedule()
        with nvtx.range("prepare"):   batch = engine.prepare(plan)
        with nvtx.range("forward"):   logits = engine.forward(batch)
        with nvtx.range("sample"):    toks = engine.sample(logits)
        with nvtx.range("update"):    engine.update(toks)
torch.cuda.synchronize()
torch.cuda.profiler.stop()
Shell
nsys profile -t cuda,nvtx,osrt --cuda-graph-trace=node \
  --capture-range=cudaProfilerApi --capture-range-end=stop \
  --python-sampling=true \
  -o decode python bench_decode.py

--python-sampling=true adds Python call stacks sampled on the CPU rows, so a gap can be traced to the Python function running during it. --pytorch=autograd-nvtx adds NVTX ranges for PyTorch operators automatically if you cannot edit the code. Leave the NVTX ranges in the code permanently: they cost almost nothing when no profiler is attached.

Recipe 3: GPU busy % and the gaps#

The quick way:

Shell
nsys stats --report cuda_gpu_kern_sum --report cuda_api_sum decode.nsys-rep
nsys recipe cuda_gpu_time_util_map --input decode.nsys-rep     # busy % over time, per GPU
nsys recipe nvtx_gpu_proj_sum --input decode.nsys-rep          # GPU time under each NVTX range

The exact way, from the SQLite export (nsys export --type sqlite decode.nsys-rep). Kernels on different streams can overlap, so take the union of intervals rather than the sum:

Python
import sqlite3
con = sqlite3.connect("decode.sqlite")
rows = con.execute(
    "SELECT start, end FROM CUPTI_ACTIVITY_KIND_KERNEL ORDER BY start").fetchall()

busy, cur_s, cur_e = 0, *rows[0]
for s, e in rows[1:]:
    if s > cur_e:                      # a gap: close the current busy interval
        busy += cur_e - cur_s
        cur_s, cur_e = s, e
    else:                              # overlap: extend it
        cur_e = max(cur_e, e)
busy += cur_e - cur_s
wall = rows[-1][1] - rows[0][0]        # better: the NVTX step range's duration
print(f"GPU busy {100*busy/wall:.1f}%   idle {(wall-busy)/1e6:.1f} ms")
busy above ~90%   → GPU-bound. Go to the kernel table (22.b) and Recipe 4.
busy 50–90%       → partly host-bound. Look at the gaps' position: between steps (scheduler,
                    sampling, Python) or inside steps (launches, syncs).
busy below 50%    → host-bound or waiting. Read the CPU rows, the CUDA API row and the NCCL rows.

Then read the API summary. In steady-state decode with graphs on, expect a few cudaGraphLaunch calls per step and few cudaLaunchKernel calls. Thousands of cudaLaunchKernel calls per step mean graphs are not being used (capture failed, or eager mode is on). Any cudaStreamSynchronize or cudaMemcpy device-to-host in the middle of a step is an implicit sync (.item(), .cpu(), .tolist()).

Recipe 4: one kernel in depth#

Never point ncu at a serving process: it serialises and replays every profiled kernel, and the server appears to hang. Isolate the kernel in a small script with the real shapes, then:

Shell
ncu --set full \
    --kernel-name regex:"attention|flash" \
    --launch-skip 20 --launch-count 3 \
    -o attn python microbench_attention.py
  • --launch-skip passes warm-up launches; --launch-count limits the work.
  • Kernels inside CUDA graphs are profiled as individual kernel nodes by default. --graph-profiling graph profiles a whole graph as one workload instead, which keeps caches warm between nodes and gives a more realistic picture of the graph as it really runs.
  • Read it as 6.d teaches: speed of light (compute vs memory throughput), occupancy, memory workload analysis, warp stall reasons, and the roofline chart.

For scripting, request specific metrics and --csv. Metric names change between GPU generations; ncu --query-metrics lists the ones your GPU supports.

Recipe 5: many GPUs#

Shell
nsys profile -t cuda,nvtx,nccl --cuda-graph-trace=node \
  --trace-fork-before-exec=true -o tp_trace \
  torchrun --nproc_per_node=4 bench_tp.py

nsys recipe nccl_sum --input tp_trace.nsys-rep                 # time per collective type
nsys recipe nccl_gpu_overlap_trace --input tp_trace.nsys-rep   # compute/communication overlap
nsys recipe nccl_pace --input tp_trace.nsys-rep                # progress across ranks and steps

For multi-node jobs, write one report per process (-o trace_%q{RANK} uses an environment variable in the file name) and pass the directory to the recipes. What to look for:

1. Collective time per step, per rank      should be similar across ranks
2. Gaps before a collective on one rank    that rank arrived late: more work, CPU contention,
                                           or a slower link
3. Collective time vs compute between      your tensor-parallel overhead, measured; compare
   collectives                             with the prediction from 9.g
4. Ranks in lockstep                       in the multi-row timeline, collectives should line up

A rank that is consistently late at collectives is load imbalance or CPU contention on that rank’s host thread (common when rank 0 also runs the scheduler), or a topology problem (22.k, case 5).

Recipe 6: the PyTorch profiler#

6.d covers the API. For an engine, profile engine steps, not one forward pass, with a schedule that skips warm-up, and group by input shape:

Python
from torch.profiler import profile, schedule, ProfilerActivity
with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],
             schedule=schedule(skip_first=10, wait=1, warmup=2, active=5),
             record_shapes=True) as prof:
    for _ in range(20):
        engine.step()
        prof.step()
print(prof.key_averages(group_by_input_shape=True)
          .table(sort_by="cuda_time_total", row_limit=15))
prof.export_chrome_trace("steps.json")      # open in https://ui.perfetto.dev

Grouping by shape shows when one shape (the largest prefill chunk, or a batch size without a captured graph) is disproportionately expensive. On a vLLM server, --profiler-config with "profiler": "torch" plus POST /start_profile and /stop_profile produces the same traces (19.d). Holistic Trace Analysis reads many such traces at once and summarises idle time, kernel breakdown and communication overlap per rank.


6. Under the hood: why the recipes are needed#

  • Graphs hide kernels. A replayed graph is one cudaGraphLaunch on the CPU and, by default, one block on the GPU row. --cuda-graph-trace=node asks CUPTI (the CUDA profiling interface) for per-node records, at some extra overhead. Decode in modern engines runs almost entirely from graphs, so without it you cannot see which kernel is slow.
  • Engines are multi-process. vLLM runs an API server, an engine core and one worker per GPU (16.d). nsys must follow child processes, and the CUDA work happens in the workers.
  • Tracing has a cost. nsys adds a few to around fifteen per cent depending on what is traced (CPU sampling and per-node graph tracing cost the most). ncu replays each kernel tens of times and can slow a program by 10–100x or more. Keep nsys windows short and ncu off servers.
  • GPU metrics in the timeline. --gpu-metrics-devices=all samples hardware counters (SM activity, DRAM bandwidth, NVLink and PCIe traffic) into rows under the timeline at a fixed rate, so you can see bandwidth drop during a gap. It uses the same counters as DCGM profiling (22.d); pause one to use the other.

What a healthy decode profile looks like#

DECODE STEP, batch 64, a well-tuned engine:

GPU busy                       above 90%
Weight GEMMs                   largest share of GPU time; near the bandwidth floor (22.b)
Attention                      grows with context; often the second largest
Norms, activations, sampling   small; a few per cent each
NCCL (with TP)                 below ~15% of the step on NVLink
cudaGraphLaunch                a few per step
cudaLaunchKernel               few in steady-state decode
Device-to-host copies          one small one per step (the sampled tokens)

RED FLAGS
✗ GPU busy below 70%           → host-bound or waiting
✗ thousands of cudaLaunchKernel → graphs not active
✗ several syncs per step        → implicit syncs in Python
✗ a kernel you do not recognise taking 20% or more
✗ NCCL above ~30% of the step   → topology problem or TP too high (14.m)

The percentages are typical, not targets. Keep a reference profile per release and compare against your own, not against this list.


7. Performance implications#

  • Profiling changes timing. Measure performance with profilers off; use traces to explain numbers, not to produce them.
  • Graph node tracing slows graphs. Short kernels inside graphs look a little longer than they are. Compare relative shares, not absolute microseconds.
  • The first steps lie. JIT compilation, autotuning, allocator growth and graph capture all happen early. Capture ranges after warm-up avoid them.
  • Shapes matter. A microbenchmark with batch 1 and 128 tokens of context profiles different kernels from production batch 64 and 8k context.

8. Production implications#

  • Keep NVTX ranges in the engine permanently.
  • Profile in the deployment container, with the same driver, CUDA and library versions.
  • Keep a reference trace per release and diff kernel summaries between releases; it finds regressions in minutes.
  • Use a test replica fed with a slice of mirrored or replayed traffic for live profiling.
  • Automate GPU busy % on a nightly benchmark and alert on drops.
  • Never run ncu against production.

9. Common mistakes#

  1. Profiling without warm-up. The trace is all JIT, autotuning and allocator growth.
  2. Forgetting --cuda-graph-trace=node. Decode looks like one giant kernel.
  3. Profiling only the parent process. The kernels run in worker processes.
  4. Running ncu on a server. It appears to hang.
  5. Summing kernel times across streams and getting a “busy” figure above 100%.
  6. Reading only the kernel summary and ignoring the gaps.
  7. Comparing traces from different driver or library versions and blaming your code.
  8. Profiling one rank of a multi-GPU job and missing the imbalance.

10. Hands-on exercise#

  1. Live server. Run Recipe 1 against a small model. Find one decode step in the timeline and list its kernels with and without --cuda-graph-trace=node.
  2. GPU busy %. Compute it with cuda_gpu_time_util_map and with the SQLite script for the same trace. Do they agree?
  3. Find a sync. Add a .item() to a decode loop. Find it in the CUDA API row and in the Python samples. Measure its cost; remove it.
  4. One kernel. Take the attention kernel from your trace, reproduce its shapes in a microbenchmark, and run Recipe 4. Is it memory-bound and near its roof?
  5. Multi-GPU. Profile a TP=2 or TP=4 run with Recipe 5. What share of the step is NCCL? Does it match the 9.g estimate?
  6. Regression drill. Profile before and after disabling CUDA graphs. Diff the cuda_api_sum tables. How quickly could you tell what changed?

11. Interview questions#

  1. How would you profile a running vLLM server without capturing start-up?
  2. Why does a decode step appear as one block in a default Nsight Systems trace, and how do you see inside it?
  3. How do you compute GPU busy %, and why not by summing kernel durations?
  4. What would you expect to see in the CUDA API summary of a healthy decode loop?
  5. Why can you not run Nsight Compute against a production server?
  6. In a multi-GPU trace, one rank always reaches the all-reduce last. What are the likely causes?
  7. When would you use the PyTorch profiler instead of Nsight?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in