Workload Profiling
Quick Reference
Pick ONE path based on the workload type:
| Workload |
Approach |
Section |
| Training loop |
Manual torch.cuda.synchronize() + time.perf_counter() with warmup |
Loop Workloads — Manual Timing |
| Single kernel or op |
Write CUDA event benchmark (pre-allocate, warmup, event pairs) |
Non-Loop Workloads — CUDA Event Benchmarking |
| Add timeline labels for nsys |
Use @nvtx.annotate decorator or context manager |
NVTX Reference |
Principles
- Measure, don't guess. Every performance claim must trace back to profiler output or structured measurement data. Never invent metrics.
- Isolate steady-state. Warmup costs (CUDA context init, cuDNN autotuning, JIT compilation) distort measurements. Always exclude warmup iterations before collecting data.
- Use hardware timing. CUDA events measure GPU time precisely. CPU timers (
time.perf_counter()) include host overhead and miss asynchronous execution.
- No sync inside measurement loops. Each
torch.cuda.synchronize() adds 10-50us overhead. Record CUDA events asynchronously, sync once at the end.
- Pre-allocate everything. Tensors, events, compiled kernels — all before the timing loop. For CuTe DSL kernels, pre-compile with
cute.compile().
- Minimize profiler interference. Start with lightweight measurement (manual timing for latency/throughput) and escalate to heavier tools (Kineto, nsys, ncu) only when lighter tools cannot answer the question.
Loop Workloads — Manual Timing
For training loops and iterative workloads, use manual torch.cuda.synchronize() + time.perf_counter() timing with warmup to measure per-iteration latency, throughput, and data load time.
Injection Template
Read the user's training script, understand the dataloader and loop structure, then inject timing code.
import time
import torch
WARMUP = 5
NUM_ITERS = 30
BATCH_SIZE = 128 # global batch size for throughput calculation
iter_times = []
data_times = []
for i, batch in enumerate(dataloader):
if i >= WARMUP + NUM_ITERS:
break
t_data_end = time.perf_counter()
torch.cuda.synchronize()
t_start = time.perf_counter()
# ... existing training loop body ...
torch.cuda.synchronize()
t_end = time.perf_counter()
if i >= WARMUP:
iter_ms = (t_end - t_start) * 1000
iter_times.append(iter_ms)
if i > 0:
data_times.append((t_data_end - prev_iter_end) * 1000)
print(f"[{i:04d}]: iter {iter_ms:.2f} ms, fps {BATCH_SIZE / (iter_ms / 1000):.2f}")
prev_iter_end = t_end
import statistics
print(f"Average: iter {statistics.mean(iter_times):.2f} ms, "
f"fps {BATCH_SIZE / (statistics.mean(iter_times) / 1000):.2f}")
Interpreting Results
- iter (ms): Wall-clock time per iteration (compute + communication, excluding data loading)
- data (ms): Time spent in dataloader between iterations. If
data / iter > 0.2, data loading is a bottleneck.
- fps: Global throughput in samples/second. Use with known FLOPs-per-sample to compute MFU.
Limitations
Manual timing reports aggregate iteration timing — not per-sub-phase breakdown (forward, backward, optimizer). When the user asks where time is spent within compute:
- Add
torch.cuda.synchronize() + time.perf_counter() around each sub-phase for a one-off diagnosis, OR
- Add NVTX annotations and run with
nsys profile for timeline visualization.
Non-Loop Workloads — CUDA Event Benchmarking
For single kernels, one-shot inference, or standalone operations, write CUDA event benchmarking code directly.
PyTorch: Simple (Mean Only)
import torch
def benchmark(fn, warmup=50, iters=100):
for _ in range(warmup):
fn()
torch.cuda.synchronize()
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
for _ in range(iters):
fn()
end.record()
torch.cuda.synchronize()
return start.elapsed_time(end) / iters # ms per iteration
PyTorch: Detailed (Per-Iteration Stats)
import torch
import statistics
def benchmark_detailed(fn, warmup=50, iters=100):
for _ in range(warmup):
fn()
torch.cuda.synchronize()
starts = [torch.cuda.Event(enable_timing=True) for _ in range(iters)]
ends = [torch.cuda.Event(enable_timing=True) for _ in range(iters)]
for i in range(iters):
starts[i].record()
fn()
ends[i].record()
torch.cuda.synchronize()
times = [starts[i].elapsed_time(ends[i]) for i in range(iters)]
return {
"mean_ms": statistics.mean(times),
"median_ms": statistics.median(times),
"std_ms": statistics.stdev(times) if len(times) > 1 else 0,
"min_ms": min(times),
"max_ms": max(times),
}
Anti-Patterns
| Anti-Pattern |
Problem |
torch.cuda.synchronize() before AND after each iteration |
Adds ~10-50us overhead per iteration |
time.perf_counter() for GPU timing |
Measures CPU time, misses async GPU execution |
| Missing warmup |
First iterations include JIT, clock ramp-up, context init |
| Allocating tensors inside measurement loop |
Allocation overhead pollutes timing |
| Reporting only mean |
Hides variance, outliers, bimodal distributions |
For additional benchmarking templates (CUDA Graph, CuTe DSL, Triton, Raw CUDA), see references/benchmarking-patterns.md.
NVTX Reference
NVTX (NVIDIA Tools Extension) adds named annotations to profiler timelines. Use NVTX to label phases (forward, backward, optimizer) for readability in nsys — not for measurement.
import nvtx
# Decorator — annotates every call
@nvtx.annotate("training_step", color="blue")
def training_step():
...
# Context manager — annotates a code block
with nvtx.annotate("data_loading", color="green"):
batch = next(dataloader)
- Do annotate training phases (forward, backward, optimizer, data loading) for nsys timeline clarity.
- Do not annotate for measurement — use CUDA events or manual timing instead.
- Do not over-annotate — too many fine-grained ranges add visual clutter and minor overhead.
For NVTX domains, categories, payloads, and legacy API details, see references/nvtx-api.md.
References
- references/benchmarking-patterns.md — CUDA Graph, CuTe DSL, Triton, Raw CUDA templates; warmup guidance; GPU hardware properties; reporting format
- references/nvtx-api.md — Domains, categories, payloads, legacy push/pop API
- references/pytorch-profiler-api.md — PyTorch 2.0+ profiler API changes (
device_time vs deprecated cuda_time)
1---2name: nvidia-tensorrt-llm-perf-workload-profiling3description: Code instrumentation for timing workloads. Two scenarios: (1) Training loop — inject manual timing to report per-iteration latency, throughput (samples/sec), and data load time. (2) Standalone kernel/op — write CUDA event timing code with warmup, per-iteration statistics, and anti-pattern avoidance. Also covers NVTX annotation for labeling profiler timelines. NOT for: running or analyzing profiler tools (nsys, ncu, Nsight Systems, Nsight Compute), writing kernels (Triton, CuTe, CUDA), applying optimizations (CUDA Graphs, gradient checkpointing, fusion), or interpreting roofline/SOL% metrics. Triggers: "measure throughput", "benchmark this function", "time my training loop", "samples per second", "NVTX annotate", "instrument my dataloader", "data load time", "kernel timing", "how do I time".4license: Apache-2.05---67# Workload Profiling89## Quick Reference1011Pick ONE path based on the workload type:1213| Workload | Approach | Section |14|----------|----------|---------|15| Training loop | Manual `torch.cuda.synchronize()` + `time.perf_counter()` with warmup | Loop Workloads — Manual Timing |16| Single kernel or op | Write CUDA event benchmark (pre-allocate, warmup, event pairs) | Non-Loop Workloads — CUDA Event Benchmarking |17| Add timeline labels for nsys | Use `@nvtx.annotate` decorator or context manager | NVTX Reference |1819## Principles2021- **Measure, don't guess.** Every performance claim must trace back to profiler output or structured measurement data. Never invent metrics.22- **Isolate steady-state.** Warmup costs (CUDA context init, cuDNN autotuning, JIT compilation) distort measurements. Always exclude warmup iterations before collecting data.23- **Use hardware timing.** CUDA events measure GPU time precisely. CPU timers (`time.perf_counter()`) include host overhead and miss asynchronous execution.24- **No sync inside measurement loops.** Each `torch.cuda.synchronize()` adds 10-50us overhead. Record CUDA events asynchronously, sync once at the end.25- **Pre-allocate everything.** Tensors, events, compiled kernels — all before the timing loop. For CuTe DSL kernels, pre-compile with `cute.compile()`.26- **Minimize profiler interference.** Start with lightweight measurement (manual timing for latency/throughput) and escalate to heavier tools (Kineto, nsys, ncu) only when lighter tools cannot answer the question.2728## Loop Workloads — Manual Timing2930For training loops and iterative workloads, use manual `torch.cuda.synchronize()` + `time.perf_counter()` timing with warmup to measure per-iteration latency, throughput, and data load time.3132### Injection Template3334Read the user's training script, understand the dataloader and loop structure, then inject timing code.3536```python37import time38import torch3940WARMUP = 541NUM_ITERS = 3042BATCH_SIZE = 128 # global batch size for throughput calculation4344iter_times = []45data_times = []4647for i, batch in enumerate(dataloader):48 if i >= WARMUP + NUM_ITERS:49 break5051 t_data_end = time.perf_counter()5253 torch.cuda.synchronize()54 t_start = time.perf_counter()5556 # ... existing training loop body ...5758 torch.cuda.synchronize()59 t_end = time.perf_counter()6061 if i >= WARMUP:62 iter_ms = (t_end - t_start) * 100063 iter_times.append(iter_ms)64 if i > 0:65 data_times.append((t_data_end - prev_iter_end) * 1000)66 print(f"[{i:04d}]: iter {iter_ms:.2f} ms, fps {BATCH_SIZE / (iter_ms / 1000):.2f}")6768 prev_iter_end = t_end6970import statistics71print(f"Average: iter {statistics.mean(iter_times):.2f} ms, "72 f"fps {BATCH_SIZE / (statistics.mean(iter_times) / 1000):.2f}")73```7475### Interpreting Results7677- **iter (ms)**: Wall-clock time per iteration (compute + communication, excluding data loading)78- **data (ms)**: Time spent in dataloader between iterations. If `data / iter > 0.2`, data loading is a bottleneck.79- **fps**: Global throughput in samples/second. Use with known FLOPs-per-sample to compute MFU.8081### Limitations8283Manual timing reports **aggregate** iteration timing — not per-sub-phase breakdown (forward, backward, optimizer). When the user asks **where time is spent within compute**:84851. Add `torch.cuda.synchronize()` + `time.perf_counter()` around each sub-phase for a one-off diagnosis, OR862. Add NVTX annotations and run with `nsys profile` for timeline visualization.8788## Non-Loop Workloads — CUDA Event Benchmarking8990For single kernels, one-shot inference, or standalone operations, write CUDA event benchmarking code directly.9192### PyTorch: Simple (Mean Only)9394```python95import torch9697def benchmark(fn, warmup=50, iters=100):98 for _ in range(warmup):99 fn()100 torch.cuda.synchronize()101102 start = torch.cuda.Event(enable_timing=True)103 end = torch.cuda.Event(enable_timing=True)104105 start.record()106 for _ in range(iters):107 fn()108 end.record()109 torch.cuda.synchronize()110111 return start.elapsed_time(end) / iters # ms per iteration112```113114### PyTorch: Detailed (Per-Iteration Stats)115116```python117import torch118import statistics119120def benchmark_detailed(fn, warmup=50, iters=100):121 for _ in range(warmup):122 fn()123 torch.cuda.synchronize()124125 starts = [torch.cuda.Event(enable_timing=True) for _ in range(iters)]126 ends = [torch.cuda.Event(enable_timing=True) for _ in range(iters)]127128 for i in range(iters):129 starts[i].record()130 fn()131 ends[i].record()132133 torch.cuda.synchronize()134 times = [starts[i].elapsed_time(ends[i]) for i in range(iters)]135136 return {137 "mean_ms": statistics.mean(times),138 "median_ms": statistics.median(times),139 "std_ms": statistics.stdev(times) if len(times) > 1 else 0,140 "min_ms": min(times),141 "max_ms": max(times),142 }143```144145### Anti-Patterns146147| Anti-Pattern | Problem |148|--------------|---------|149| `torch.cuda.synchronize()` before AND after each iteration | Adds ~10-50us overhead per iteration |150| `time.perf_counter()` for GPU timing | Measures CPU time, misses async GPU execution |151| Missing warmup | First iterations include JIT, clock ramp-up, context init |152| Allocating tensors inside measurement loop | Allocation overhead pollutes timing |153| Reporting only mean | Hides variance, outliers, bimodal distributions |154155For additional benchmarking templates (CUDA Graph, CuTe DSL, Triton, Raw CUDA), see [references/benchmarking-patterns.md](references/benchmarking-patterns.md).156157## NVTX Reference158159NVTX (NVIDIA Tools Extension) adds named annotations to profiler timelines. Use NVTX to label phases (forward, backward, optimizer) for readability in nsys — not for measurement.160161```python162import nvtx163164# Decorator — annotates every call165@nvtx.annotate("training_step", color="blue")166def training_step():167 ...168169# Context manager — annotates a code block170with nvtx.annotate("data_loading", color="green"):171 batch = next(dataloader)172```173174- **Do** annotate training phases (forward, backward, optimizer, data loading) for nsys timeline clarity.175- **Do not** annotate for measurement — use CUDA events or manual timing instead.176- **Do not** over-annotate — too many fine-grained ranges add visual clutter and minor overhead.177178For NVTX domains, categories, payloads, and legacy API details, see [references/nvtx-api.md](references/nvtx-api.md).179180## References181182- [references/benchmarking-patterns.md](references/benchmarking-patterns.md) — CUDA Graph, CuTe DSL, Triton, Raw CUDA templates; warmup guidance; GPU hardware properties; reporting format183- [references/nvtx-api.md](references/nvtx-api.md) — Domains, categories, payloads, legacy push/pop API184- [references/pytorch-profiler-api.md](references/pytorch-profiler-api.md) — PyTorch 2.0+ profiler API changes (`device_time` vs deprecated `cuda_time`)