Phase 04/Measure and tune/Performance instrumentation and profiling tooling
PHASE 04 · Measure and tune

Performance instrumentation and profiling tooling

0%
8 h6 subtopics2 lessons · 2 required
In plain English

A car with no dashboard can still drive, but tuning one without a speedometer and a fuel gauge is guesswork. Instrumentation is the work of building the dashboard into the engine: little timers and counters placed inside the code that record what ran, when, and for how long, without slowing the car down. Done well, every request, kernel and transfer carries a label, and you can replay one slow minute and see exactly which part ate the time. Done badly, the gauges themselves cost speed, lie about what happened, or drown you in numbers nobody reads. This topic is about building gauges that are cheap, honest and actually used.

Why it matters

Nsight profiling teaches you to consume traces; production teams also have to produce them. Fleet-wide performance work starts from the data: which events exist, what they cost, and whether you can trust them. Instrumentation decisions, what to measure, at what overhead, with which correlation ids, decide which investigations are even possible later.

Hiring signal

NVIDIA hires a dedicated performance-instrumentation engineer to define and maintain the performance data requirements and to inform the build of low-overhead instrumentation and annotation APIs; Databricks wants people with experience building instrumentation, tracing, and profiling tools for ML models; Anthropic's capacity team builds performance instrumentation that measures how efficiently every major workload uses the hardware it runs on.

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

Learning objectives

  • Explain the trace data model (events, ranges, spans, correlation ids) and how torch.profiler, NVTX and CUPTI fit together.
  • Annotate PyTorch code with NVTX ranges and record_function so an nsys or chrome trace reads like the request lifecycle.
  • Measure and minimize instrumentation overhead, and choose between tracing, sampling and aggregation per question.
  • Design a small telemetry schema with validation so gaps and bad data are caught before analysis.
  • Build and export traces in the Chrome trace-event format and answer timing questions from them programmatically.

Key concepts

Instrumentation
Code added to a system to emit measurements (timestamps, counters, metadata) about its own execution.
NVTX
NVIDIA Tools Extension; a tiny C/Python API whose range annotations show up as named ranges in Nsight traces.
CUPTI
The CUDA Profiling Tools Interface underneath Nsight; collects kernel launches, memory copies and driver API events with correlation ids.
Correlation id
An identifier tying a host-side event (API call, request) to the GPU work it caused, so a trace connects cause and effect.
Observer effect
The slowdown and distortion caused by measuring; the reason instrumentation is budgeted in microseconds per event.
Tracing vs sampling vs aggregation
Recording every event, recording stacks periodically, or recording only counters; the three cost versus detail trade-offs.
Chrome trace-event format
The JSON schema behind chrome://tracing and Perfetto; the de-facto interchange format for timelines.
Telemetry schema and validation
Named fields, units and invariants for emitted data, plus checks that reject missing or implausible values at ingestion.

Subtopics

  1. 1. The trace data model

    Events, durations, instant markers, counters, flows and correlation ids; why a request-id that reaches the GPU is the most valuable field you can add.

  2. 2. Annotation APIs, NVTX and record_function

    nvtx ranges in Python, torch.autograd.profiler.record_function, naming conventions, and where annotations land in nsys and torch.profiler traces.

  3. 3. Under the hood, CUPTI and Nsight

    How nsys reads CUPTI activity records, what gets collected at the driver API level, and what is invisible without source annotation.

  4. 4. Overhead and observer effects

    Measuring per-event cost, tracing versus sampling versus aggregation, and setting an instrumentation budget for a production path.

  5. 5. Telemetry pipelines and data quality

    Schema contracts, validation at ingestion, finding visibility gaps with concrete cannot-diagnose-this evidence, and conventions other teams can rely on.

  6. 6. Turning traces into answers

    Exporting chrome-trace JSON, computing self-time and critical-path tables, and building the smallest view that answers where the time went for one request.

Resources

repo
documentation

Hands-on lessons

L1

Build a mini NVTX-style tracer

CPU · your Macscript120 minrequired

Goal · A small Python tracing library that records nested ranges with correlation ids and exports valid Chrome trace-event JSON.

  1. 1Design the event model, begin and end events forming ranges, instant markers, counters, and a flow id that links events across producer and consumer threads.
  2. 2Implement a Tracer with a context manager and decorator that record monotonic timestamps and thread ids into an in-memory event list.
  3. 3Add a correlation id that propagates through a queue between two worker threads, so a unit of work can be followed end to end.
  4. 4Export the event list to Chrome trace-event JSON (ph B, E, X, i, C fields) and open it in Perfetto or chrome://tracing to confirm ranges nest correctly.
  5. 5Measure per-event overhead with time.perf_counter_ns around a million begin and end pairs, and report nanoseconds per event.
  6. 6Add a sampling mode that records only every Nth event and an aggregate mode that keeps counters instead of events; re-measure overhead for all three modes.
Deliverable
A tracer.py module, an exported trace file that renders correctly in Perfetto, and a short overhead table for the three modes.
Check
The trace opens without parse errors and shows nested ranges; correlation ids connect events across threads; full-tracing overhead is under 2 microseconds per event and aggregate mode is at least 10x cheaper.
L2

Instrument a PyTorch decode loop with NVTX and torch.profiler

Colab T4 · freenotebook120 minrequired

Goal · A GPT-2 decode loop whose torch.profiler chrome trace, with your NVTX and record_function annotations, reads like the request lifecycle (token step, attention, MLP, sampler).

  1. 1On a Colab T4, load GPT-2 small and write a batched greedy decode loop of 64 tokens.
  2. 2Annotate it, nvtx ranges for prefill and each decode step, record_function around attention, MLP and the sampler, and a correlation id per request.
  3. 3Profile with torch.profiler (activities CPU and CUDA), export the chrome trace, and download it.
  4. 4Identify in the trace, the NVTX ranges you added, the CUDA kernels they contain, and one example of CPU-to-GPU correlation.
  5. 5Compute the share of GPU time under attention versus MLP versus sampler ranges from the exported JSON with a small script.
  6. 6Re-run with profiler off and with NVTX removed, and estimate the wall-clock cost of your instrumentation on this loop.
Deliverable
The annotated notebook, the chrome trace file, and the GPU-time-share table with an instrumentation-cost estimate.
Check
Your named ranges are visible in the trace and bracket the intended CUDA kernels; the attention plus MLP plus sampler share accounts for over 80 percent of GPU busy time; instrumentation cost is quantified in percent of step time.
Fallback
Run the same loop on CPU-only torch with activities CPU only; the ranges, shares and overhead measurement still work, just without CUDA kernel rows.

Build your own

Build your own NVTX-style tracer

PythonCPU · your Mac~4 h

A nested, cross-thread tracing library that exports Chrome trace-event JSON, with a measured overhead budget.

The real thing: github.com/NVIDIA/NVTX ↗

How you know a stage passes

You write tests/tracer.spec.py first. It constructs workloads with nested ranges and two worker threads, runs your tracer, and asserts on the exported JSON: valid Chrome trace schema, correct nesting by timestamp, flows connecting producer and consumer events, and an overhead ceiling measured with perf_counter_ns.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01an event log with timestamps
    begin and end events with nanosecond monotonic timestamps land in an in-memory log, and a range duration is derived from any begin and end pair.
    test · pytest asserts two logged ranges match the expected durations within 1 ms for known sleeps.
  2. 02nested ranges with a thread-local stack
    ranges nest correctly via a per-thread stack, including a range that raises an exception midway.
    test · pytest asserts parent and child relationships by timestamp containment and that an exception still closes the range.
  3. 03correlation ids across threads
    a flow id propagates through a queue between two threads, linking cause and effect events.
    test · pytest asserts the exported JSON contains flow events tying a producer event to its consumer event by id.
  4. 04Chrome trace-event export
    the log exports to valid Chrome trace-event JSON that Perfetto renders as nested ranges.
    test · pytest validates required fields per event type; manual open in Perfetto shows the nested timeline.
  5. 05sampling and aggregate modes with an overhead budget
    full tracing, Nth-event sampling and counter-only modes are selectable, and per-event overhead is measured for each.
    test · pytest asserts sampling mode records one in N events, and the printed report shows full tracing under 2 microseconds per event and aggregate mode at least 10x cheaper.
  6. 06a self-time analysis view
    a script reads the exported trace and prints a self-time table per range name (own time minus children).
    test · pytest asserts the self-time table ranks a known busy range first and that self-time plus children equals total range time within 1 percent.

Knowledge check

QWhy does instrumentation need an overhead budget rather than just more detail?

Because every recorded event costs time; beyond a small per-event budget the measurement changes the system being measured (observer effect) and can dominate a fast path like decode.

QWhat is a correlation id and what does it make possible?

An identifier propagated from a host-side call to the GPU work or downstream events it causes; it lets a trace connect a request or API call to the kernels and copies it triggered.

QWhen would you choose sampling or aggregation over full tracing?

When the path is hot enough that per-event cost or data volume is unacceptable; counters and periodic stacks give trends at far lower cost, at the price of losing per-event detail.

QName two ways bad telemetry is worse than no telemetry.

It misleads investigations (wrong units, dropped events taken as absence of work) and it consumes budget (overhead, storage) while giving false confidence; validation exists to catch both.

Completion

  • All 6 subtopics marked done
  • All 2 required lessons done
  • All subtopics marked completed.
  • Lessons l1 and l2 deliverables saved and checks pass.
  • Can explain, from one of your own traces, how a request id reached a CUDA kernel and what your instrumentation cost was.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →