Instrument a training workload with NVTX ranges.
Capture an Nsight profile with nsys profile.
Find the bottleneck by parsing the NVTX range report.
Apply a profile-driven fix and measure the gain. Our run: profile-driven optimization: 25.55 ms/step -> 9.13 ms/step (2.80x speedup)
Intermediate · on a real NVIDIA GPU
Nsight Systems Profiling: Finding the Bottleneck That Costs You 40% of Your GPU
Run the full profile-then-fix loop with NVIDIA Nsight Systems, instrument a training loop with NVTX ranges, capture a .nsys-rep, parse the NVTX summary to pinpoint the bottleneck, then apply a targeted fix and measure the speedup.
$29.99 a month with Pro. It opens this lab and every other one. Cancel any time.
The 4 steps
each one checked
A check runs your work at the end of every step. Hints and the full solution are there if you get stuck.
- 1
Instrument a training workload with NVTX ranges
Read this step
Metrics (Lab I-1) tell you something is slow. Profiling tells you exactly which nanosecond is slow. NVIDIA Nsight Systems (
nsys) is the timeline-level profiler that's standard in every serious CUDA shop — it records every CUDA API call, every kernel launch, every memory copy, every NVTX range, and renders them on a unified timeline you can zoom into.This lab teaches the profile-then-optimize workflow on a deliberately suboptimal training loop. You'll find the bottleneck (GPU sits idle waiting for the CPU dataloader), apply a one-line fix, and measure the throughput jump.
Why Nsight Systems and not just
time.perf_counter()?Timing calls measure wall-clock time across the whole step. Nsight measures:
- CUDA kernel execution time per kernel, aggregated (you can see which kernel eats the most GPU time)
- Launch gaps — time between the end of one kernel and the start of the next, which is either CPU overhead or a sync barrier
- Memory transfers (H2D/D2H) overlapped or not with compute
- CPU thread activity — are Python worker threads blocked on the GIL?
- NVTX ranges you annotate your code with (
torch.cuda.nvtx.range_push/pop) so you see logical phases (forward, backward, optimizer)
Two modes we'll use:
nsys profile --stats=true ...— produces a.nsys-repreport + prints summary stats to stdout. What you'll use 95% of the time.- Nsight Systems GUI — open the
.nsys-repin the desktop app for the interactive timeline. Not demonstrated here (no display), but mention in the references.
References
- Nsight Systems User Guide — the complete reference.
- Karpathy — Recipe for Training Neural Networks — not Nsight-specific but makes the case that profiling before optimizing is non-negotiable.
- NVTX ranges in PyTorch — how we'll annotate phases.
- "GPU Performance Background" — NVIDIA deep-learning perf guide — the mental model you need before reading a profile.
Without NVTX, an Nsight profile is a sea of
cudaLaunchKernelevents. With NVTX ranges, you see your code's logical phases ("data_load", "forward", "backward", "optimizer") as colored bars on the timeline. Every serious CUDA project ships with NVTX.We'll write a small training script with NVTX annotations, save it to a file, and verify
nsysis on the PATH.import subprocess, os # Confirm nsys is available nsys_result = subprocess.run(['nsys', '--version'], capture_output=True, text=True) nsys_version = nsys_result.stdout.strip() print(f'nsys version: {nsys_version}') # The workload we'll profile lives at workspace/scripts/bad_training.py. It's a # deliberately-bad training loop: # - CPU-side preprocessing that blocks the main thread each iteration # - Slow host-to-device transfers (non-pinned memory) # - A plain `for`-loop dataloader that does all work synchronously workload_script_path = '/home/labuser/workspace/scripts/bad_training.py' assert os.path.exists(workload_script_path), f'workload script not found at {workload_script_path}' print(f'Workload script: {workload_script_path} ({os.path.getsize(workload_script_path)} bytes)')from IPython.display import Code Code(filename='/home/labuser/workspace/scripts/bad_training.py', language='python') - 2
Capture an Nsight profile with nsys profile
- 3
Find the bottleneck by parsing the NVTX range report
- 4
Apply a profile-driven fix and measure the gain
Before you start
3 things
- PyTorch training loop basics
- Comfortable with subprocess / shell invocation from Python
- Understanding of CPU vs GPU work and pipeline stalls
What you get
- A JupyterLab notebook on a real NVIDIA GPU
- A check at the end of every step
- Hints and the full solution
- Nothing to install or configure
Exam domains covered
NCA-AIIO, NCP-AIO, NCP-GENL, NCP-ADS, NCA-GENL, NCA-GENM, NCP-AII, NCA-ADS
The GPU and Kubernetes track
lab 16 of 20
GPU scheduling on your own Kubernetes cluster, the GPU Operator, CUDA kernels and profiling.
- Beginner · 5 min · Kubernetes · ProWelcome to NCA-AIIO Labs: Schedule Your First GPU Pod
- Intermediate · 40 min · NVIDIA GPU · ProNVIDIA GPU Operator on k3s: Single-Node Kubernetes for GPU Workloads
- Intermediate · 35 min · Kubernetes · ProInside the NVIDIA GPU Operator: From Helm to Workload-Ready
- Intermediate · 40 min · Kubernetes · ProKubernetes Resource Requests & Limits: Who Gets What, and Who Survives
- Intermediate · 35 min · Kubernetes · ProMulti-GPU-Type Targeting: nodeSelector, nodeAffinity & Tolerations
- Intermediate · 35 min · Kubernetes · ProPriorityClass & Preemption: Who Survives the GPU Squeeze
- Intermediate · 35 min · Kubernetes · ProWorkload Controllers: Deployment, StatefulSet, DaemonSet for AI
- Intermediate · 35 min · Kubernetes · ProPersistent Storage for AI Workloads: PVCs, StorageClass & the Checkpoint Pattern
- Intermediate · 40 min · NVIDIA GPU · ProGPU Container Lifecycle: Build, Test, Ship, Rollback
- Intermediate · 35 min · Kubernetes · ProRolling Updates, Rollback & Blue-Green for AI Inference
- Intermediate · 40 min · Kubernetes · ProStuck-Pending Triage Day: Diagnose Any GPU Pod That Won't Run
- Intermediate · 40 min · NVIDIA GPU · ProGPU Observability: From nvidia-smi to a Production Monitoring Stack
- Advanced · 50 min · NVIDIA GPU · ProGPU Health Checks + Auto-Remediation
- Advanced · 45 min · NVIDIA GPU · ProCUDA Programming Fundamentals
- Intermediate · 35 min · NVIDIA GPU · ProProfile PyTorch Training with the Built-in Profiler
- this labNsight Systems Profiling: Finding the Bottleneck That Costs You 40% of Your GPU
- Advanced · 45 min · NVIDIA GPU · ProGPU Sharing: Streams, MPS, MIG, and the Real Cost of Contention
- Intermediate · 30 min · NVIDIA GPU · ProNVIDIA DALI: GPU-Accelerated Data Pipelines
- Intermediate · 40 min · NVIDIA GPU · ProGPU-Accelerated Data Science with RAPIDS
- Intermediate · 35 min · NVIDIA GPU · ProGPU Cost & Efficiency Audit
More lab paths
2
Questions about this lab
6 answers
What's the difference between Nsight Systems and PyTorch Profiler?
PyTorch Profiler operates at the torch-op level, aten::conv2d, Optimizer.step, and its main outputs are the key_averages() table and a Chrome trace of torch ops. Nsight Systems operates a layer below that: it traces the CUDA API (cudaLaunchKernel, cudaMemcpy), CUDA stream activity, OS threads, and your NVTX ranges, on a unified timeline. Use PyTorch Profiler to answer 'which op is expensive'; use Nsight Systems to answer 'why is my GPU idle between ops'.
Why NVTX ranges instead of just reading the raw kernel names?
Raw kernel names are anonymous, sm80_xmma_gemm_f16f16_f16f32_... tells you it's a GEMM but not which layer in your model. NVTX markers (torch.cuda.nvtx.range_push('forward')) inject human-readable labels into the CUDA stream, so nsys stats --report=nvtx_sum groups kernels by phase and you immediately see data_load: 140 ms, forward: 22 ms, backward: 31 ms. PyTorch also emits NVTX markers internally for torch ops when the profiler is active, which is why --trace=cuda,nvtx,osrt is the canonical trace set.
Does the lab's fix (pre-allocating data on GPU) work in production?
Absolutely not, it's a teaching device. Pre-loading the full dataset into VRAM is fine on synthetic toy data but fails instantly on ImageNet or any real corpus that doesn't fit in GPU memory. The reflection question at the end asks you to design the real production fix: async DataLoader with num_workers>0, pin_memory=True, non_blocking=True transfers, or a DALI pipeline, so batch N+1 loads while batch N computes. The point of the lab's fix is to prove, with a clean before/after measurement, that the bottleneck was what the profile said it was.
How do I tell from an Nsight timeline whether my CPU-GPU pipeline is overlapped?
On the timeline view, you should see data_load activity on a CPU worker thread running concurrently with forward/backward kernels on the CUDA stream, not before them. If the CUDA stream has a gap that's exactly aligned with a data_load NVTX range on the CPU side, your pipeline is serial. The NVTX ranges are what make this visually obvious; without them, you're squinting at anonymous CPU-thread samples and trying to correlate by wall-clock.
Can I use nsys without opening the desktop Nsight Systems UI?
Yes, that's exactly what Steps 2 and 3 do. nsys profile --stats=true prints a CUDA API summary and kernel summary directly to stdout, and nsys stats --report=nvtx_sum --format=csv emits parseable CSV. You can build the whole automated-profile pipeline (capture, parse, surface the bottleneck, regression-test) from a Python script, which is what a real CI job would do. The GUI adds the pretty interactive timeline, but all the data is in the .nsys-rep file.
What exactly does each step check?
Step 1 verifies nsys_version contains NVIDIA/Nsight branding and that your workload script exists with NVTX markers and a CUDA import. Step 2 requires the .nsys-rep report exists and is >0.5 MB and that the CUDA API summary mentions cudaLaunchKernel/cudaMemcpy. Step 3 parses top_kernels, checks at least 3 of the canonical NVTX ranges are present, and asserts data_load ranks in the top 2. Step 4 computes before_avg_step_ms / after_avg_step_ms and requires the speedup to exceed 1.1×.
What you'll capture in this Nsight Systems lab
about
Most PyTorch training jobs leave 30-50% of GPU time on the floor, and the reason is almost never the model, it's a launch gap, a missed overlap, or a CPU dispatcher that can't keep up. Nsight Systems is how senior engineers find those gaps in minutes instead of weeks. You'll run the full profile-then-fix loop end to end: an instrumented training script with NVTX phase markers, a real .nsys-rep capture, a parsed NVTX summary that names the bottleneck, a targeted fix, and a measured speedup against the original. By the end you'll have a nsys workflow you can paste into a CI job (capture → parse → regression-test) and the mental model that separates CPU-launch-bound from compute-bound from memory-bandwidth-bound workloads. About 35 minutes on a real NVIDIA GPU pod we provision, nsys, the CUDA toolkit, and PyTorch are preinstalled, and you can download the .nsys-rep to open in the Nsight Systems desktop UI.
The technical core is the capture command and what it actually traces: nsys profile --trace=cuda,nvtx,osrt --sample=cpu --stats=true --output=profile.nsys-rep python workload.py. cuda catches cudaLaunchKernel / cudaMemcpyAsync and per-stream kernel execution; nvtx picks up the torch.cuda.nvtx.range_push('forward') markers you injected (and the ones PyTorch emits internally for torch ops); osrt traces OS runtime thread activity so you can see CPU workers blocking on pthread_cond_wait. NVTX is the piece that turns an Nsight trace from anonymous sm80_xmma_gemm_... kernel names into a readable timeline of data_load, forward, backward, optimizer. The headline insight: Nsight shows you the gaps between kernels, stretches where the GPU is idle because the CPU hasn't dispatched the next launch, or because batch N+1 wasn't ready when batch N finished. That's the view PyTorch Profiler structurally cannot give you.
The second insight most engineers miss: the lab's fix (pre-allocating data on GPU) is a teaching device, not a production pattern. Real datasets don't fit in VRAM. The right production fix is async DataLoader with num_workers>0, pin_memory=True, non_blocking=True transfers, or a DALI pipeline, so batch N+1 loads while batch N computes. The reflection forces you to describe what overlap actually looks like on the Nsight timeline: data_load on a CPU worker thread running concurrently with forward/backward kernels on the CUDA stream, not serially before them. That's how you verify from a profile whether the fix worked.
Prereqs: PyTorch training-loop basics, subprocess.run comfort in Python, a working mental model of CPU-GPU pipeline stalls. Preinstalled: nsys CLI, CUDA toolkit, PyTorch, JupyterLab. Grading checks real artifacts: the .nsys-rep must be >0.5 MB (anything smaller means profiling didn't actually run), cuda_api_summary must contain real CUDA API names like cudaLaunchKernel or cudaMemcpy, top_kernels must have data_load ranked in the top 2, and your post-fix step time must be at least 1.1× faster than the baseline, proving the profile-driven diagnosis was correct.