GPU Performance Optimization

Estimated guided hours: 44

Course overview

GPU Performance Optimization teaches a repeatable way to improve a workload: establish equivalent work, measure a trustworthy baseline, identify the limiting resource, change one factor and measure again. Learn to connect PyTorch execution, GPU timelines and kernel evidence to an end-to-end optimization decision.

Read GPU Performance Tools before practical work. Complete GPU Fundamentals first, or be ready to explain GPU execution, memory and timing. This course owns general PyTorch performance; training checkpointing, inference attention and CUDA C++ implementation are developed in their specialized courses.

Local experiments use one full H100. Distributed concepts connect to the separately qualified fabric experiments in Advanced Labs. Follow Lab Preparation in the shared Lab Guide. Its single command prepares the available lab software; check the completion summary before practice, then qualify the runtime on the allocated hardware.

For a tensor-reading refresher, use PyTorch for GPU Performance Engineering, a concise visual course with commented examples and no labs.

How to use this course

Learn

Read the objective and explanation, then use the mental model to review the mechanism. Explain what the technique is, why it is useful and how it works before following the Practice links.

Practice

Follow Lab Preparation to prepare the available lab software with one command. Check its completion summary before submitting a lab. Each practical lab explains its purpose and concepts, then gives the commands and comparison to make. Check the results before interpreting performance.

Review

Compare correctness, repeated measurements, and profiler observations. Use the glossary and detailed diagrams when a term or relationship needs a second look.

Use the benchmark worksheet to record what your environment demonstrates and what remains to be tested.

1. Controlled GPU optimization

Objective

Define equivalent work, accepted outputs, and benchmark identity before tuning.

How it works

What GPU optimization means

GPU optimization means making an application use less time, memory or energy for a specified amount of correct work. It does not mean making a utilization gauge as high as possible. This course teaches a repeatable way to investigate a slow workload, identify the stage that limits its result, and select a change that addresses that stage. GPU Fundamentals provides the prerequisite definitions of GPUs, tensors, kernels and streams.

A kernel is a unit of device code launched across GPU threads. A Python operation may invoke one kernel, several kernels, a library routine or compiled generated code. Optimizing that operation could mean executing fewer instructions, reusing data, reducing intermediate allocations, exposing more independent work, or removing unnecessary launches. It can also mean changing the surrounding CPU work so the kernel receives inputs on time.

Why a powerful GPU can still be slow

A baseline is the reference implementation or run; a candidate contains the change being tested. A control is a comparison designed to isolate a suspected cause. Correctness tolerance is the allowed numerical difference from the reference. The critical path is the chain of dependencies that determines when the result is ready: exposed time still delays completion, whereas overlapped work progresses alongside other work. Amdahl's law bounds the overall benefit by the part of the program left unchanged. A shape lists tensor dimensions, a dtype specifies value representation, and a seed initializes reproducible pseudorandom choices. A text token is a unit produced by a tokenizer, often a word part or punctuation mark; token counts describe equivalent work only when the tokenizer and input are fixed. These are the basic terms used to define an optimization experiment.

An expensive GPU is useful only while advancing the application's required work. It may be waiting for data, starved by CPU submission, repeating avoidable memory reads, processing inefficient shapes, or waiting for another device. A fast kernel can be followed by a long CPU pause. Conversely, a continuously busy GPU can be doing avoidable work. Optimization is needed when measured latency, throughput or memory use fails the application's target, not simply because a newer technique exists.

CPU operations still matter. Loading files, decompressing records, tokenizing text, creating batches, dispatching operations and processing outputs commonly run on the host. Moving every one of them to the GPU is not the goal. Accelerate, batch or overlap the stage that actually delays completion. First confirm correctness and resource availability; an exhausted input queue and an incorrect output are different problems.

How an application reaches the GPU

Follow one batch through storage or an input source, CPU preparation in host RAM, transfer to device memory, framework dispatch, queued kernel execution, and output consumption. The CPU sends launch commands through the CUDA software stack, while transfer operations move data. A launch does not automatically resend every tensor; already-resident data can be used by successive kernels. The CPU may continue submitting work before the GPU finishes, so a timestamp around a Python call is not necessarily the time to obtain a usable result.

End-to-end GPU performance system A request or training step moves through input preparation, CPU launch, transfer, GPU kernels, synchronization or communication, and completion. A lower panel maps kernel work to bandwidth and compute ceilings. Critical-path stages input CPU / storage dispatch Python + launch transfer PCIe / fabric GPU kernels memory + compute sync / collective exposed waits complete user metric A timeline reveals which stages are exposed, overlapped, serialized, or absent. Kernel ceiling model bandwidth-side candidate compute-side candidate below both: inspect gaps, dependencies, parallelism arithmetic intensity: useful operations per measured byte useful work rate memory ceiling compute ceiling
End-to-end GPU performance system

A request or training step moves through input preparation, CPU launch, transfer, GPU kernels, synchronization or communication, and completion. A lower panel maps kernel work to bandwidth and compute ceilings.

Investigate in this order: define the desired outcome and correctness limits; reproduce a representative baseline; separate CPU, transfer, device, input and communication time; choose one plausible limiting stage; change one factor; repeat the same work; accept only if the complete result improves within the limits. A timeline is often more useful initially than a detailed kernel counter because it shows which stages are actually exposed on the path to completion.

Causal optimization loop Follow the arrows downward, then return to the baseline for another controlled trial. The workload and correctness contract stay fixed while one factor changes; remeasurement supports a keep, reject or inconclusive decision. Diagram concepts: Freeze baseline; Change one factor; Remeasure and decide. Freeze baselineChange one factorRemeasure and decide
Causal optimization loop

Follow the arrows downward, then return to the baseline for another controlled trial. The workload and correctness contract stay fixed while one factor changes; remeasurement supports a keep, reject or inconclusive decision.

How techniques and tools fit the investigation

Compare the real input pipeline with synthetic host inputs and with inputs already resident on the GPU to investigate input starvation. Compilation translates a program region into an executable implementation; fusion combines operations into fewer kernels; a CUDA Graph is a reusable plan of device operations and their dependencies. These techniques respectively change implementation, remove intermediate work, or reduce repeated submission overhead. Layout describes how tensor indices map to storage; numerical precision describes how finely values are represented. They are introduced here as a map, then defined and practiced in their own lessons. These are hypotheses to test, not switches to enable together. Distributed overlap belongs later, after the local path is understood.

Read-only nvidia-smi and NVIDIA Data Center GPU Manager (DCGM) observations describe device state and trends. A profiler records execution activity: PyTorch Profiler associates framework operations with that activity, Nsight Systems explains the CPU/transfer/kernel timeline, and Nsight Compute examines selected kernel resource and memory behavior. NVIDIA Tools Extension (NVTX) supplies human-readable ranges in a trace. Profilers add overhead, so collect diagnostic traces separately from final unprofiled timing. Lesson 3 and the Diagnostic tooling reference guide explain selection and safe use.

Execution and dependencies

GPU Fundamentals supplied execution, memory, timing, and roofline models. Optimization begins by turning those models into a controlled experiment whose inputs, outputs and timed operations remain fixed.

An optimization changes one part of the path from an input to a usable result. That path can include host preparation, data transfer, launches, GPU kernels, communication and output handling. A stage delays the result when later required work must wait for it. A stage that overlaps independent work may consume resources without adding its full duration to completion time.

The comparison becomes meaningful only when the baseline and candidate perform equivalent work. Shapes, dtypes, seeds, sequence lengths, batch semantics and output tolerances define that work. Warm-up, compilation state, repetitions and environment define the conditions under which it runs. Repeated samples show normal variation; the best sample alone can hide it.

The first explanation to test should connect a resource to an observed delay. Arithmetic demand can limit compute; repeated transfers can limit data movement; slow submission can leave the device waiting; communication or input preparation can delay dependent work. For diagnosis, this course groups these delays into compute, memory/data movement, host/launch, communication, or input/storage limits. This is a teaching organization, not a set of NVIDIA profiler metric names. Memory capacity answers whether the workload fits at all. Divergence, layout, fragmentation and imbalance describe mechanisms that can produce these constraints, rather than interchangeable names for a bottleneck.

Five primary GPU performance bottleneck classes This course groups possible bottlenecks into five diagnostic categories. The boxes represent compute, memory/data movement, launch or CPU, communication, and input or storage bottlenecks. A lower band lists cross-cutting mechanisms, while memory capacity is separated as a feasibility constraint. compute memory /data movement launch / CPU communication input / storage math throughput ceiling bandwidth · latency· useful bytes submission gaps + sync exposed rank-to-rank work data, preprocessing, weights, checkpoints Cross-cutting mechanisms that refine the diagnosis transfers · layout and coalescing · insufficient waves · divergence · synchronization · imbalance · throttling Separate feasibility question: does the workload fit? Course categories; use profiler metrics to test each diagnosis.
Five primary GPU performance bottleneck classes

This course groups possible bottlenecks into five diagnostic categories. The boxes represent compute, memory/data movement, launch or CPU, communication, and input or storage bottlenecks. A lower band lists cross-cutting mechanisms, while memory capacity is separated as a feasibility constraint.

A disconfirming control is a comparison designed to show that an explanation could be wrong. If input preparation appears to starve the GPU, repeat equivalent device work with inputs already resident on it. If the idle gaps remain, input preparation alone does not explain them. The control narrows the cause; it does not replace the full application measurement.

A useful hypothesis predicts both supporting evidence and a control that could disprove it. For example, if input preparation is the cause, starting with resident inputs should remove the associated wait. A high utilization reading or a long kernel by itself cannot make that causal connection.

Amdahl's law limits the possible overall benefit. If a stage occupies 10 percent of serial latency, eliminating it leaves the other 90 percent. Total latency falls by at most 10 percent, giving a maximum speedup of about 1.11×. Improving a small stage cannot remove time spent elsewhere.

Most false speedups come from changing the workload, omitting required synchronization, warming only one candidate, or accepting a numerically different result. A useful result must also matter on the end-to-end critical path.

Evidence-driven optimization loop Six boxes form a loop from baseline through correctness, timing, classification, one change, and remeasurement. 1. Freeze workload+ metric 2. Prove correctness 3. Measure + profile 4. Classify the limiter 5. Change one thing 6. Remeasureand decide
Evidence-driven optimization loop

Six boxes form a loop from baseline through correctness, timing, classification, one change, and remeasurement.

Try a small example

Assume a request spends 6 milliseconds preparing data on the CPU and 4 milliseconds executing GPU work, with no overlap. Halving the GPU work yields 8 milliseconds overall, not 5. If preparation of the next batch can safely overlap the current batch's device work, steady-state throughput may instead be limited by the slower stage; first-request latency and buffer ownership still need separate checks. Draw both timelines before choosing a technique.

Mental model

A benchmark is a controlled experiment. Input shapes, dtypes, seeds, compilation state, hardware allocation, and correctness criteria are controlled variables; the selected optimization is the independent variable.

2. Asynchronous performance measurement

Objective

Choose CUDA events, synchronized wall time, or profiler timelines for the question being asked.

How it works

GPU submission is asynchronous: a CPU call can finish after requesting work but before the GPU completes it. Wall-clock timing measures elapsed real time between host timestamps. CUDA-event timing measures the interval between markers reached on the device, which can include dependencies, idle gaps and other effects inside that interval; it is not simply a sum of active kernel durations. Synchronization lets the caller wait for the required GPU work before reading its result or stopping a CPU timer.

Warm-up runs prepare caches, compilation and library choices before steady-state measurement. Lazy initialization defers setup until first use; autotuning tries candidate implementations to choose one. Repeated samples expose variation: the median is the middle ordered value, or the average of the two middle values for an even sample count. A percentile such as p95 marks a value at or below which approximately 95 percent of observations fall. A short isolated kernel and a complete application include different operations in their measurements, even when both report milliseconds.

First identify the operations to measure and where their result is needed. Then choose a timer and synchronization that include completion of those operations.

A GPU operation has two relevant moments: the CPU submits it, and the device finishes the required work. A host timer stopped at the first moment measures submission. To measure a usable result, the stopping point must include the second moment and any other dependencies in the request.

Asynchronous timing Read downward in event order. Submission can finish while device work remains; a CPU timer for the complete operation stops only after the required GPU work finishes. The spacing does not represent duration or prove overlap. Diagram concepts: CPU submits work; GPU executes queued work; Required work completes. CPU submits workGPU executes queued workRequired work completes
Asynchronous timing

Read downward in event order. Submission can finish while device work remains; a CPU timer for the complete operation stops only after the required GPU work finishes. The spacing does not represent duration or prove overlap.

CUDA events mark progress on the device. Place a timing-enabled start event before the operation and an end event after it in the same dependency chain. Once the end event completes, their elapsed time describes that device interval. The interval can include waits or idle gaps between the markers; it is not necessarily the sum of active kernel durations. With several streams, dependencies must join all work included in the measurement. An end event in one stream does not automatically cover unrelated work in another.

For an end-to-end iteration, a CPU clock surrounds the full request and stops after its declared completion. This includes required host work and transfers as well as device work. Warm-up precedes steady-state measurement because first use can trigger module loading, allocator growth, compilation and autotuning. If startup is the question, those costs instead belong inside the measurement. Retaining individual samples makes medians and slow tails visible.

Reading a CUDA scalar with .item() is a small operation with a significant ordering effect: its value must reach the CPU before the call can return. A reduction such as square().mean() first computes the scalar on the device; reading it then adds a host wait. Frequent logging can therefore serialize a loop. Where the application permits it, detached device scalars can be retained and reported together later. Detaching removes an autograd connection; it neither moves data to the CPU nor waits for completion. The final read still belongs in timing when the application requires it.

CUDA submission is asynchronous. A CPU timer stopped after submission reports enqueue cost. Two timing-enabled CUDA events measure an elapsed stream interval. A CPU timer stopped after required synchronization includes the host-observed wait for completion. These are different metrics, not contradictory answers.

Mental model

GPU work is queued asynchronously. CUDA events measure an elapsed stream interval, which can include waits and idle gaps. A CPU timer stopped after the required synchronization measures the host-observed duration of the selected operations, including host work and transfers when they occur between its timestamps.

3. Performance evidence and profiling

Objective

Escalate from application symptoms to the narrowest tool that answers the next question.

How it works

A benchmark measures how long work takes or how much work completes; a profiler records where execution spends time; monitoring samples system state. A trace records events, often displayed as a timeline. A hardware counter measures activity such as bytes moved or instructions executed. NVIDIA Nsight Systems follows the application timeline across CPU work, GPU launches and communication. Nsight Compute examines a selected kernel's hardware behavior. PyTorch Profiler relates framework operations to CPU and device activity.

Instrumentation adds observation work to the program. NVIDIA Tools Extension (NVTX) ranges are named annotations that help identify a chosen phase in a trace. Self time excludes an event's recorded children; inclusive time includes them, so summing overlapping rows can double-count work. Collecting many counters may require replay—rerunning the measured work—which is why a profile explains performance but is not automatically an unbiased benchmark.

Trustworthy timing proves that a slowdown exists but rarely explains it. Tool selection should follow a hypothesis and move from broad semantic context toward a single kernel only when the evidence requires it.

Profiler evidence funnel Read downward as an investigation order, narrowing only when the next question needs more detail. Framework events identify operations, the timeline exposes dependencies, and kernel counters explain a selected operation. These are views of execution, not stages the workload passes through. Diagram concepts: Framework attribution; System timeline; Selected kernel counters. Framework attributionSystem timelineSelected kernel counters
Profiler evidence funnel

Read downward as an investigation order, narrowing only when the next question needs more detail. Framework events identify operations, the timeline exposes dependencies, and kernel counters explain a selected operation. These are views of execution, not stages the workload passes through.

A useful profile connects the code that requested work to the activity that completed it. Begin with that relationship, then ask for more detail only where the trace leaves an unanswered question.

Choose the view that answers the question

PyTorch Profiler connects Python operators, shapes, allocations, and scheduled training steps; short active windows and semantic NVTX ranges keep traces interpretable. Nsight Systems shows CPU threads, CUDA application programming interface (API) calls, kernels, copies, collectives, and gaps on a common timeline; inspect the timeline before aggregate tables. Nsight Compute replays selected kernels to collect instruction, memory, scheduler, and roofline metrics; replay overhead means its run is not acceptance timing. nvidia-smi and DCGM provide device state, NVIDIA Collective Communications Library (NCCL) Tests isolate collectives, nvbandwidth isolates supported transfer paths, and serving load tools own request-level distributions. Tool availability and counter permission belong to the cluster owner; the learner verifies them inside an allocation and fails clearly if a required scope is unavailable.

Tool scope from service objective to selected kernel A vertical diagnostic ladder moves from inference load and end-to-end metrics through device telemetry, framework operators, system timeline, and one selected kernel. Side labels show the artifact produced at each level. AIPerf or application benchmark TTFT · ITL · end-to-end latency · request/token throughput nvidia-smi and DCGM health · power · clocks · memory · interval SM/DRAM/fabric activity PyTorch Profiler + NVTX operators · shapes · calls · allocations · semantic phases Nsight Systems CPU/GPU timeline · gaps · copies · sync · NCCL Nsight Compute one kernel · counters · roofline Descend only when the broader artifact identifies a stable, material question for the next layer.
Tool scope from service objective to selected kernel

A vertical diagnostic ladder moves from inference load and end-to-end metrics through device telemetry, framework operators, system timeline, and one selected kernel. Side labels show the artifact produced at each level.

For an initial tool map, use the GPU Performance Tools guide: it separates device health, continuous telemetry, framework attribution, system timelines, kernel counters and load generation. It also explains protected DCGM Exporter/Prometheus collection, counter contention, NCCL Tests versus nvbandwidth and standardized benchmark context. Reading these interfaces is not permission to reconfigure cluster monitoring or networking. Use the cheapest observation that can distinguish your current hypothesis, then narrow the scope before collecting expensive kernel details.

Follow a submitted operation onto the device

Read an NVTX range first as a host annotation: it names the code that submitted work, not necessarily the interval during which the GPU executed that work. Follow CUDA API correlation to the corresponding copy or kernel on its stream, then inspect the dependency that delays the next operation. A blank region on one selected stream is only an absence of captured activity there. Other streams, processes, copy engines or uncaptured work may still be active. Likewise, a continuous kernel bar does not establish that all streaming multiprocessors are busy or that any compute pipeline reaches peak throughput. Use qualified hardware metrics when that is the question.

Account for what the capture includes and changes

Nsight Systems can retain PyTorch context through explicit NVTX and supported PyTorch annotation options. Its visibility depends on the selected trace domains, processes and permissions; it is not an unlimited view of the machine. A nearby memory-unmapping call is a hypothesis for a host delay, not causal proof. Match the blocked API, allocation lifetime and downstream wait, make one controlled change, then repeat the trace. Keep acceptance timing in a separate unprofiled run. Nsight Compute replay, cache control and clock control can change a kernel's conditions; do not compare its duration directly with application timing without accounting for those settings.

Capturing every counter creates huge, perturbing traces without answering the question. Engineers also confuse monitoring, profiling, and benchmarking, or treat unavailable privileged counters as a reason to guess.

Mental model

PyTorch Profiler connects framework operators to device work; Nsight Systems exposes CPU, runtime, kernels, communication, and gaps; Nsight Compute diagnoses a selected kernel.

4. Submission overhead and kernel fusion

Objective

Recognize launch-bound workloads and reduce unnecessary dispatch.

How it works

Eager execution asks the framework to perform operations as the program reaches them. Dispatch is the process of selecting and submitting an implementation; dispatch overhead is the CPU work surrounding the useful device computation. Compilation analyzes a program region and generates an executable implementation. Fusion combines several operations into fewer kernels, allowing some intermediate values to remain in registers instead of being written to separate tensors. Vectorization or batching expresses work on many values together rather than issuing a separate operation for each value.

For example, multiplying, adding and activating an array can launch three kernels in eager execution but may become one fused kernel. A compiler guard checks an assumption such as shape or dtype; a graph break ends a captured compiler region when code cannot be represented there. Aliasing means tensors share storage, and mutation changes existing values. Compilation and fusion are distinct from CUDA Graph replay, introduced next.

A Systems timeline exposes gaps and many short kernels. This lesson chooses semantics-preserving ways to submit fewer, larger pieces of work.

In eager execution, the CPU repeatedly selects and submits implementations as it reaches tensor operations. If each GPU kernel is very short, the device may finish one before the CPU submits the next. Much of the elapsed time can then come from dispatch and launch rather than arithmetic.

Several changes address different parts of this delay. Batching independent items or vectorizing a Python loop expresses more work per call. Existing fused operators combine calculations that would otherwise require several kernels. Fusion can keep intermediate values inside a kernel, removing both launches and the writes and rereads of temporary tensors. Removing an unnecessary .item() avoids a different cost: waiting for a device value on the host.

Launch and fusion Compare the separate and fused implementations, then their application result. Fusion can remove launches and intermediate traffic, but the complete result improves only when those savings exceed added costs. The boxes are comparison topics, not a sequence of kernel execution. Diagram concepts: Separate small kernels; Fused computation; Complete application result. Separate small kernelsFused computationComplete applicationresult
Launch and fusion

Compare the separate and fused implementations, then their application result. Fusion can remove launches and intermediate traffic, but the complete result improves only when those savings exceed added costs. The boxes are comparison topics, not a sequence of kernel execution.

An activation illustrates work that can sometimes be fused with nearby arithmetic. SiLU, the sigmoid linear unit, computes x/(1+exp(-x)); tanh maps real values smoothly between -1 and 1. Both return zero for an input of zero. A multiply, add and activation may become one generated kernel if the compiler can preserve the required values and operation semantics.

torch.compile analyzes an operation region and may generate fused work or reduce Python overhead. Shape guards check assumptions used by that implementation. Unsupported operations can create graph breaks; changing shapes or assumptions can require other compiled variants or fallbacks. Aliasing, mutation, numerical order and reuse can also prevent a proposed fusion. Cold compilation and cache behavior are separate costs from steady execution.

fullgraph=True requires one compiler graph for the selected function and raises an error for an unsupported graph break. That graph represents operations and dependencies; it may still generate several CUDA kernels. Only the emitted work shows whether the intended launches and intermediate traffic were actually removed.

H100 can finish small elementwise kernels faster than Python and the runtime can dispatch them. The symptom is a launch-dense timeline with low work per launch, not merely low average utilization.

Mental model

Many tiny eager operations repeatedly cross Python, dispatcher, and CUDA-launch boundaries. Fusion, compilation, batching, or graphs can amortize those costs.

5. Reusable GPU execution plans

Objective

Identify graph-safe regions and measure replay benefits and constraints.

How it works

A CUDA Graph is a reusable execution plan for GPU operations and the dependencies between them. Operations, such as kernels or memory copies, are nodes; dependency edges specify which work must finish before other work can start. The ordinary plan is a directed acyclic graph: its dependency arrows do not form a cycle. Instead of rebuilding and submitting each operation individually on every iteration, the application prepares a graph and launches the prepared plan again. Capture records compatible submitted work into a graph; replay executes that recorded plan, not a saved set of numerical answers.

For example, a multiply → add → activation sequence can be replayed through one graph launch while still containing three kernels. Graph replay reduces repeated submission and setup work; kernel fusion combines operations within a kernel, while compilation translates a program representation into executable work. These are separate transformations.

Instantiation prepares a graph as an executable plan. A graph-private memory pool retains storage used by captured work. A shape bucket groups inputs handled by one supported capture; a fallback executes inputs outside that capture's contract through another supported path. Buckets and fallback routing are extensions to this lesson's fixed-shape baseline, not requirements of every CUDA Graph application.

Compilation can change and fuse a graph of operations. CUDA Graphs solve a different problem: they record an already chosen stable sequence of CUDA work and replay its submission cheaply.

A graph replay starts from an execution plan prepared earlier. First, warm-up establishes the allocations, library plans and compiled code needed by the workload. Capture then records compatible device operations and their dependencies. Instantiation prepares that recorded graph for execution. Later replays launch the prepared plan with less repeated host submission work.

The plan refers to storage as well as operations. In this PyTorch workflow, captured allocations use graph-private memory pools, and referenced virtual addresses must remain valid for replay. A common arrangement copies new values into stable input buffers, replays the graph, and consumes results from stable output buffers. The values can change even though the buffers and execution structure stay compatible.

Execution-plan reuse Read downward through preparation and reuse. Warm-up resolves lazy work, capture records an eligible dependency graph, and instantiation prepares an executable plan. Replays reuse its eligible structure and storage addresses while input values may change; replay does not make dependent operations concurrent. Diagram concepts: Warm up and retain buffers; Capture and instantiate; Refresh values and replay. Warm up and retain buffersCapture and instantiateRefresh values and replay
Execution-plan reuse

Read downward through preparation and reuse. Warm-up resolves lazy work, capture records an eligible dependency graph, and instantiation prepares an executable plan. Replays reuse its eligible structure and storage addresses while input values may change; replay does not make dependent operations concurrent.

Shapes, referenced storage, control flow, stream dependencies and participating operations form this capture's contract. An input outside that contract cannot simply be substituted and assumed safe. As an optional extension, implement separate compatible captures for a bounded set of shape buckets and route other inputs through an eager path.

Graph replay does not erase preparation costs or free memory retained by graph pools. Compilation time, capture time, steady replay time, retained memory and bucket hit/fallback rates therefore describe different consequences. A compiled region may be captured, but compilation determines its implementation while the CUDA Graph records how the resulting device work is submitted.

Graph capture is powerful for repeated fixed work but fragile around dynamic allocation, changing addresses, CPU decisions, synchronization, and unsupported operations. Confusing compile, capture, and replay hides cold cost and fallback behavior.

The dependency structure is a directed acyclic graph (DAG): nodes are operations, edges are prerequisites, and no chain loops back to its own unfinished start. Replay repeats this finite plan.

Mental model

CUDA Graphs capture a repeated device-work DAG and replay it with lower launch overhead. This PyTorch exercise requires compatible shapes, stable referenced storage and capture-safe operations; these are its capture contract, not a claim that the broader CUDA API forbids graph updates.

6. Input readiness and transfer overlap

Objective

Detect and repair host-side starvation without hiding it behind device averages.

How it works

An input pipeline turns source data into batches ready for GPU computation. It can read files, decode records, transform values, combine examples and transfer the resulting tensors. PyTorch's DataLoader coordinates fetching and batching; workers perform preparation, and collation combines individual examples into the batch structure. Prefetch prepares future batches before they are requested, while queue depth describes how many are waiting. Persistent workers keep their processes alive between passes through the data, called epochs.

Tokenization converts text into model token IDs; augmentation transforms examples while preserving the intended task. A pinned host buffer supports suitable asynchronous host-to-device (H2D) transfers. A resident-input control starts with data already on the GPU; a synthetic-input control generates data without the real storage path. Comparing these controls helps locate starvation, when the next batch is not ready, without assuming every idle gap is caused by slow GPU kernels.

Even perfect GPU kernels wait if the next batch is not ready. Model the loader as producers filling a bounded queue for a GPU consumer rather than as a single “data time” number.

Follow a batch through the producer stages: read the source, decode it, tokenize or augment it if needed, collate examples, prepare host storage and copy tensors to the GPU. The GPU consumer can begin only when its input is ready. If preparation is slower than consumption, the ready queue empties and the GPU waits, even when its kernels are efficient.

Input pipeline Arrows show one batch's dependencies: prepare it, complete its input copy, then consume it. Different batches may overlap with suitable streams, hardware and ownership; this stage map does not itself depict overlap. Diagram concepts: Storage and CPU preparation; H2D copy from pinned memory; GPU consumes the batch. Storage and CPUpreparationH2D copy from pinnedmemoryGPU consumes the batch
Input pipeline

Arrows show one batch's dependencies: prepare it, complete its input copy, then consume it. Different batches may overlap with suitable streams, hardware and ownership; this stage map does not itself depict overlap.

Workers can prepare several batches concurrently, and prefetch lets them work ahead. This absorbs some variation but uses memory and cannot sustain a producer that is consistently too slow. Persistent workers avoid repeated process startup between epochs when that startup matters. Extra workers can instead increase storage contention or CPU scheduling costs. The pipeline must preserve distributed sampling, epoch/seed behavior, sample order where required and exact sample counts.

Pinned memory keeps host pages resident so suitable direct memory access (DMA) transfers can use their stable backing without first staging pageable data. Pinning has a cost and consumes host resources. A preallocated or loader-managed pinning path may amortize that cost; pinning each batch in the hot loop can erase the saving.

A nonblocking copy lets the CPU continue, but a copy and kernel in the same stream still run in order. Actual copy/compute overlap needs separate streams, independent work, suitable hardware and explicit dependencies. A device buffer cannot be read until its input copy finishes or overwritten until its computation finishes. The host source must also remain unchanged until the copy stops reading it. Keeping a tensor alive prevents deallocation, not premature in-place modification.

Input slots protect copy and compute Follow one paired host/device slot downward. Its previous computation must finish before refill. The host source stays unchanged until the copy completes; computation waits for that completion. Only finished computation permits the next reuse. The return arrow repeats this ownership cycle. Other slots may overlap independent work; heights are not measurements. 1. Wait for prior slot computation 2. Fill pinned host and enqueue H2D 3. Copy completes; compute may read 4. Compute finishes; slot may be reused Reuse for the next batch
Input slots protect copy and compute

Follow one paired host/device slot downward. Its previous computation must finish before refill. The host source stays unchanged until the copy completes; computation waits for that completion. Only finished computation permits the next reuse. The return arrow repeats this ownership cycle. Other slots may overlap independent work; heights are not measurements.

Batch-ready timestamps, queue depth, idle gaps and stage durations distinguish these waits. Synthetic inputs remove the real storage path; resident inputs also remove host preparation and transfer. Their different effects help locate the delay. Worker prefetch, asynchronous host submission and device overlap solve different problems. Data Loading Library (DALI) or another accelerated pipeline is useful only when it addresses the demonstrated stage while preserving the same input semantics.

Increasing workers can move the bottleneck to storage, CPU scheduling, memory, interprocess transfer, or shared filesystem contention. It can also duplicate or reorder samples and change the training workload.

Mental model

Reading, decoding, preprocessing, batching, pinning, and transfer form a producer pipeline. The device stalls when the next batch is not ready. NVIDIA DALI is one optional accelerated data-pipeline implementation, not evidence that storage, decode, or transfer is the current limiter.

7. Tensor layout and memory traffic

Objective

Reduce layout conversions, non-coalesced access, and materialized intermediates.

How it works

A tensor's layout maps logical indices to storage addresses. A producer creates values and a consumer uses them; an intermediate is the producer's result passed between operations. Materializing an intermediate means writing it into an allocation instead of keeping it within an executing kernel. Read/write accounting counts those reads, writes and copies. An implicit conversion happens inside a framework or library call when its preferred layout differs from the supplied one.

For example, a transpose can initially be a cheap view, but the next operator may need a physical copy. An epilogue is work applied to an operation's result, such as adding bias after matrix multiplication; fusing it may avoid an intermediate allocation. Aliasing or mutation can require preserving shared storage, so a compiler's alias guard checks assumptions before transforming the program. This lesson extends single-access coalescing to the interfaces between several operators.

Fundamentals Lab 04 established strides, packing cost and break-even reuse for one access pattern. Keep that result as a prerequisite. This lesson asks how several producers and consumers agree on layouts, where implicit conversions appear, and whether fusion can remove an entire intermediate.

Consider two operators where the second consumes the first one's output. In an unfused implementation, the first writes an intermediate tensor and the second reads it. Some reads may hit a cache, but the intermediate still creates storage and memory requests. A fused implementation may pass those values within a kernel and avoid materializing that tensor.

Layout adds another possible cost between the operators. A producer may return a view with no copy, while the consumer requires a different physical arrangement and materializes one internally. Accounting for traffic operation by operation makes these costs visible: input reads, output writes, temporary writes and rereads, packing copies and later reuse. Kernel and allocation evidence can then distinguish a real copy from a metadata-only view.

Layout and traffic choices Compare three mechanisms, not mandatory stages. A view changes strides without moving values; a consumer may require a real layout copy; fusion can keep intermediate values within one kernel. Include the complete producer-to-consumer path before deciding which removes actual traffic. Diagram concepts: View: change addressing; Copy: move into new layout; Fusion: avoid intermediates. View: change addressingCopy: move into new layoutFusion: avoidintermediates
Layout and traffic choices

Compare three mechanisms, not mandatory stages. A view changes strides without moving values; a consumer may require a real layout copy; fusion can keep intermediate values within one kernel. Include the complete producer-to-consumer path before deciding which removes actual traffic.

Packing once pays an initial conversion cost for cheaper repeated accesses. It breaks even when pack_cost < reuse_count × (strided_cost - packed_cost): the total saving across later uses must exceed the copy. The shape alone cannot establish that saving; strides and the consumer's lane mapping determine the addresses accessed.

Fusion and conversion must also preserve storage relationships. Aliases can expose the same values through several tensors, mutation can make old values significant, and lifetimes determine which results must coexist. Compiler guards or graph breaks may prevent an intended transformation for those reasons. The resulting kernels and surviving intermediates reveal what changed in practice.

Logical tensor bytes can understate physical traffic. Temporary materialization, layout copies, cache-line over-fetch, and repeated reads consume high-bandwidth memory (HBM) bandwidth and allocation capacity even when the Python expression looks compact.

A persisting-L2 (level-two cache) access policy identifies a memory range whose accesses should receive preferential retention in the shared L2 cache on supported configurations. It is a reuse hint, not a guarantee that the range stays resident. Giving a proven reusable range that preference competes with other useful data and requires CUDA-level evidence.

Mental model

A tensor view changes how existing storage is addressed; a materialized copy moves data. Optimize the producer and consumer together so layout conversion and intermediate traffic are included in the decision.

8. Memory allocation and ownership

Objective

Distinguish allocated, reserved, live, cached, fragmented, and peak memory.

How it works

An allocator manages requests for memory. PyTorch's caching allocator can retain blocks after tensors stop using them so later allocations avoid repeated device-allocation overhead. Allocated bytes track live tensor storage; reserved bytes also include storage held by the allocator for reuse. Peak memory is the largest amount observed during a specified interval. A workspace is temporary storage an operation needs in addition to its inputs and outputs.

Fragmentation means free storage is divided into pieces that cannot satisfy a particular request efficiently. Size classes group allocation sizes; an inactive split is an unused part of a split allocation segment. A memory snapshot records the allocator's state for inspection. In-place operations update existing storage, but aliases and autograd—the system that records operations for differentiation—may still need the old values. Reserved memory exceeding allocated memory is therefore not by itself a leak, and releasing cached blocks cannot free live tensors.

An output pipeline moves device results into host buffers and hands completed results to a consumer, such as an encoder or storage client. A buffer pool reuses a bounded set of allocations. Backpressure is the wait imposed when every slot is still owned by a transfer or consumer; it prevents unbounded queued results. A future represents eventual completion or failure of a worker task. This lesson applies allocator lifetime to both GPU and CPU ownership, after Lesson 6 established input-stream dependencies.

Read/write accounting counts bytes moved. An allocation-lifetime diagram asks when each allocation must coexist, which determines whether the workload fits and whether allocator state is being mistaken for a leak.

An allocation contributes to memory demand for as long as some operation needs it. Inputs, outputs, workspaces, communication buffers and compiler or graph pools can overlap in lifetime. Peak demand occurs where the largest set must coexist, so shortening one long-lived allocation can matter more than reducing several small ones.

When a tensor is no longer needed, PyTorch's caching allocator can keep its storage for a later allocation. memory_allocated describes live tensor storage known to the allocator; memory_reserved includes both active storage and allocator-held capacity. They are overlapping quantities, not two memory bills to add together. High reserved memory after tensors are freed can therefore be normal reuse behavior.

Allocator lifetime Read downward through one allocation's lifetime. After the last tensor and asynchronous user release it, eligible storage can remain cached. Reserved bytes include active allocations as well as cached capacity. Diagram concepts: Tensor uses storage; Allocator can cache it; Later allocation may reuse it. Tensor uses storageAllocator can cache itLater allocation may reuseit
Allocator lifetime

Read downward through one allocation's lifetime. After the last tensor and asynchronous user release it, eligible storage can remain cached. Reserved bytes include active allocations as well as cached capacity.

Free capacity is not always available in a useful shape. Inactive split blocks and mismatched size classes can prevent a new request from fitting efficiently. Allocation retries and memory snapshots help distinguish this pressure from genuinely live tensors. empty_cache() can release eligible unused cached storage, but it cannot release a tensor that still has a live reference. In-place changes are safe only when aliases and autograd do not require the previous values. Training-specific checkpointing and state sharding address different causes of long lifetimes.

An output pipeline extends lifetime beyond the GPU kernel. A device-to-host copy must finish before the CPU reads its destination. The CPU consumer must then finish before that host buffer is reused. The device source must remain valid until the copy stops reading it. A bounded pool returns a slot only after these owners have released it; when no slot is free, backpressure waits instead of allocating an unbounded queue.

Output ownership lasts through consumption Follow one output slot downward. The copy stream waits for GPU production, then copies into pinned host storage. The CPU reads only after copy completion. The return arrow permits another output only after the CPU consumer finishes. Buffer lifetime and readiness are separate from submitting an event marker. 1. GPU produces; record ready 2. Copy stream waits; copy to pinned host 3. Copy completes; CPU may read 4. Consumer finishes; slot may be reused Reuse for the next batch
Output ownership lasts through consumption

Follow one output slot downward. The copy stream waits for GPU production, then copies into pinned host storage. The CPU reads only after copy completion. The return arrow permits another output only after the CPU consumer finishes. Buffer lifetime and readiness are separate from submitting an event marker.

Capacity and bandwidth are different problems. Reducing reserved memory may not speed a step, while shortening one large live interval can enable a larger useful batch even with unchanged kernel time.

CUDA memory pools and stream-ordered allocation make reuse and ordering explicit below the framework layer; they do not reduce live tensor bytes.

Mental model

Live tensor storage determines the irreducible memory demand. Allocation reuse can avoid repeated system work, but safe reuse still follows tensor ownership and stream completion.

9. Efficient numerical-library execution

Objective

Align matrix dimensions, batches, and dtypes with efficient library kernels.

How it works

A numerical library selects an implementation using the operation, dimensions, layout, numerical format and hardware. General matrix multiplication (GEMM) multiplies an M-by-K matrix by a K-by-N matrix to produce M-by-N values: M and N are output dimensions, while K is the dimension summed over. A tile is a smaller rectangular piece handled cooperatively by the implementation. Dispatch chooses the implementation; a cast converts values between numerical formats.

Padding adds unused or neutral values to reach a supported or efficient shape. It is valid only when the original result is preserved, such as adding matching zero entries along K. Shape alignment means dimensions suit a kernel's tile sizes; pointer alignment instead concerns memory addresses. Tensor Core hardware supports particular arithmetic paths, not every possible shape or dtype. The goal is to preserve useful work while choosing an efficient library path, not to enlarge the task until a benchmark looks faster.

Layout determines how bytes arrive; shape and precision determine which maintained library kernel can consume them and whether Tensor Core tiles are used efficiently.

A library receives an operation together with its shapes, dtypes and layout, then selects an implementation for the available hardware. A matrix kernel divides the work into tiles. Dimensions that leave small partial tiles may use the selected implementation inefficiently, while a nearby larger shape may select a different kernel or fit its tiles better.

Padding can exploit that behavior, but it adds work. For a matrix product, zero padding along the reduction dimension preserves the original sum when both operands are padded consistently. The kernel still multiplies the extra entries. A faster kernel is useful only if the complete padded calculation, including preparation and result handling, finishes sooner for the same useful output. Useful floating-point operations (FLOPs) or tokens and padded FLOPs or tokens must therefore remain separate counts.

Precision affects both bytes and eligible arithmetic. Stored inputs may use one format, multiplication another internal mode, accumulation a wider format and outputs a final rounded format. Casts and scaling add operations of their own. A dtype change or aligned dimension alone does not prove Tensor Core execution; library dispatch and kernel evidence establish the actual path.

Representative shapes, batches, dtypes and layouts expose these choices without changing model semantics. Alignment requirements depend on the library, version and operation rather than one universal multiple. Time, memory and output error describe the result together. Attention-specific backend selection and scaled dot-product attention (SDPA) experiments build on this model in the Inference course.

Shape and precision The arrows connect input properties to implementation selection and its consequences. Padding or casting adds work of its own; a faster selected kernel must still preserve the useful result and repay those costs. Diagram concepts: Shape, layout and dtype; Library selects a kernel; Time, memory and error. Shape, layout and dtypeLibrary selects a kernelTime, memory and error
Shape and precision

The arrows connect input properties to implementation selection and its consequences. Padding or casting adds work of its own; a faster selected kernel must still preserve the useful result and repay those costs.

A mathematically smaller shape can run slower when it selects a poor kernel, wastes a final tile, or prevents fusion. Padding can improve kernel efficiency while increasing total work, so comparisons must normalize useful work.

Mental model

Library dispatch depends on dtype, dimensions, strides, alignment, and hardware. A small amount of shape padding can improve utilization, but excess padding wastes work and memory.

10. Parallel imbalance and completion tails

Objective

Distinguish lane divergence, uneven blocks, uneven ranks, and the final partial scheduling wave.

How it works

Load imbalance means parallel tasks take different amounts of time, leaving some workers idle while others finish. Makespan is the elapsed time until all tasks are done. Contention occurs when workers compete for the same resource. A partial grid wave occurs when too few blocks remain to fill the available resident-block slots. That scheduling tail differs from tail latency, which describes slow observations in a distribution such as p95.

Warp divergence is another level: lanes within one warp follow different paths. Shared memory is divided into independently serviced banks. A bank conflict occurs when accesses to different words compete for the same bank's service; supported same-word broadcasts are different. A persistent kernel keeps workers active to take more tasks instead of launching a fresh grid for each batch of work. These concepts all involve unused capacity, but their causes and fixes differ. Diagnose the level of imbalance before changing task sizes, grouping or scheduling.

The local lessons have covered launch overhead, data movement, allocation, shapes and precision. Now distinguish idle lanes, uneven blocks and partial grid waves before introducing distributed scaling. Rank skew is a preview of the same completion-time problem across workers in Lesson 11.

Parallel work finishes when its last required task finishes. To explain unused capacity near that point, first identify which unit is uneven: lanes within a warp, blocks within a grid, or processes across a distributed job.

Inside a warp, divergent branches run with different active-lane masks. Lanes on one path do not perform useful work while the other path's instructions execute. Across blocks, data-dependent work, contention or unequal tiles can instead give whole blocks different durations. These are separate causes even when both leave execution capacity unused.

A partial final wave needs no unequal durations at all. Suppose earlier waves fill all available resident-block slots, but only a few blocks remain. Those blocks still have to run, leaving other slots unused until the grid completes. Comparing the grid size with concurrent block capacity explains this scheduling tail. A uniform-work control helps distinguish it from blocks that are individually slow.

Kernel geometry, residency, and wave tails This simplified wave model groups blocks by concurrent resident capacity across four example SMs. Actual blocks can start as resources become available. Register, shared-memory, thread, and block limits determine resident blocks, while a partial final wave leaves some SMs idle. Grid blocks B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 Example residency: two blocks per SM SM 0 SM 1 SM 2 SM 3 wave 1: B0 wave 1: B1 wave 1: B2 wave 1: B3 wave 1: B4 wave 1: B5 wave 1: B6 wave 1: B7 partial final wave B8 and B9 use only part of the GPU resident-block limits threads · registers · shared memory block limit · architectural limit Waves model capacity; actual blocks can start as resources become available.
Kernel geometry, residency, and wave tails

This simplified wave model groups blocks by concurrent resident capacity across four example SMs. Actual blocks can start as resources become available. Register, shared-memory, thread, and block limits determine resident blocks, while a partial final wave leaves some SMs idle.

Across ranks, one worker may reach a collective later than its peers. Their apparent communication time then includes waiting for its arrival. Per-rank timelines separate that skew from the transfer itself. Active-lane metrics, block-work distributions and rank timelines answer different questions and should not substitute for one another. Bank conflicts, registers, spills and occupancy can explain a kernel's behavior; implementing their low-level repair belongs to Custom CUDA Kernels.

These problems can all leave execution resources idle, but they arise at different scheduling levels. A branch rewrite cannot remove a one-block tail, and adding blocks cannot equalize variable per-rank data.

Tail diagnosis Compare where capacity becomes unused. Divergence affects lanes within a warp, skew affects whole tasks or ranks, and a partial final wave can occur even with equal-duration blocks. Each requires evidence at its own level. Diagram concepts: Lane divergence; Block or rank skew; Final partial wave. Lane divergenceBlock or rank skewFinal partial wave
Tail diagnosis

Compare where capacity becomes unused. Divergence affects lanes within a warp, skew affects whole tasks or ranks, and a partial final wave can occur even with equal-duration blocks. Each requires evidence at its own level.

Mental model

Unused lanes, unequal block or rank work, and a partial final grid wave are different causes of idle capacity. Identify which unit finishes late before changing how work is grouped.

11. GPU communication paths and performance

Objective

Establish a correct message-size baseline, identify the actual transport, test one job-local change, and decide whether it deserves an application trial.

How it works

Communication tuning means reducing the time that correct data exchange adds to a workload. NVIDIA Collective Communications Library (NCCL) implements GPU communication operations such as all-reduce. It chooses among available paths and algorithms; it does not create the physical network. InfiniBand is a switched network architecture, RDMA over Converged Ethernet (RoCE) supplies remote direct memory access (RDMA) over Ethernet, and GPUDirect RDMA permits a supported network interface card (NIC) to access GPU memory directly. Fundamentals explains those layers; here the question is which path a real job selected and whether changing one choice helps.

A transport is the software/data-transfer path, such as NCCL's Socket or IB transport. The IB name also covers RoCE through the verbs interface; a log containing IB does not necessarily mean an InfiniBand physical link. An algorithm organizes collective exchanges, while a protocol controls how NCCL chunks and synchronizes those exchanges. A queue pair (QP) is an adapter work-queue pair; increasing QPs can spread network flows, but also adds overhead. These are distinct experimental factors, not a checklist of switches to enable together.

Complete local timing, profiling and load-balance lessons first. Revisit Fundamentals Lesson 12 for networking layers and collective semantics. Use this lesson before Lesson 12's scaling/overlap experiment so a degraded transport is not mistaken for an application scheduling problem.

A collective needs both a usable data path and agreement among its participating processes. Physical connectivity makes a path possible; communicator initialization selects how this job will use it. Performance depends on what happens after that selection.

Qualify the path before measuring candidates

Topology and port-state queries describe the available attachment and network, while NCCL startup logs describe what a particular communicator selected. GPU/NIC proximity, active ports, payload transport and GPU-memory registration are different observations. IP interfaces and RDMA HCAs also use different name spaces. Socket traffic can serve setup even when payloads use RDMA; NET/IB alone therefore cannot establish GPUDirect RDMA. Registration can use a supported peer-memory or DMA-BUF (Linux’s framework for sharing buffers between device drivers) path, so a missing nvidia-peermem module is not conclusive.

Device and topology queries, communicator startup logs and collective benchmark rows answer different questions: what paths exist, what this job selected and how its collective behaved. The NCCL library loaded by a standalone benchmark may differ from the one used by PyTorch.

Network evidence before application tuning Four ordered evidence stages distinguish platform capability, the path selected by a job, correct collective timing and application benefit. Each stage has a different observation. A failed or unknown prerequisite prevents a stronger claim. 1 Capability GPU/NIC topology, active fabric, qualified registration 2 Selected path NCCL startup diagnostics; not an adapter-name guess 3 Collective result Zero errors, full size curve, three independent runs 4 Application benefit Repeat fixed-work scaling and exposed-overlap checksUnknown or failed evidence is a limitation, not permission to configure the cluster.
Network evidence before application tuning

Four ordered evidence stages distinguish platform capability, the path selected by a job, correct collective timing and application benefit. Each stage has a different observation. A failed or unknown prerequisite prevents a stronger claim.

Read a complete size curve, not its best row

An asynchronous collective returns a Work handle representing pending work. For this CUDA/NCCL path, work.wait() joins completion to the current CUDA stream; it does not by itself mean the CPU has waited for device completion. A host timing observation still needs the relevant event or device synchronization.

The logical payload is the tensor size being reduced. Dividing that size by elapsed time gives algorithmic bandwidth. NCCL Tests also reports a collective-specific normalized bus bandwidth. For all-reduce with N ranks and logical payload S bytes, algbw = S / time_seconds / 1e9 and busbw = algbw × 2(N−1)/N. The second expression is a normalization for comparing collective work; it is not a hardware traffic counter. With two ranks the multiplier is one, so equal algbw and busbw are expected. They do not establish saturation. Keep MiB (2²⁰ bytes), GB/s (10⁹ bytes/s), and link rates in Gb/s (bits/s) distinct.

Why a comparison needs a fresh communicator

Automatic selection is the baseline for identifying a useful intervention. Transport, GPU-memory access, collective algorithm and QP count change different parts of execution. A comparison is meaningful only when the selected path is eligible and all other work, ranks and transport conditions remain fixed. Communicator initialization consumes these settings, so a fresh process isolates a candidate from an already initialized baseline. Site interface/plugin configuration is part of the environment contract; inherited experimental overrides would confound the comparison. More network flows can improve distribution while adding latency and adapter overhead, so extra configuration is not evidence of improvement.

MPI, the Message Passing Interface, coordinates cooperating processes. In an MPI-enabled NCCL benchmark, MPI coordinates ranks while NCCL performs the GPU collective.

Two fast GPUs can spend most of a step waiting for communication. Wrong placement, a slow link, network congestion or one late rank can overwhelm a small algorithmic improvement. A synthetic all-reduce curve isolates part of the problem; only a subsequent application measurement establishes useful benefit.

Mental model

Separate four claims: the platform supports a path; this job selected it; the collective performs correctly and quickly on it; the application benefits. Each claim needs its own evidence. Neither a product name nor a high utilization percentage establishes all four. Begin with the actual GPU → local attachment → NIC → fabric → remote NIC → GPU path, then examine operation semantics and timing.

12. Distributed scaling and communication overlap

Objective

Separate useful compute, communication, exposed communication, and synchronization imbalance.

How it works

Distributed optimization asks how work and communication combine across processes. A rank identifies a participating process. Data-parallel execution gives ranks different input work; in training, Distributed Data Parallel (DDP) keeps a model replica on each rank and combines gradients. Parameters are the model's adjustable values; loss is the numerical objective used to judge its output. A gradient describes how changing a parameter affects loss; backward computes gradients, and the optimizer uses them to update parameters. This short training example illustrates a general communication dependency rather than replacing the Training course.

A collective is a group communication operation. A bucket combines several values into one transfer, and becomes ready when those values have been produced. Communication is overlapped when independent computation progresses at the same time. Exposed communication is the part still delaying completion on the critical path—the chain of dependencies that determines total elapsed time. An asynchronous call returning early alone does not demonstrate useful overlap.

A measured single-GPU baseline, local imbalance diagnosis and Lesson 11's qualified communication path are prerequisites for useful scaling evidence. Distributed execution adds data partitioning, process placement and collective dependencies; one slow rank can now set the completion time for all ranks.

In fixed-work strong scaling, the same global task is split among more ranks. Compare its one-rank time T1 with its N-rank time TN: speedup is T1/TN, and efficiency is T1/(N*TN). For two ranks TN is T2. Weak scaling asks a different question: each rank keeps the same local work, so adding ranks increases the global task.

DDP illustrates the dependencies. Each rank holds a model replica and processes its assigned input. DDP averages gradients across ranks before the dependent optimizer update. With equal-sized disjoint batches and the same local mean-loss convention, a global batch of 64 can be split into 32 examples per rank on two ranks. Giving each rank 64 would double the work. Initial state, data and optimizer settings must also agree; reduced-precision reduction order can still cause numerical differences.

Fixed-work one-rank and two-rank critical paths A one-rank baseline contains the complete compute interval. A two-rank fixed-global-work run shortens per-rank compute but adds an arrival wait for the early rank and collective communication. The non-overlapped collective is exposed communication, not an additional interval after the collective. Speedup is determined by the slowest rank's complete interval, not by shorter local compute alone. one rank rank 0 rank 1 complete fixed global work on one GPU baseline end-to-end interval rank 0 local compute half of fixed global work rank 1 local compute straggler example collective message size + fabric collective all ranks participate arrival wait step ends here collective = exposed communication compare full intervals Hold global work fixed for strong scaling speedup = one-rank interval ÷ slowest two-rank interval
Fixed-work one-rank and two-rank critical paths

A one-rank baseline contains the complete compute interval. A two-rank fixed-global-work run shortens per-rank compute but adds an arrival wait for the early rank and collective communication. The non-overlapped collective is exposed communication, not an additional interval after the collective. Speedup is determined by the slowest rank's complete interval, not by shorter local compute alone.

Backward produces gradients progressively. A bucket groups gradients for communication and becomes ready when all its required gradients have been produced. A smaller bucket may become ready sooner, giving its collective more time to overlap remaining backward computation. It also creates more collectives and pays more fixed latency. A larger bucket amortizes that overhead but may start too late to hide its transfer. The optimizer waits for all gradients it needs, so any unfinished communication remains exposed on the critical path.

Collective overlap Time runs downward in both columns. A ready bucket begins communication before independent backward work ends. Only the unfinished tail then delays the dependent update. Bar lengths are schematic, not measurements. Diagram concepts: Backward work; Gradient all-reduce; Exposed communication. ComputeCollectiveBackward workGradientall-reduceExposedcommunicationBucket readyCompute endsTime ↓
Collective overlap

Time runs downward in both columns. A ready bucket begins communication before independent backward work ends. Only the unfinished tail then delays the dependent update. Bar lengths are schematic, not measurements.

An asynchronous collective returns a Work handle while the operation is pending. Independent computation can proceed before joining the result. For ordinary CUDA/NVIDIA Collective Communications Library (NCCL) work, work.wait() establishes the dependency on the current CUDA stream; it does not universally mean that the CPU waited for every device operation. A CPU timer for completed GPU work still needs the relevant event or device synchronization before it stops. Buffers must remain valid, and ranks must preserve matching collective order.

A timeline connects bucket readiness, collective start and end, independent computation and the final consumer wait. It must establish actual overlap; early return from a call cannot do so. The slowest rank sets group completion, and its late arrival must be separated from time spent transferring data.

async_op=True or a non-default stream proves only asynchronous submission. The collective still delays the step if consumers wait immediately, if it contends with compute, or if the slowest rank arrives late.

Non-uniform memory access (NUMA) means that a CPU’s access cost depends on which socket owns the memory. Placing communication buffers and processes near their GPU and network attachment can avoid extra host interconnect traffic; placement must be verified for the actual allocation.

Mental model

Distributed speedup depends on fixed work, per-rank work, collective volume, overlap, and the slowest rank. Communication hidden behind useful compute is not on the critical path. GPU/CPU/NIC NUMA placement and transport health are qualified before NCCL algorithm or protocol tuning.

13. Choosing an optimization layer

Objective

Choose the lowest-maintenance optimization layer that meets the requirement.

How it works

The framework, library, compiler and custom-kernel layers solve different parts of a GPU program. A framework such as PyTorch composes tensor operations. Libraries supply maintained implementations: cuBLAS provides linear algebra, cuDNN neural-network primitives, and CUB parallel building blocks such as reductions within CUDA Core Compute Libraries (CCCL). CUTLASS provides composable templates for matrix kernels. A compiler transforms source or an operation graph into executable code. A custom kernel is device code whose implementation and support contract you maintain.

A hotspot is a region responsible for a meaningful part of the measured cost. An epilogue performs output-side work such as bias and activation after a matrix product. Bias adds an offset; an activation applies a nonlinear function to the result. ReLU, the rectified linear unit, is the activation max(0, x): it replaces negative values with zero and leaves nonnegative values unchanged. A fallback is a deliberately supported alternative for inputs outside a specialization's scope, not permission to hide unsupported behavior. Escalation means selecting the smallest layer that can solve the proven problem while keeping correctness and maintenance manageable.

The earlier lessons identify a causal limiter. Escalation asks which existing abstraction can remove that limiter while preserving correctness, portability, and operational simplicity.

The appropriate implementation layer follows from the missing capability. If unnecessary batching or framework work causes the delay, changing that work may solve it without replacing the kernel. If a maintained operator already expresses the desired calculation, PyTorch, cuBLAS, cuDNN, CUB/CCCL or a supported attention engine can provide an implementation with an existing support path.

When repeated submission or intermediates are the problem, compilation, fusion or CUDA Graph replay may address that specific cost. When a matrix product is already efficient but its output-side work needs specialization, a CUTLASS skeleton with a custom epilogue may be sufficient. Handwritten CUDA becomes a candidate when a meaningful hotspot remains and maintained paths do not express the required semantics efficiently.

Library-first decision Read downward only while an important gap remains. Stop at a maintained option that satisfies the operation and performance contract. The final custom path inherits correctness, coverage and maintenance obligations. Diagram concepts: Framework or compiler; Maintained library; Narrow custom CUDA gap. Framework or compilerMaintained libraryNarrow custom CUDA gap
Library-first decision

Read downward only while an important gap remains. Stop at a maintained option that satisfies the operation and performance contract. The final custom path inherits correctness, coverage and maintenance obligations.

Each option brings a scope: supported shapes and dtypes, numerical behavior, portability, observability, fallback behavior and an owner who maintains it. A microbenchmark gain contributes to the application only through the time it removes from the critical path. Correctness and maintenance effort therefore belong in the decision alongside elapsed time. The Custom CUDA course develops the additional indexing, masking, synchronization, testing and version responsibilities.

Numerical comparison needs an appropriate reference. A higher-precision calculation helps distinguish different valid rounding paths from a changed formula. Unit roundoff describes the relative rounding scale of normal floating-point values, but cancellation can make a small final result unusually sensitive to intermediate rounding.

For example, 1.125 * 3.625 - 4 = 0.078125 in exact arithmetic. Rounding the product to bfloat16 (BF16) first gives 4.0625, leaving 0.0625 after subtraction. The small final difference comes from a much larger intermediate. An acceptance rule based only on relative error in the small result can misclassify that rounding path; the rule must reflect the operation's actual rounding structure.

Custom code can win a microbenchmark yet lose end to end, duplicate a maintained library, or become incompatible with new shapes and software. The optimization layer is an engineering cost decision, not a badge of sophistication.

Mental model

Mature libraries encode hardware-specific algorithms and ongoing maintenance. Framework composition, compilation, library selection, or a custom epilogue often captures the value without owning an entire kernel.

14. GPU fabric topology and peer traffic

Objective

Distinguish local peer traffic from inter-node transfers and interpret a verified peer matrix without treating an average as proof of every path.

How it works

A GPU fabric is the collection of links and switches connecting devices. NVLink/NVSwitch connects the eight H100s inside a worker; InfiniBand connects separate workers. A one-GPU TCP worker cannot supply evidence about either eight-GPU peer paths or the intended cross-node fabric. First verify placement, then test the relevant path. Eight devices produce 56 directed peer pairs; a missing pair invalidates a full-matrix claim. Copy engines move data through dedicated transfer hardware, while kernels execute on streaming multiprocessors (SMs). These paths can move the same bytes with different resource costs. Use the measured minimum and per-pair matrix to locate an asymmetry before proposing a driver or fabric fault.

GPU fabric topology and peer traffic Read the bidirectional connectors as possible transfer directions, not simultaneous measured traffic. A→B and B→A are separate cases. Eight GPUs have 8 × 7 = 56 directed pairs; the source and destination never coincide in the peer matrix. Diagram concepts: GPU A: source or destination; NVLink / NVSwitch path; GPU B: destination or source. GPU A: source ordestinationNVLink / NVSwitch pathGPU B: destination orsource
GPU fabric topology and peer traffic

Read the bidirectional connectors as possible transfer directions, not simultaneous measured traffic. A→B and B→A are separate cases. Eight GPUs have 8 × 7 = 56 directed pairs; the source and destination never coincide in the peer matrix.

The linked advanced labs require the separate two-node, sixteen-H100 cluster. Confirm eight full GPUs per worker, healthy NVLink/NVSwitch and active InfiniBand. Capture each rank separately; profiler overhead belongs to diagnostic evidence. Grafana provides measured comparison summaries and job-window context. State what the evidence can establish before choosing the next change.

Consider two peer pairs carrying the same 64 MiB buffer. If one takes 0.25 ms and the other 0.50 ms, the second path supplies half the useful rate. That difference does not identify a bad switch: first verify direction, engine, device placement, repeated variation and competing work. Inspect the vendor matrix before averaging. The diagonal is not a peer transfer and must not be included as a zero-bandwidth link. Increasing buffer size is a separate workload study because setup overhead becomes a smaller fraction of elapsed time. Preserve the same buffer and iteration count when comparing execution engines. Stop if any directed pair fails data verification.

Mental model

A peer matrix describes directed paths under a particular transfer engine. Verify each path and its data before using the minimum or average to explain the fabric.

15. GPU memory over InfiniBand

Objective

Distinguish host and GPU memory registration, interpret RDMA transfer units, and isolate the effect of queue depth while preserving verified payloads.

How it works

Remote direct memory access (RDMA) lets a network adapter read or write registered memory without the remote CPU copying each payload. The network interface controller (NIC), called a host channel adapter (HCA) on InfiniBand, performs the transfer. Memory registration exposes a specific buffer to that adapter with the required access rights. Host registration and GPU registration are different paths; GPUDirect RDMA permits the NIC to access GPU memory. DMA-BUF is Linux’s buffer-sharing interface; nvidia-peermem is NVIDIA’s peer-memory kernel module. The selected GPU-registration path must match the installed driver, kernel and NIC stack. Check the GPU-to-NIC topology and actual registration evidence before interpreting speed. A TCP address may be used for connection bootstrap even when payloads use InfiniBand. Conversely, a NET/IB log alone does not prove direct GPU memory access. At 200 Gbit/s bidirectional aggregate traffic, dividing by eight gives 25 GB/s aggregate; that is not 25 GB/s in each direction. Keep sizes and queue depth equal when comparing memory types.

GPU memory over InfiniBand Compare two memory-registration choices feeding the same network adapter, not a sequence from host memory through GPU memory. The selected path determines the accessible buffer; endpoint validation proves payload correctness, while vendor timing supplies the useful transfer rate. Diagram concepts: Host buffer registered to HCA; GPU buffer registered to HCA; HCA transfers over InfiniBand. Host buffer registered toHCAGPU buffer registered toHCAHCA transfers overInfiniBand
GPU memory over InfiniBand

Compare two memory-registration choices feeding the same network adapter, not a sequence from host memory through GPU memory. The selected path determines the accessible buffer; endpoint validation proves payload correctness, while vendor timing supplies the useful transfer rate.

The linked advanced lab requires the separate two-node, sixteen-H100 cluster and a qualified GPU-memory registration path. Inspect endpoint payload validation, registration evidence and the vendor transfer timings. This RDMA-only transfer does not provide a useful CUDA kernel timeline, so Nsight Systems is explicitly inapplicable. Grafana compares measured transfer results and supplies job-window context; sampled GPU activity cannot establish network latency or prove GPUDirect RDMA.

For a controlled experiment, hold the selected HCA, GPU, message size, iteration count, queue-pair count and transmit depth fixed, changing only host versus GPU memory. Require both endpoints to validate nonzero received bytes. Next, freeze the successful GPU-memory path and change transmit depth alone. A deeper queue can hide latency until bandwidth or another resource saturates; it can also add work without improving useful rate. Neither result authorizes changing switch policy. Inspect the owner-qualified topology and runtime evidence before proposing an infrastructure intervention. Keep connection logs private and report the measured path, units and registration method with the result.

Mental model

Registration determines which memory the NIC can access. Queue depth determines how much work can remain in flight; both the validated path and the measurement units must be known before interpreting bandwidth.

16. Communication ownership and rank timelines

Objective

Use per-rank timelines to identify the dependency that limits a collective step and distinguish useful overlap from resource contention.

How it works

A rank is one process in a distributed group. A collective combines or exchanges values across that group. It has both a value contract and a participation contract: every required rank must execute compatible operations in compatible order. A hierarchy can reduce cross-node participants but adds local reductions and broadcasts. The NVIDIA Collective Communications Library (NCCL) already chooses topology-aware algorithms, so an explicit hierarchy may be slower. Overlap helps only when independent computation occupies time that would otherwise be exposed communication. The completion time is determined by the slowest participating rank. Use PyTorch traces for framework attribution, Systems CUDA/NCCL timelines for cross-process dependencies, and a separate unprofiled run for the final number. A shorter wait accompanied by slower general matrix multiplication (GEMM) is not automatically an end-to-end improvement; communication and compute can compete for streaming multiprocessor (SM) and memory resources.

Communication ownership and rank timelines Arrows show dependencies for one distributed iteration, not elapsed duration. Independent compute may run while communication is in flight, but a dependent consumer must wait for the required collective result. The last required rank determines completion. Diagram concepts: Ranks produce owned values; Compatible collective on every rank; Dependent work waits for completion. Ranks produce owned valuesCompatible collective onevery rankDependent work waits forcompletion
Communication ownership and rank timelines

Arrows show dependencies for one distributed iteration, not elapsed duration. Independent compute may run while communication is in flight, but a dependent consumer must wait for the required collective result. The last required rank determines completion.

The linked advanced labs require the separate two-node, sixteen-H100 cluster. Confirm eight full GPUs per worker, healthy NVLink/NVSwitch and active InfiniBand. Capture each rank separately; profiler overhead belongs to diagnostic evidence. Grafana provides measured comparison summaries and job-window context. State what the evidence can establish before choosing the next change.

Suppose serialized communication takes 4 ms and independent compute takes 6 ms. Ideal overlap would approach 6 ms, but actual overlap can contend for SMs or memory and take 8 ms. An 8 ms result improves on a 10 ms serial step while still falling short of that ideal. If compute expands to 11 ms under contention, a shorter exposed collective wait can accompany a slower total step. Mark submission, useful compute and dependency waits separately. Compare the same iteration on every rank, because the fastest rank cannot authorize the next distributed step. Retain the distributions and separate instrumentation cost from the clean measurement.

Mental model

Distributed completion follows the last required dependency. Overlap is useful only when it shortens the complete step without changing the value or participation contract.

Practical labs

Download results

Download all lab results:
Grafana dashboards, Small and Large results

Setup the lab environment:
Lab setup guide

Lab 01: Compare CPU timers and CUDA events

This lab measures one GPU operation three ways to expose a common benchmarking mistake: timing only the host's submission of asynchronous work. You will compare unsynchronized host time, synchronized host time, and CUDA-event time.

Complete source: labs/01_timing_basics.py
"""Show why host wall-clock timing without synchronization is misleading."""

from __future__ import annotations

import argparse
import statistics
import time

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    size = 2_048 if args.workload == "small" else 8_192
    # Create the synthetic tensors used by this experiment.
    a = torch.randn((size, size), device="cuda", dtype=torch.bfloat16)
    b = torch.randn((size, size), device="cuda", dtype=torch.bfloat16)

    def operation() -> object:
        return a @ b

    for _ in range(args.warmup):
        operation()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    unsynchronized = []
    for _ in range(args.iterations):
        start = time.perf_counter()
        operation()
        unsynchronized.append((time.perf_counter() - start) * 1_000)
    torch.cuda.synchronize()
    synchronized = []
    for _ in range(args.iterations):
        start = time.perf_counter()
        operation()
        torch.cuda.synchronize()
        synchronized.append((time.perf_counter() - start) * 1_000)
    event_samples = cuda_times_ms(
        torch, operation, warmup=args.warmup, iterations=args.iterations
    )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="01_timing_basics",
        environment=environment,
        measurements={
            "host_without_sync_median_ms": round(statistics.median(unsynchronized), 4),
            "host_with_sync_median_ms": round(statistics.median(synchronized), 4),
            "cuda_events": summarize_ms(event_samples),
        },
        correctness={"finite_output": bool(torch.isfinite(operation()).all().item())},
    )
    print(f"Completed timing comparison: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/01_timing_basics.sbatch --workload small

# Optional profiling
sbatch slurm/01_timing_basics.sbatch --workload small --profiler all

Lab 02: Remove unnecessary per-step host synchronization

Fetching a CUDA scalar into Python can force the host to wait for the GPU. In a repeated loop, those waits can prevent efficient submission of later work.

Complete source: labs/02_sync_trap.py
"""Compare per-step .item() synchronization with one delayed reduction."""

from __future__ import annotations

import argparse
import math
import statistics
import time

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    resolve_int_override,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def measure(torch: object, function: object, warmup: int, iterations: int) -> float:
    for _ in range(warmup):
        function()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    samples = []
    for _ in range(iterations):
        torch.cuda.synchronize()
        start = time.perf_counter()
        function()
        torch.cuda.synchronize()
        samples.append((time.perf_counter() - start) * 1_000)
    return statistics.median(samples)


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--steps", type=int, default=None)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    steps = resolve_int_override(
        args.steps,
        25 if args.workload == "small" else 200,
        option="--steps",
    )
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    # Create the synthetic tensors used by this experiment.
    x = torch.randn(8_000_000, device="cuda")

    def synchronized_loop() -> float:
        total = 0.0
        for _ in range(steps):
            total += (x.square().mean()).item()
        return total

    def delayed_loop() -> float:
        values = []
        for _ in range(steps):
            values.append(x.square().mean())
        return float(torch.stack(values).sum().item())

    sync_ms = measure(torch, synchronized_loop, args.warmup, args.iterations)
    delayed_ms = measure(torch, delayed_loop, args.warmup, args.iterations)
    expected = synchronized_loop()
    actual = delayed_loop()
    correct = (
        math.isfinite(expected)
        and math.isfinite(actual)
        and abs(expected - actual) <= 1e-6 + abs(expected) * 1e-5
    )
    if not correct:
        raise SystemExit("The two reduction strategies returned different values.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="02_sync_trap",
        environment=environment,
        measurements={
            "steps": steps,
            "per_step_item_median_ms": round(sync_ms, 4),
            "delayed_item_median_ms": round(delayed_ms, 4),
        },
        correctness={"equivalent_sum": True},
    )
    print(f"Completed synchronization experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/02_sync_trap.sbatch --workload small

# Optional profiling
sbatch slurm/02_sync_trap.sbatch --workload small --profiler all

Lab 03: Compare eager and compiled pointwise execution

Several pointwise operations can repeatedly read and write intermediate tensors. Compilation may combine that work and reduce launches or memory traffic.

Complete source: labs/03_compile_fusion.py
"""Compare eager and compiled execution of a pointwise workload."""

from __future__ import annotations

import argparse
import time

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    elements = 16_000_000 if args.workload == "small" else 128_000_000
    # Create the synthetic tensors used by this experiment.
    x = torch.randn(elements, device="cuda")
    bias = torch.randn(elements, device="cuda")

    def workload(value: object, offset: object) -> object:
        hidden = value * 1.25 + offset
        gated = torch.nn.functional.silu(hidden) * hidden
        return torch.tanh(gated + 0.1)

    compiled = torch.compile(workload, fullgraph=True)
    compile_started = time.perf_counter()
    compiled(x, bias)
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    first_call_ms = (time.perf_counter() - compile_started) * 1_000
    eager_samples = cuda_times_ms(
        torch,
        lambda: workload(x, bias),
        warmup=args.warmup,
        iterations=args.iterations,
    )
    compiled_samples = cuda_times_ms(
        torch,
        lambda: compiled(x, bias),
        warmup=args.warmup,
        iterations=args.iterations,
    )
    correct = bool(
        torch.allclose(workload(x, bias), compiled(x, bias), rtol=1e-5, atol=1e-6)
    )
    if not correct:
        raise SystemExit("Compiled and eager results diverged.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="03_compile_fusion",
        environment=environment,
        measurements={
            "elements": elements,
            "compiled_first_call_ms": round(first_call_ms, 4),
            "eager": summarize_ms(eager_samples),
            "compiled": summarize_ms(compiled_samples),
        },
        correctness={"allclose": True},
    )
    print(f"Completed compile experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/03_compile_fusion.sbatch --workload small

# Optional profiling
sbatch slurm/03_compile_fusion.sbatch --workload small --profiler all

Lab 04: Replay a fixed-shape workload with a CUDA Graph

A CUDA Graph is a reusable plan of device operations and their dependencies. Capture records compatible work into the plan; replay executes it again, rather than returning cached output values.

Complete source: labs/04_cuda_graphs.py
"""Capture and replay a fixed-shape inference step with a CUDA Graph."""

from __future__ import annotations

import argparse

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    width = 2_048 if args.workload == "small" else 8_192
    batch = 32 if args.workload == "small" else 128
    # Create the synthetic tensors used by this experiment.
    static_input = torch.randn((batch, width), device="cuda", dtype=torch.bfloat16)
    weight = torch.randn((width, width), device="cuda", dtype=torch.bfloat16)

    def eager_step() -> object:
        return torch.nn.functional.silu(static_input @ weight)

    warmup_stream = torch.cuda.Stream()
    warmup_stream.wait_stream(torch.cuda.current_stream())
    with torch.cuda.stream(warmup_stream):
        for _ in range(max(3, args.warmup)):
            eager_step()
    torch.cuda.current_stream().wait_stream(warmup_stream)
    graph = torch.cuda.CUDAGraph()
    with torch.cuda.graph(graph):
        captured_output = eager_step()

    def replay() -> object:
        graph.replay()
        return captured_output

    eager_samples = cuda_times_ms(
        torch, eager_step, warmup=args.warmup, iterations=args.iterations
    )
    graph_samples = cuda_times_ms(
        torch, replay, warmup=args.warmup, iterations=args.iterations
    )
    reference = eager_step()
    replay()
    correct = bool(torch.allclose(reference, captured_output, rtol=1e-2, atol=1e-2))
    if not correct:
        raise SystemExit("CUDA Graph replay did not match eager execution.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="04_cuda_graphs",
        environment=environment,
        measurements={
            "shape": [batch, width],
            "eager": summarize_ms(eager_samples),
            "cuda_graph": summarize_ms(graph_samples),
        },
        correctness={"allclose": True, "fixed_shape": True},
    )
    print(f"Completed CUDA Graph experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/04_cuda_graphs.sbatch --workload small

# Optional profiling
sbatch slurm/04_cuda_graphs.sbatch --workload small --profiler all

Lab 05: Locate waiting in a DataLoader pipeline

GPU utilization can be limited by preparing and delivering the next batch rather than by the device computation itself. This lab compares zero and four DataLoader workers on deterministic synthetic samples.

Complete source: labs/05_input_pipeline.py
"""Compare serial and worker-backed DataLoader pipelines feeding an H100."""

from __future__ import annotations

import argparse
import math
import time

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    resolve_int_override,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--batches", type=int, default=None)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    batches = resolve_int_override(
        args.batches,
        20 if args.workload == "small" else 100,
        option="--batches",
    )
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    feature_width = 4_096

    class SyntheticDataset(torch.utils.data.Dataset):
        def __len__(self) -> int:
            return (batches + args.warmup) * 8

        def __getitem__(self, index: int) -> object:
            generator = torch.Generator().manual_seed(index)
            # Create the synthetic tensors used by this experiment.
            sample = torch.randn(feature_width, generator=generator)
            return sample.sin().cos()

    dataset = SyntheticDataset()

    def run_loader(workers: int) -> tuple[dict[str, object], float]:
        loader = torch.utils.data.DataLoader(
            dataset,
            batch_size=8,
            num_workers=workers,
            pin_memory=True,
            persistent_workers=workers > 0,
            prefetch_factor=2 if workers > 0 else None,
        )
        phase_samples: dict[str, list[float]] = {
            "batch_ready_gap": [],
            "h2d": [],
            "device_consumption": [],
            "end_to_end": [],
        }
        checksum = torch.zeros((), device="cuda")
        iterator = iter(loader)
        for _ in range(args.warmup):
            warmup_batch = next(iterator).to("cuda", non_blocking=True)
            warmup_batch.square().mean()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        host_batch_bytes = None
        all_batches_pinned = True
        for _ in range(batches):
            step_started = time.perf_counter()
            host_batch = next(iterator)
            batch_ready = time.perf_counter()
            current_bytes = host_batch.numel() * host_batch.element_size()
            if host_batch_bytes is None:
                host_batch_bytes = current_bytes
            elif current_bytes != host_batch_bytes:
                raise SystemExit("Input batches changed byte size during measurement.")
            all_batches_pinned = all_batches_pinned and bool(host_batch.is_pinned())
            h2d_start = torch.cuda.Event(enable_timing=True)
            h2d_end = torch.cuda.Event(enable_timing=True)
            compute_start = torch.cuda.Event(enable_timing=True)
            compute_end = torch.cuda.Event(enable_timing=True)
            h2d_start.record()
            batch_value = host_batch.to("cuda", non_blocking=True)
            h2d_end.record()
            compute_start.record()
            checksum = checksum + batch_value.square().mean()
            compute_end.record()
            compute_end.synchronize()
            step_finished = time.perf_counter()
            phase_samples["batch_ready_gap"].append(
                (batch_ready - step_started) * 1_000
            )
            phase_samples["h2d"].append(float(h2d_start.elapsed_time(h2d_end)))
            phase_samples["device_consumption"].append(
                float(compute_start.elapsed_time(compute_end))
            )
            phase_samples["end_to_end"].append((step_finished - step_started) * 1_000)
        assert host_batch_bytes is not None
        return (
            {
                "num_workers": workers,
                "prefetch_factor": 2 if workers > 0 else None,
                "pin_memory": True,
                "non_blocking": True,
                "host_batch_bytes": host_batch_bytes,
                "all_batches_pinned": all_batches_pinned,
                "phases": {
                    name: {
                        **summarize_ms(samples),
                        "sample_count": len(samples),
                    }
                    for name, samples in phase_samples.items()
                },
            },
            float(checksum.item()),
        )

    serial, serial_sum = run_loader(0)
    worker, worker_sum = run_loader(4)
    correct = (
        math.isfinite(serial_sum)
        and math.isfinite(worker_sum)
        and abs(serial_sum - worker_sum) <= 1e-6 + abs(serial_sum) * 1e-5
    )
    if not correct:
        raise SystemExit("Pipeline variants produced different checksums.")
    if not serial["all_batches_pinned"] or not worker["all_batches_pinned"]:
        raise SystemExit("DataLoader returned an unpinned timed batch.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="05_input_pipeline",
        environment=environment,
        measurements={
            "batches": batches,
            "timing_boundary": "single-stream serialized component evidence",
            "variants": {"num_workers_0": serial, "num_workers_4": worker},
        },
        correctness={"checksum": True, "all_batches_pinned": True},
    )
    print(f"Completed input pipeline experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/05_input_pipeline.sbatch --workload small

# Optional profiling
sbatch slurm/05_input_pipeline.sbatch --workload small --profiler all

Lab 07: Build a readable profiler map of a workload

A useful profile connects application regions to GPU activity so that you can explain a delay, not merely collect a large report. This lab provides labeled PyTorch and NVTX regions around a small tensor workload. Normal execution uses the built-in PyTorch collector; external captures disable it.

Complete source: labs/07_profile_workload.py
"""Create labeled PyTorch and NVTX regions for system and kernel profiling."""

from __future__ import annotations

import argparse
import os

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--export-trace", action="store_true")
    parser.add_argument(
        "--external-only",
        action="store_true",
        help="Run NVTX regions without nesting the PyTorch profiler.",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    width = 2_048 if args.workload == "small" else 8_192
    # Create the synthetic tensors used by this experiment.
    x = torch.randn((64, width), device="cuda", dtype=torch.bfloat16)
    weight = torch.randn((width, width), device="cuda", dtype=torch.bfloat16)

    def workload() -> object:
        with torch.cuda.nvtx.range("train_step"):
            with torch.cuda.nvtx.range("projection"):
                hidden = x @ weight
            with torch.cuda.nvtx.range("activation_and_reduction"):
                return torch.nn.functional.gelu(hidden).float().square().mean()

    for _ in range(args.warmup):
        workload()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    profiler = None
    loss = None
    if args.external_only:
        for _ in range(args.iterations):
            loss = workload()
        torch.cuda.synchronize()
    else:
        os.environ["COURSE_PROFILE_TOOL"] = "torch"
        with torch.profiler.profile(
            activities=[
                torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA,
            ],
            record_shapes=True,
            profile_memory=True,
        ) as profiler:
            for _ in range(args.iterations):
                loss = workload()
                profiler.step()
    assert loss is not None
    trace_path = None
    if args.export_trace:
        if profiler is None:
            raise SystemExit(
                "--export-trace requires the PyTorch profiler; omit --external-only."
            )
        args.output_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
        trace_directory = args.output_dir / f"07-profile-run-{args.run_id}"
        try:
            trace_directory.mkdir(mode=0o700)
        except FileExistsError as exc:
            raise SystemExit(
                f"Refusing to reuse an existing trace directory: {trace_directory}"
            ) from exc
        trace_path = trace_directory / "trace.json"
        profiler.export_chrome_trace(str(trace_path))
        os.chmod(trace_path, 0o600)
    top_cuda = (
        "Captured by the external NVIDIA profiler."
        if profiler is None
        else profiler.key_averages().table(sort_by="self_cuda_time_total", row_limit=8)
    )
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="07_profile_workload",
        environment=environment,
        measurements={
            "trace_exported": trace_path is not None,
            "top_cuda_table": top_cuda,
        },
        correctness={"finite_loss": bool(torch.isfinite(loss).item())},
    )
    print(top_cuda)
    print(f"Completed profiling workload: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
Framework-to-kernel attribution with NVTX A train-step NVTX range contains forward, backward, and optimizer phases. PyTorch operators inside a phase lead to CUDA kernels, copies, and allocations in the profiler trace. NVTX: train_step forward projection · attention · loss backward autograd operators optimizer updates · zero grad PyTorch operator shape · calls · allocation CUDA activity kernel · memcpy · sync trace question what dominates and why?
Framework-to-kernel attribution with NVTX

A train-step NVTX range contains forward, backward, and optimizer phases. PyTorch operators inside a phase lead to CUDA kernels, copies, and allocations in the profiler trace.

Nsight Systems evidence for synchronization and launch fixes Two baseline timelines show repeated CPU synchronization waits and many small kernels with host gaps. Corresponding candidate timelines move the scalar read after GPU work and replace many launches with a fused compiled region. sync baseline delayed read launch baseline compiled candidate kernel host wait kernel host wait kernel host wait queued GPU reductions one read short kernels + submission gaps compiled/fused device region Compare equivalent NVTX ranges and use unprofiled JSON timing for the keep/reject decision.
Nsight Systems evidence for synchronization and launch fixes

Two baseline timelines show repeated CPU synchronization waits and many small kernels with host gaps. Corresponding candidate timelines move the scalar read after GPU work and replace many launches with a fused compiled region.

# Normal execution
sbatch slurm/07_profile_workload.sbatch --workload small --export-trace

# Optional profiling
sbatch slurm/07_profile_workload.sbatch --workload small --export-trace --profiler all

Lab 09: Build a causal compilation experiment

This capstone turns a promising optimization into a controlled comparison. You will evaluate eager versus compiled execution for the same BF16 matmul-and-activation pipeline, preserving shapes, inputs, residency, and mathematical work.

Complete source: labs/09_capstone.py
"""Compare eager and compiled execution with dtype, residency, and work fixed."""

from __future__ import annotations

import argparse
import statistics
import time
from typing import Any, Callable

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    size = 2_048 if args.workload == "small" else 8_192
    # Create the synthetic tensors used by this experiment.
    device_a = torch.randn((size, size), device="cuda", dtype=torch.bfloat16)
    device_b = torch.randn((size, size), device="cuda", dtype=torch.bfloat16)

    def workload(a: Any, b: Any) -> Any:
        return torch.tanh(torch.nn.functional.silu(a @ b) + 0.1)

    compiled = torch.compile(workload, fullgraph=True)
    compiled(device_a, device_b)
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()

    def eager() -> Any:
        return workload(device_a, device_b)

    def compiled_candidate() -> Any:
        return compiled(device_a, device_b)

    def wall_samples(operation: Callable[[], Any]) -> list[float]:
        samples = []
        for _ in range(args.iterations):
            torch.cuda.synchronize()
            started = time.perf_counter()
            operation()
            torch.cuda.synchronize()
            samples.append((time.perf_counter() - started) * 1_000)
        return samples

    trials = []
    allclose = True
    for trial in range(3):
        operations = (
            (("eager", eager), ("compiled", compiled_candidate))
            if trial % 2 == 0
            else (("compiled", compiled_candidate), ("eager", eager))
        )
        measured: dict[str, dict[str, float]] = {}
        for label, operation in operations:
            measured[label] = {
                **{
                    f"cuda_{key}": value
                    for key, value in summarize_ms(
                        cuda_times_ms(
                            torch,
                            operation,
                            warmup=args.warmup,
                            iterations=args.iterations,
                        )
                    ).items()
                },
                **{
                    f"wall_{key}": value
                    for key, value in summarize_ms(wall_samples(operation)).items()
                },
            }
        eager_output = eager()
        compiled_output = compiled_candidate()
        trial_close = bool(
            torch.allclose(eager_output, compiled_output, rtol=1e-2, atol=1e-2)
        )
        allclose = allclose and trial_close
        eager_median = measured["eager"]["cuda_median_ms"]
        compiled_median = measured["compiled"]["cuda_median_ms"]
        trials.append(
            {
                "trial": trial + 1,
                "execution_order": [label for label, _operation in operations],
                "eager": measured["eager"],
                "compiled": measured["compiled"],
                "observed_baseline_to_compiled_ratio": round(
                    eager_median / compiled_median, 4
                ),
                "outputs_match": trial_close,
            }
        )
    if not allclose:
        raise SystemExit("Compiled capstone output failed the BF16 tolerance.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="09_capstone",
        environment=environment,
        measurements={
            "independent_variable": "torch.compile fullgraph versus eager",
            "controlled_factors": {
                "dtype": "bfloat16",
                "input_residency": "both inputs resident on the same GPU",
                "shape": [size, size],
                "operation": "matmul -> SiLU -> add scalar -> tanh",
            },
            "trials": trials,
            "median_observed_ratio_across_trials": round(
                statistics.median(
                    trial["observed_baseline_to_compiled_ratio"] for trial in trials
                ),
                4,
            ),
            "publication_rule": (
                "report this scoped GPU observation only with profiler evidence; "
                "do not generalize it to other shapes or versions"
            ),
        },
        correctness={
            "all_three_trials_match_with_bf16_tolerance": allclose,
            "same_dtype_residency_shape_and_work": True,
        },
    )
    print(f"Completed causal optimization capstone: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/09_capstone.sbatch --workload small

# Optional profiling
sbatch slurm/09_capstone.sbatch --workload small --profiler all

Lab 10: Survey library behavior across shapes and dtypes

Matrix libraries select implementations partly from shape and precision, so nearby dimensions can produce noticeably different performance. This lab surveys matrix widths and dtypes while checking each result against its corresponding reference.

Complete source: labs/10_shape_precision.py
"""Compare matrix shape and precision choices without assuming a speedup."""

from __future__ import annotations

import argparse

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    return parser.parse_args()


def main() -> None:
    # Read the experiment controls before allocating inputs.
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    aligned = 1_024 if args.workload == "small" else 4_096
    misaligned = aligned - 7
    rows = []
    all_finite = True
    all_acceptable = True
    for label, width, dtype in (
        ("bf16_aligned", aligned, torch.bfloat16),
        ("bf16_misaligned", misaligned, torch.bfloat16),
        ("fp32_aligned", aligned, torch.float32),
    ):
        # Create the synthetic tensors used by this experiment.
        left_fp32 = torch.randn((width, width), device="cuda", dtype=torch.float32)
        right_fp32 = torch.randn((width, width), device="cuda", dtype=torch.float32)
        left = left_fp32.to(dtype=dtype)
        right = right_fp32.to(dtype=dtype)
        reference = left_fp32 @ right_fp32
        result = left @ right
        samples = cuda_times_ms(
            torch,
            lambda left=left, right=right: left @ right,
            warmup=args.warmup,
            iterations=args.iterations,
        )
        median_ms = summarize_ms(samples)["median_ms"]
        operations = 2 * width**3
        relative_l2_error = float(
            torch.linalg.vector_norm(result.float() - reference)
            / torch.linalg.vector_norm(reference)
        )
        acceptable = relative_l2_error < (1e-2 if dtype == torch.bfloat16 else 1e-5)
        rows.append(
            {
                "mode": label,
                "width": width,
                "dtype": str(dtype).removeprefix("torch."),
                "timing": summarize_ms(samples),
                "effective_tflops": round(operations / (median_ms / 1_000) / 1e12, 3),
                "relative_l2_error": round(relative_l2_error, 8),
                "numerically_acceptable": acceptable,
            }
        )
        all_finite = all_finite and bool(torch.isfinite(result).all().item())
        all_acceptable = all_acceptable and acceptable
    if not all_finite or not all_acceptable:
        raise SystemExit("A matrix result failed the declared numerical gate.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="10_shape_precision",
        environment=environment,
        measurements={"cases": rows},
        correctness={"all_results_finite": True, "all_numerically_acceptable": True},
    )
    print(f"Completed shape and precision experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/10_shape_precision.sbatch --workload small

# Optional profiling
sbatch slurm/10_shape_precision.sbatch --workload small --profiler all

Lab 12: Follow live, cached, and released GPU memory

Deleting a tensor does not necessarily return its memory reservation to the driver, and emptying the cache cannot free a live tensor. This lab makes those distinctions observable through a short allocation lifecycle.

Complete source: labs/12_allocator_lifetime.py
"""Observe allocated, reserved, reusable, and released CUDA allocator bytes."""

from __future__ import annotations

import argparse
import gc
from typing import Any

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)

    def snapshot() -> dict[str, Any]:
        stats = torch.cuda.memory_stats()
        return {
            "allocated_bytes": int(stats["allocated_bytes.all.current"]),
            "reserved_bytes": int(stats["reserved_bytes.all.current"]),
            "inactive_split_bytes": int(stats["inactive_split_bytes.all.current"]),
            "allocation_retries": int(stats["num_alloc_retries"]),
            "out_of_memory_events": int(stats["num_ooms"]),
        }

    torch.cuda.empty_cache()
    baseline = snapshot()
    scale = 1 if args.workload == "small" else 4

    def allocate(mebibytes: int) -> Any:
        tensor = torch.empty(
            mebibytes * scale * 2**20,
            dtype=torch.uint8,
            device="cuda",
        )
        tensor.fill_(1)
        return tensor

    first = allocate(64)
    middle = allocate(32)
    last = allocate(64)
    after_three_allocations = snapshot()
    del middle
    gc.collect()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    after_middle_delete = snapshot()
    replacement = allocate(24)
    after_reuse_candidate = snapshot()
    del last, replacement
    gc.collect()
    torch.cuda.synchronize()
    before_empty_cache_with_first_live = snapshot()
    torch.cuda.empty_cache()
    after_empty_cache_with_first_live = snapshot()
    del first
    gc.collect()
    torch.cuda.synchronize()
    after_all_delete = snapshot()
    torch.cuda.empty_cache()
    after_final_empty_cache = snapshot()

    allocated_dropped = (
        after_middle_delete["allocated_bytes"]
        < after_three_allocations["allocated_bytes"]
    )
    reservation_survived_middle_delete = (
        after_middle_delete["reserved_bytes"]
        >= after_three_allocations["reserved_bytes"]
    )
    first_tensor_was_live = (
        before_empty_cache_with_first_live["allocated_bytes"]
        > baseline["allocated_bytes"]
    )
    empty_cache_preserved_live_allocation = (
        after_empty_cache_with_first_live["allocated_bytes"]
        == before_empty_cache_with_first_live["allocated_bytes"]
    )
    all_lab_allocations_released = (
        after_all_delete["allocated_bytes"]
        < before_empty_cache_with_first_live["allocated_bytes"]
    )
    final_empty_cache_did_not_increase_reservation = (
        after_final_empty_cache["reserved_bytes"] <= after_all_delete["reserved_bytes"]
    )
    if not all(
        (
            allocated_dropped,
            reservation_survived_middle_delete,
            first_tensor_was_live,
            empty_cache_preserved_live_allocation,
            all_lab_allocations_released,
            final_empty_cache_did_not_increase_reservation,
        )
    ):
        raise SystemExit("CUDA allocator lifetime invariants did not hold.")
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="12_allocator_lifetime",
        environment=environment,
        measurements={
            "allocation_scale": scale,
            "baseline": baseline,
            "after_three_allocations": after_three_allocations,
            "after_middle_delete": after_middle_delete,
            "after_reuse_candidate": after_reuse_candidate,
            "before_empty_cache_with_first_live": before_empty_cache_with_first_live,
            "after_empty_cache_with_first_live": after_empty_cache_with_first_live,
            "after_all_delete": after_all_delete,
            "after_final_empty_cache": after_final_empty_cache,
        },
        correctness={
            "allocated_bytes_drop_after_delete": allocated_dropped,
            "reservation_survived_middle_delete": reservation_survived_middle_delete,
            "first_tensor_live_during_empty_cache": first_tensor_was_live,
            "empty_cache_preserved_live_allocation": (
                empty_cache_preserved_live_allocation
            ),
            "all_lab_allocations_released": all_lab_allocations_released,
            "final_empty_cache_did_not_increase_reservation": (
                final_empty_cache_did_not_increase_reservation
            ),
        },
    )
    print(f"Completed allocator-lifetime experiment: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
CUDA allocator lifetime and fragmentation Reserved segments contain active allocations, a freed reusable hole, and inactive split space; deleting tensors changes allocated bytes before empty cache can release eligible segments. live tensor A reusable hole live tensor C split reserved bytes include live allocations and allocator-owned reusable space empty_cache can release only wholly unused eligible cache—not live tensors
CUDA allocator lifetime and fragmentation

Reserved segments contain active allocations, a freed reusable hole, and inactive split space; deleting tensors changes allocated bytes before empty cache can release eligible segments.

# Normal execution
sbatch slurm/12_allocator_lifetime.sbatch --workload small

# Optional profiling
sbatch slurm/12_allocator_lifetime.sbatch --workload small --profiler all

Lab 14: Diagnose synchronization, launch, memory, and compute limits

This workshop supplies controlled examples of four bottleneck classes so you can practice choosing the right evidence. Instead of opening a profiler and guessing, you will select one case, compare baseline and candidate, and explain the causal change.

Complete source: labs/14_profiler_bottlenecks.py
"""Create profile-ready examples for four common GPU bottleneck classes."""

from __future__ import annotations

import argparse
import math
import time
from typing import Any, Callable

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--case",
        choices=("sync", "launch", "memory", "compute"),
        required=True,
        help="Bottleneck mechanism to expose to the profiler.",
    )
    parser.add_argument(
        "--mode",
        choices=("baseline", "optimized"),
        required=True,
        help="Slow baseline or mechanism-matched candidate.",
    )
    return parser.parse_args()


def compile_and_warm(
    torch: Any, function: Callable[[], Any]
) -> tuple[Callable[[], Any], float]:
    compiled = torch.compile(function, fullgraph=True)
    started = time.perf_counter()
    compiled()
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    return compiled, (time.perf_counter() - started) * 1_000


def build_sync_case(
    torch: Any, args: argparse.Namespace
) -> tuple[Callable[[], Any], Callable[[], Any], dict[str, Any]]:
    elements = 2_000_000 if args.workload == "small" else 16_000_000
    steps = 8 if args.workload == "small" else 40
    # Create the synthetic tensors used by this experiment.
    values = torch.randn(elements, device="cuda", dtype=torch.float32)

    def synchronized() -> float:
        total = 0.0
        for _ in range(steps):
            total += values.square().mean().item()
        return total

    def delayed() -> Any:
        reductions = [values.square().mean() for _ in range(steps)]
        return torch.stack(reductions).sum()

    selected = synchronized if args.mode == "baseline" else delayed
    return selected, delayed, {"elements": elements, "steps": steps}


def build_launch_case(
    torch: Any, args: argparse.Namespace
) -> tuple[Callable[[], Any], Callable[[], Any], dict[str, Any]]:
    elements = 262_144 if args.workload == "small" else 1_048_576
    steps = 12 if args.workload == "small" else 30
    values = torch.randn(elements, device="cuda", dtype=torch.float32)

    def pointwise_chain() -> Any:
        output = values
        for _ in range(steps):
            output = torch.tanh(output * 1.001 + 0.01)
        return output

    compile_ms = None
    selected = pointwise_chain
    if args.mode == "optimized":
        selected, compile_ms = compile_and_warm(torch, pointwise_chain)
    return (
        selected,
        pointwise_chain,
        {
            "elements": elements,
            "pointwise_steps": steps,
            "compiled_first_call_ms": compile_ms,
        },
    )


def build_memory_case(
    torch: Any, args: argparse.Namespace
) -> tuple[Callable[[], Any], Callable[[], Any], dict[str, Any]]:
    elements = 8_000_000 if args.workload == "small" else 64_000_000
    values = torch.randn(elements, device="cuda", dtype=torch.float32)
    bias = torch.randn(elements, device="cuda", dtype=torch.float32)

    def pointwise_pipeline() -> Any:
        hidden = values * 1.25 + bias
        gated = torch.nn.functional.silu(hidden) * hidden
        return torch.tanh(gated + 0.1)

    compile_ms = None
    selected = pointwise_pipeline
    if args.mode == "optimized":
        selected, compile_ms = compile_and_warm(torch, pointwise_pipeline)
    minimum_bytes = 3 * elements * values.element_size()
    return (
        selected,
        pointwise_pipeline,
        {
            "elements": elements,
            "compiled_first_call_ms": compile_ms,
            "minimum_input_output_bytes": minimum_bytes,
            "operation_count_note": (
                "No portable FLOP count is assigned to SiLU or tanh; use the "
                "profiler report for measured work and traffic."
            ),
        },
    )


def build_compute_case(
    torch: Any, args: argparse.Namespace
) -> tuple[Callable[[], Any], Callable[[], Any], dict[str, Any]]:
    width = 1_024 if args.workload == "small" else 4_096
    input_scale = math.sqrt(width)
    left_fp32 = (
        torch.randn((width, width), device="cuda", dtype=torch.float32) / input_scale
    )
    right_fp32 = (
        torch.randn((width, width), device="cuda", dtype=torch.float32) / input_scale
    )
    dtype = torch.float32 if args.mode == "baseline" else torch.bfloat16
    left = left_fp32.to(dtype=dtype)
    right = right_fp32.to(dtype=dtype)

    def selected() -> Any:
        return left @ right

    def reference() -> Any:
        return left_fp32 @ right_fp32

    useful_operations = 2 * width**3
    minimum_bytes = (left.numel() + right.numel() + width**2) * left.element_size()
    return (
        selected,
        reference,
        {
            "width": width,
            "dtype": str(dtype).removeprefix("torch."),
            "input_scale_divisor": input_scale,
            "input_scaling_reason": (
                "bounded reference-friendly values preserve the declared BF16 "
                "elementwise rtol=1e-2, atol=1e-2 gate"
            ),
            "useful_operations": useful_operations,
            "minimum_input_output_bytes": minimum_bytes,
            "algorithmic_arithmetic_intensity_flop_per_byte": round(
                useful_operations / minimum_bytes, 4
            ),
        },
    )


def scalar_value(torch: Any, value: Any) -> float:
    if isinstance(value, (int, float)):
        return float(value)
    return float(value.detach().float().mean().item())


def main() -> None:
    # Read the experiment controls before allocating inputs.
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    builders = {
        "sync": build_sync_case,
        "launch": build_launch_case,
        "memory": build_memory_case,
        "compute": build_compute_case,
    }
    workload, reference, case_metadata = builders[args.case](torch, args)

    samples = cuda_times_ms(
        torch,
        workload,
        warmup=args.warmup,
        iterations=args.iterations,
    )
    timing = summarize_ms(samples)

    with torch.cuda.nvtx.range("profile_region"):
        with torch.cuda.nvtx.range(f"{args.case}_{args.mode}"):
            observed = workload()
    torch.cuda.synchronize()
    expected = reference()
    torch.cuda.synchronize()

    error_metrics: dict[str, float] = {}
    if isinstance(observed, (int, float)):
        absolute_error = abs(float(observed) - scalar_value(torch, expected))
        equivalent = absolute_error <= 1e-6 + abs(float(observed)) * 1e-5
        error_metrics["absolute_error"] = round(absolute_error, 8)
    elif args.case == "compute" and args.mode == "optimized":
        reference_norm = torch.linalg.vector_norm(expected.float()).clamp_min(1e-12)
        relative_l2_error = float(
            (
                torch.linalg.vector_norm(observed.float() - expected.float())
                / reference_norm
            ).item()
        )
        equivalent = bool(
            torch.allclose(observed.float(), expected.float(), rtol=1e-2, atol=1e-2)
        )
        error_metrics["relative_l2_error"] = round(relative_l2_error, 8)
    else:
        equivalent = bool(
            torch.allclose(observed.float(), expected.float(), rtol=1e-5, atol=1e-6)
        )
    finite = (
        math.isfinite(float(observed))
        if isinstance(observed, (int, float))
        else bool(torch.isfinite(observed).all().item())
    )
    if not equivalent or not finite:
        raise SystemExit("The selected path failed its numerical equivalence gate.")

    median_seconds = timing["median_ms"] / 1_000
    measurements: dict[str, Any] = {
        "case": args.case,
        "mode": args.mode,
        "timing": timing,
        "profile_nvtx_range": "profile_region",
        "checksum": round(scalar_value(torch, observed), 8),
        **case_metadata,
    }
    operations = case_metadata.get("useful_operations")
    minimum_bytes = case_metadata.get("minimum_input_output_bytes")
    if operations:
        measurements["effective_workload_tflops"] = round(
            operations / median_seconds / 1e12, 4
        )
    if minimum_bytes:
        measurements["effective_minimum_io_gb_per_s"] = round(
            minimum_bytes / median_seconds / 1e9, 4
        )

    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="14_profiler_bottlenecks",
        environment=environment,
        measurements=measurements,
        correctness={
            "numerically_equivalent": True,
            "finite_output": True,
            **error_metrics,
        },
    )
    print(f"Completed {args.case}/{args.mode} profiler case: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
Reading arithmetic intensity and achieved TFLOP per second on a roofline A log-scale conceptual roofline has arithmetic intensity on the horizontal axis and achieved FLOP per second on the vertical axis. A low-intensity pointwise kernel lies on the memory side; a reused matrix multiply lies on the compute side. A point below both ceilings requires investigation of other inefficiencies. ridge: bandwidth ceiling meets compute ceiling pointwise low AI · memory-side candidate BF16 GEMM high reuse · compute-side candidate below both ceilings: inspect stalls, waves, divergence, dependencies arithmetic intensity = useful FLOP ÷ measured bytes [FLOP/byte] achieved performance [FLOP/s] memory-bandwidth boundary peak performance boundary
Reading arithmetic intensity and achieved TFLOP per second on a roofline

A log-scale conceptual roofline has arithmetic intensity on the horizontal axis and achieved FLOP per second on the vertical axis. A low-intensity pointwise kernel lies on the memory side; a reused matrix multiply lies on the compute side. A point below both ceilings requires investigation of other inefficiencies.

# Normal execution
sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case sync --mode baseline

# Optional profiling
sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case sync --mode baseline --profiler all

Lab 15: Distinguish task imbalance from partial grid waves

A long final task can delay completion even when most work has finished, while a partial grid wave can leave SM capacity unused. This lab explores those effects separately with concurrent GEMMs and a Triton wave probe.

Complete source: labs/15_tail_load_balance.py
"""Compare balanced and skewed concurrent GPU task sets with approximately matched work."""

from __future__ import annotations

import argparse
import math
import statistics

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation

try:
    import triton
    import triton.language as tl
except ImportError:
    triton = None
    tl = None


if triton is not None and tl is not None:

    @triton.jit
    def uniform_tail_probe(output, work: tl.constexpr):
        program = tl.program_id(axis=0)
        value = program.to(tl.float32) * 0.0001
        for iteration in tl.range(0, work):
            value = value * 1.000001 + (iteration + 1) * 0.0000001
        tl.store(output + program, value)
else:
    uniform_tail_probe = None


def percentile(values: list[float], fraction: float) -> float:
    ordered = sorted(values)
    return ordered[
        max(0, min(len(ordered) - 1, math.ceil(fraction * len(ordered)) - 1))
    ]


def distribution_ms(values: list[float]) -> dict[str, float]:
    return {
        "min_ms": round(min(values), 4),
        "p50_ms": round(statistics.median(values), 4),
        "p90_ms": round(percentile(values, 0.9), 4),
        "p99_ms": round(percentile(values, 0.99), 4),
        "max_ms": round(max(values), 4),
    }


def wave_model(blocks: int, resident_slots: int) -> dict[str, float | int]:
    waves = (blocks + resident_slots - 1) // resident_slots
    tail_blocks = blocks - (waves - 1) * resident_slots
    return {
        "blocks": blocks,
        "waves": waves,
        "tail_blocks": tail_blocks,
        "tail_utilization": round(tail_blocks / resident_slots, 4),
    }


def tail_reference(torch: object, blocks: int, work: int) -> object:
    """Evaluate the Triton program's per-program result on the CPU in FP32."""
    values = torch.arange(blocks, dtype=torch.float32) * 0.0001
    for iteration in range(work):
        values = values * 1.000001 + (iteration + 1) * 0.0000001
    return values


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    if triton is None or uniform_tail_probe is None:
        raise SystemExit("This lab requires the environment's PyTorch Triton compiler.")
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    base = 256 if args.workload == "small" else 1_024
    balanced_widths = [base] * 8
    skewed_widths = [3 * base // 2] + [7 * base // 8] * 7

    def build_case(widths: list[int]) -> tuple[list[object], list[object]]:
        left = [
            torch.randn((width, width), device="cuda", dtype=torch.bfloat16)
            for width in widths
        ]
        right = [torch.randn_like(value) for value in left]
        return left, right

    def measure(widths: list[int]) -> dict[str, object]:
        left, right = build_case(widths)
        streams = [torch.cuda.Stream() for _ in widths]

        def run_once() -> tuple[float, list[float], list[object]]:
            start = torch.cuda.Event(enable_timing=True)
            finish = torch.cuda.Event(enable_timing=True)
            begins = [torch.cuda.Event(enable_timing=True) for _ in widths]
            ends = [torch.cuda.Event(enable_timing=True) for _ in widths]
            current = torch.cuda.current_stream()
            start.record(current)
            outputs = []
            for stream, begin, end, lhs, rhs in zip(
                streams, begins, ends, left, right, strict=True
            ):
                stream.wait_event(start)
                with torch.cuda.stream(stream):
                    begin.record(stream)
                    outputs.append(lhs @ rhs)
                    end.record(stream)
            for end in ends:
                current.wait_event(end)
            finish.record(current)
            finish.synchronize()
            return (
                float(start.elapsed_time(finish)),
                [
                    float(begin.elapsed_time(end))
                    for begin, end in zip(begins, ends, strict=True)
                ],
                outputs,
            )

        for _ in range(args.warmup):
            run_once()
        makespans: list[float] = []
        task_samples: list[float] = []
        outputs: list[object] = []
        for _ in range(args.iterations):
            makespan, tasks, outputs = run_once()
            makespans.append(makespan)
            task_samples.extend(tasks)
        finite = all(bool(torch.isfinite(output).all()) for output in outputs)
        if not finite:
            raise SystemExit(
                "A scheduled matrix multiplication produced non-finite output."
            )
        return {
            "widths": widths,
            "modeled_gemm_flops": 2 * sum(width**3 for width in widths),
            "makespan": summarize_ms(makespans),
            "task_duration": summarize_ms(task_samples),
            "makespan_distribution": distribution_ms(makespans),
            "task_duration_distribution": distribution_ms(task_samples),
            "median_task_to_max_task_ratio": round(
                statistics.median(task_samples) / max(task_samples), 4
            ),
        }

    balanced = measure(balanced_widths)
    skewed = measure(skewed_widths)
    work_ratio = skewed["modeled_gemm_flops"] / balanced["modeled_gemm_flops"]
    if abs(work_ratio - 1.0) > 0.02:
        raise SystemExit(
            "The balanced and skewed cases differ by more than two percent in "
            "modeled GEMM work; adjust the workload before interpreting timing."
        )
    properties = torch.cuda.get_device_properties(0)
    num_warps = 16
    threads = num_warps * 32
    tail_work = 256 if args.workload == "small" else 2_048
    compiled = uniform_tail_probe[(1,)](
        torch.empty(1, device="cuda"), work=tail_work, num_warps=num_warps
    )
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    registers = int(getattr(compiled, "n_regs", 0))
    metadata = getattr(compiled, "metadata", None)
    shared_bytes = int(getattr(metadata, "shared", 0)) if metadata else 0
    occupancy_limits = [properties.max_threads_per_multi_processor // threads]
    register_capacity = int(getattr(properties, "regs_per_multiprocessor", 0))
    if registers and register_capacity:
        occupancy_limits.append(register_capacity // (registers * threads))
    shared_capacity = int(getattr(properties, "shared_memory_per_multiprocessor", 0))
    if shared_bytes and shared_capacity:
        occupancy_limits.append(shared_capacity // shared_bytes)
    architectural_block_limit = int(
        getattr(properties, "max_blocks_per_multi_processor", 0)
    )
    if architectural_block_limit:
        occupancy_limits.append(architectural_block_limit)
    blocks_per_sm = min(limit for limit in occupancy_limits if limit > 0)
    resident_slots = properties.multi_processor_count * blocks_per_sm
    tail_output = torch.empty(2 * resident_slots + 1, device="cuda")
    partial_wave_cases = []
    all_partial_wave_programs_correct = True
    for blocks in (
        resident_slots,
        resident_slots + 1,
        2 * resident_slots,
        2 * resident_slots + 1,
    ):

        def launch(blocks: int = blocks) -> None:
            uniform_tail_probe[(blocks,)](
                tail_output, work=tail_work, num_warps=num_warps
            )

        for _ in range(args.warmup):
            launch()
        torch.cuda.synchronize()
        samples: list[float] = []
        measured_launch = annotated_operation(launch, "tail_measure")
        for _ in range(args.iterations):
            started = torch.cuda.Event(enable_timing=True)
            finished = torch.cuda.Event(enable_timing=True)
            started.record()
            measured_launch()
            finished.record()
            finished.synchronize()
            samples.append(float(started.elapsed_time(finished)))
        tail_output.fill_(float("nan"))
        launch()
        torch.cuda.synchronize()
        observed = tail_output[:blocks].cpu()
        expected = tail_reference(torch, blocks, tail_work)
        correct = bool(
            torch.isfinite(observed).all()
            and torch.allclose(observed, expected, rtol=1e-5, atol=1e-6)
        )
        all_partial_wave_programs_correct = (
            all_partial_wave_programs_correct and correct
        )
        if not correct:
            raise SystemExit(
                f"Partial-wave probe failed sentinel/reference validation: {blocks=}"
            )
        partial_wave_cases.append(
            {
                "model": wave_model(blocks, resident_slots),
                "completion_distribution": distribution_ms(samples),
                "max_absolute_error": float((observed - expected).abs().max()),
            }
        )

    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="15_tail_load_balance",
        environment=environment,
        measurements={
            "balanced": balanced,
            "skewed": skewed,
            "skewed_to_balanced_modeled_work_ratio": round(work_ratio, 4),
            "schedule": "eight independent CUDA streams with one task per stream",
            "partial_wave_probe": {
                "sm_count": properties.multi_processor_count,
                "warps_per_block": num_warps,
                "registers_per_thread": registers,
                "shared_bytes_per_block": shared_bytes,
                "derived_blocks_per_sm": blocks_per_sm,
                "resident_block_slots": resident_slots,
                "cases": partial_wave_cases,
            },
            "profiler_confirmation_required": True,
        },
        correctness={
            "matched_work_within_two_percent": abs(work_ratio - 1.0) <= 0.02,
            "all_outputs_finite": True,
            "all_partial_wave_programs_completed_and_match_reference": (
                all_partial_wave_programs_correct
            ),
        },
    )
    print(f"Wrote load-balance evidence: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/15_tail_load_balance.sbatch --workload small

# Optional profiling
sbatch slurm/15_tail_load_balance.sbatch --workload small --profiler all

Lab 16: Custom kernel decision making

Before maintaining custom GPU code, check whether a supported framework or library primitive already expresses the computation efficiently. This lab compares a composed matrix expression with a maintained PyTorch primitive.

Complete source: labs/16_library_first_decision.py
"""Compare an unfused composition with a maintained PyTorch library primitive."""

from __future__ import annotations

import argparse
from typing import Any

from common import (
    add_common_args,
    cuda_times_ms,
    load_torch,
    require_course_gpu,
    seed_everything,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def reference_checks(
    torch: Any, x: Any, weight: Any, bias: Any, outputs: dict[str, Any]
) -> tuple[dict[str, bool], dict[str, Any]]:
    """Check both BF16 paths against FP64 math with an intermediate-rounding budget."""
    product = x.double() @ weight.double()
    reference = torch.relu(product + bias.double())
    rtol, atol = 1e-2, 1e-2
    unit_roundoff = torch.finfo(torch.bfloat16).eps / 2
    # The composition rounds the matmul before bias addition. Propagate that
    # error through the final BF16 rounding; ReLU cannot amplify absolute error.
    rounding_allowance = unit_roundoff * (1 + unit_roundoff) * product.abs()
    budget = atol + rtol * reference.abs() + rounding_allowance
    if not bool(torch.isfinite(reference).all() and torch.isfinite(budget).all()):
        raise SystemExit("Non-finite FP64 reference or BF16 error budget")
    checks = {}
    errors = {}
    for name, output in outputs.items():
        if (
            output.shape != reference.shape
            or output.dtype != torch.bfloat16
            or not bool(torch.isfinite(output).all())
            or not bool((output >= 0).all())
        ):
            raise SystemExit(f"Invalid BF16 ReLU output: {name}")
        error = (output.double() - reference).abs()
        within_budget = bool((error <= budget).all())
        if not within_budget:
            raise SystemExit(f"FP64 reference error budget exceeded: {name}")
        checks[f"{name}_matches_reference"] = within_budget
        errors[name] = {
            "max_abs_error": float(error.max()),
            "max_error_budget_fraction": float((error / budget).max()),
        }
    return checks, {
        "reference_dtype": "float64",
        "rtol": rtol,
        "atol": atol,
        "bf16_unit_roundoff": unit_roundoff,
        "max_intermediate_rounding_allowance": float(rounding_allowance.max()),
        "errors": errors,
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    # Keep random inputs repeatable across comparable runs.
    seed_everything(torch, args.seed)
    size = 512 if args.workload == "small" else 4096
    # Create the synthetic tensors used by this experiment.
    x = torch.randn(size, size, device="cuda", dtype=torch.bfloat16)
    weight = torch.randn_like(x)
    bias = torch.randn(size, device="cuda", dtype=torch.bfloat16)

    def composed() -> object:
        return torch.relu(x @ weight + bias)

    def library_path() -> object:
        return torch.relu(torch.addmm(bias, x, weight))

    checks, numerics = reference_checks(
        torch,
        x,
        weight,
        bias,
        {"composed": composed(), "library_addmm": library_path()},
    )
    rows = {
        name: summarize_ms(
            cuda_times_ms(
                torch, operation, warmup=args.warmup, iterations=args.iterations
            )
        )
        for name, operation in (("composed", composed), ("library_addmm", library_path))
    }
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="16_library_first_decision",
        environment=environment,
        measurements={
            "shape": [size, size],
            "numerics": numerics,
            "timing": rows,
            "decision_order": [
                "framework configuration",
                "compiler",
                "maintained library",
                "custom kernel",
            ],
        },
        correctness=checks,
    )
    print(f"Wrote library-first evidence: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
Teaching diagram
Optimization keep or reject decision A candidate change passes four visible gates: correctness, end-to-end objective, memory budget, and repeatability. Any failed gate leads to reject and learn; only a branch that passes all four is kept. candidate correct? end-to-end objective? memory? repeatable? keep reject / learn preserve evidence yes yes yes yes no no no no A faster kernel is rejected when the declared workload, objective, or evidence contract does not pass.
Optimization keep or reject decision

A candidate change passes four visible gates: correctness, end-to-end objective, memory budget, and repeatability. Any failed gate leads to reject and learn; only a branch that passes all four is kept.

# Normal execution
sbatch slurm/16_library_first_decision.sbatch --workload small

# Optional profiling
sbatch slurm/16_library_first_decision.sbatch --workload small --profiler all

Lab 19: Overlap H2D copies with a bounded input ring

A nonblocking copy can free the CPU while the GPU still executes copies and kernels sequentially. This lab separates those two effects.

Complete source: labs/19_h2d_pipeline.py
"""Compare bounded serial and overlapped H2D input pipelines on one H100."""

from __future__ import annotations

import argparse
import math
import time
from typing import Any

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument("--mode", choices=("serial", "pipeline"), default="serial")
    parser.add_argument("--slots", type=int, default=2)
    parser.add_argument("--batches", type=int, default=16)
    parser.add_argument("--work", type=int, default=4, help="Dense GEMMs per batch")
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    if not 1 <= args.slots <= 8 or not 2 <= args.batches <= 256:
        parser.error("--slots must be 1..8 and --batches must be 2..256")
    if not 1 <= args.work <= 32:
        parser.error("--work must be 1..32")
    return args


def run_pipeline(torch: Any, args: argparse.Namespace) -> tuple[float, int]:
    width = 512 if args.workload == "small" else 2048
    compute = torch.cuda.Stream()
    copy = torch.cuda.Stream() if args.mode == "pipeline" else compute
    hosts = [torch.empty((width, width), pin_memory=True) for _ in range(args.slots)]
    inputs = [torch.empty((width, width), device="cuda") for _ in hosts]
    outputs = [torch.empty_like(item) for item in inputs]
    weight = torch.full((width, width), 1 / width, device="cuda")
    checks = torch.empty(args.batches, dtype=torch.bool, device="cuda")
    ready = [torch.cuda.Event() for _ in hosts]
    done = [torch.cuda.Event() for _ in hosts]
    used = [False] * args.slots
    # Wait for queued GPU work to finish at this measurement boundary.
    torch.cuda.synchronize()
    started = time.perf_counter()
    with torch.cuda.nvtx.range("h2d_loop"):
        for batch in range(args.batches):
            slot = batch % args.slots
            with torch.cuda.nvtx.range("slot_reuse_wait"):
                if used[slot]:
                    done[slot].synchronize()
            value = (batch + 1) / 4096
            with torch.cuda.nvtx.range("prepare_host"):
                hosts[slot].fill_(value)
            with torch.cuda.stream(copy), torch.cuda.nvtx.range("h2d_submit"):
                inputs[slot].copy_(hosts[slot], non_blocking=True)
                ready[slot].record(copy)
            with torch.cuda.stream(compute), torch.cuda.nvtx.range("consume_batch"):
                compute.wait_event(ready[slot])
                for _ in range(args.work):
                    torch.mm(inputs[slot], weight, out=outputs[slot])
                # Power-of-two width and inputs make this reference exact.
                checks[batch] = torch.all(outputs[slot] == value)
                done[slot].record(compute)
            used[slot] = True
        with torch.cuda.nvtx.range("pipeline_drain"):
            compute.synchronize()
            copy.synchronize()
    elapsed = (time.perf_counter() - started) * 1000
    if not bool(checks.all().item()) or not math.isfinite(elapsed) or elapsed <= 0:
        raise RuntimeError("H2D pipeline failed complete-batch reference or timing")
    return elapsed, args.slots * width * width * 4


def main() -> None:
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    torch.set_num_threads(1)
    torch.backends.cuda.matmul.allow_tf32 = False
    with torch.inference_mode():
        for _ in range(args.warmup):
            run_pipeline(torch, args)
        samples = [run_pipeline(torch, args) for _ in range(args.iterations)]
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="19_h2d_pipeline",
        environment=environment,
        measurements={
            "mode": args.mode,
            "slots": args.slots,
            "batches": args.batches,
            "gemms_per_batch": args.work,
            "pinned_pool_bytes": samples[0][1],
            "whole_loop": summarize_ms([item[0] for item in samples]),
            "whole_loop_samples_ms": [item[0] for item in samples],
            "timing_scope": "host fill, copy, GEMMs, device checks, slot waits and drain; allocation excluded",
            "overlap_evidence": "pending Nsight Systems timeline; host timing alone cannot prove overlap",
        },
        correctness={
            "every_batch_matches_exact_reference": True,
            "pipeline_drained": True,
        },
    )
    print(f"Completed H2D pipeline: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/19_h2d_pipeline.sbatch --mode serial --slots 2 --workload small

# Optional profiling
sbatch slurm/19_h2d_pipeline.sbatch --mode serial --slots 2 --workload small --profiler all

Lab 20: Drain a bounded D2H output pipeline

A GPU can finish producing an output while a copy or CPU consumer still owns its data. This lab builds the missing completion path.

Complete source: labs/20_d2h_pipeline.py
"""Progress from serial output to a bounded, event-safe D2H worker pipeline."""

from __future__ import annotations

import argparse
import math
import time
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, Callable

from common import (
    add_common_args,
    load_torch,
    require_course_gpu,
    summarize_ms,
    validate_common_args,
    write_result,
)
from course_evidence import annotated_operation


class OutputSlot:
    """Keep output ownership until transfer and CPU consumption both finish."""

    def __init__(self) -> None:
        self.future: Future[Any] | None = None

    def acquire(self) -> Any:
        if self.future is None:
            return None
        value = self.future.result()
        self.future = None
        return value

    def submit(self, future: Future[Any]) -> None:
        if self.future is not None:
            raise RuntimeError("Output slot still belongs to its consumer")
        self.future = future


def consume_after_copy(event: Any, consume: Callable[[], Any]) -> Any:
    event.synchronize()
    return consume()


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    add_common_args(parser)
    parser.add_argument(
        "--mode",
        choices=("serial", "workers", "pooled", "nonblocking", "pipeline"),
        default="serial",
    )
    parser.add_argument("--slots", type=int, default=2)
    parser.add_argument("--workers", type=int, default=2)
    parser.add_argument("--batches", type=int, default=16)
    parser.add_argument(
        "--sink-ms",
        type=float,
        default=2.0,
        help="Synthetic blocking sink delay per output",
    )
    # Read the experiment controls before allocating inputs.
    args = parser.parse_args()
    if (
        not 1 <= args.slots <= 8
        or not 1 <= args.workers <= 8
        or not 2 <= args.batches <= 256
    ):
        parser.error("--slots/--workers must be 1..8; --batches must be 2..256")
    if not math.isfinite(args.sink_ms) or not 0 <= args.sink_ms <= 100:
        parser.error("--sink-ms must be finite and 0..100")
    return args


def check_output(torch: Any, host: Any, batch: int, delay_ms: float) -> int:
    if not torch.equal(host, torch.full_like(host, (batch + 1) / 4096)):
        raise RuntimeError(f"Incomplete, stale or corrupted output for batch {batch}")
    # A controlled blocking sink, not a disk benchmark or CPU Python speedup.
    time.sleep(delay_ms / 1000)
    return batch


def run_pipeline(torch: Any, args: argparse.Namespace) -> tuple[float, int]:
    width = 512 if args.workload == "small" else 2048
    pooled = args.mode in ("pooled", "nonblocking", "pipeline")
    asynchronous = args.mode in ("nonblocking", "pipeline")
    compute = torch.cuda.Stream()
    egress = torch.cuda.Stream() if args.mode == "pipeline" else compute
    inputs = [torch.empty((width, width), device="cuda") for _ in range(args.slots)]
    outputs = [torch.empty_like(item) for item in inputs]
    hosts = (
        [torch.empty((width, width), pin_memory=True) for _ in inputs] if pooled else []
    )
    weight = torch.full((width, width), 1 / width, device="cuda")
    ready = [torch.cuda.Event() for _ in inputs]
    copied = [torch.cuda.Event() for _ in inputs]
    slots = [OutputSlot() for _ in inputs]
    completed: list[int] = []

    def release(slot: OutputSlot) -> None:
        batch = slot.acquire()
        if batch is not None:
            completed.append(batch)

    with ThreadPoolExecutor(max_workers=args.workers) as pool:
        # Start the executor before timing; bounded slots limit submitted work.
        pool.submit(lambda: None).result()
        # Wait for queued GPU work to finish at this measurement boundary.
        torch.cuda.synchronize()
        started = time.perf_counter()
        with torch.cuda.nvtx.range("d2h_loop"):
            for batch in range(args.batches):
                index = batch % args.slots
                with torch.cuda.nvtx.range("output_backpressure"):
                    release(slots[index])
                with (
                    torch.cuda.stream(compute),
                    torch.cuda.nvtx.range("produce_output"),
                ):
                    inputs[index].fill_((batch + 1) / 4096)
                    torch.mm(inputs[index], weight, out=outputs[index])
                    ready[index].record(compute)
                host = (
                    hosts[index]
                    if pooled
                    else torch.empty((width, width), pin_memory=True)
                )
                with torch.cuda.stream(egress), torch.cuda.nvtx.range("d2h_submit"):
                    egress.wait_event(ready[index])
                    host.copy_(outputs[index], non_blocking=asynchronous)
                    copied[index].record(egress)

                def consume(host: Any = host, batch: int = batch) -> int:
                    with torch.cuda.nvtx.range("host_consume"):
                        return check_output(torch, host, batch, args.sink_ms)

                if args.mode == "serial":
                    completed.append(consume_after_copy(copied[index], consume))
                else:
                    slots[index].submit(
                        pool.submit(consume_after_copy, copied[index], consume)
                    )
            with torch.cuda.nvtx.range("output_drain"):
                for slot in slots:
                    release(slot)
                compute.synchronize()
                egress.synchronize()
        elapsed = (time.perf_counter() - started) * 1000
    if sorted(completed) != list(range(args.batches)):
        raise RuntimeError("Output pipeline lost or duplicated batches")
    if not math.isfinite(elapsed) or elapsed <= 0:
        raise RuntimeError("Invalid output pipeline duration")
    return elapsed, args.slots * width * width * 4


def main() -> None:
    args = parse_args()
    validate_common_args(args)
    torch = load_torch()
    environment = require_course_gpu(torch)
    torch.set_num_threads(1)
    torch.backends.cuda.matmul.allow_tf32 = False
    with torch.inference_mode():
        for _ in range(args.warmup):
            run_pipeline(torch, args)
        samples = [run_pipeline(torch, args) for _ in range(args.iterations)]
    # Save the actual measurements together with their correctness checks.
    target = write_result(
        args,
        lab_id="20_d2h_pipeline",
        environment=environment,
        measurements={
            "mode": args.mode,
            "slots": args.slots,
            "workers": args.workers,
            "batches": args.batches,
            "synthetic_sink_ms": args.sink_ms,
            "in_flight_destination_capacity_bytes": samples[0][1],
            "whole_loop": summarize_ms([item[0] for item in samples]),
            "whole_loop_samples_ms": [item[0] for item in samples],
            "timing_scope": "GPU produce, D2H, exact CPU checks, synthetic sink, waits and final drain; initial pools excluded",
            "overlap_evidence": "pending timeline; threads model blocking sinks, not GIL-bound Python acceleration",
        },
        correctness={
            "every_output_matches_exact_reference": True,
            "all_outputs_consumed_once": True,
        },
    )
    print(f"Completed D2H output pipeline: {target}")


if __name__ == "__main__":
    annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/20_d2h_pipeline.sbatch --mode serial --slots 2 --workers 2 --sink-ms 2 --workload small

# Optional profiling
sbatch slurm/20_d2h_pipeline.sbatch --mode serial --slots 2 --workers 2 --sink-ms 2 --workload small --profiler all

Course guides

Getting started

Read the course · Estimated guided time: 44 hours.

Learn to find a bottleneck, change one factor and decide whether the result justifies keeping the change. Take GPU Fundamentals first; use GPU Performance Tools for profiler concepts and PyTorch for GPU Performance Engineering for a tensor-reading refresher.

Learning route

Read measurement (Lessons 1–3), local optimization (4–10), communication and scaling (11–12), library-first decisions (13), then fabric concepts (14–16). Follow each lesson's lab links rather than numerical lab order.

  • After Lesson 3, state a bottleneck hypothesis and a disconfirming observation.
  • After Lesson 10, distinguish workload idle time from scheduler delay.
  • Use Lab 19 for a complete input-transfer pipeline and Lab 20 for output transfer and consumption; verify every output and include the final drain.
  • Complete the local capstone before extending the investigation to a fabric.

Before the first lab

Use one full, non-MIG H100 per local lab; a qualified advanced cluster can supply one-GPU allocations. Follow the Lab Guide to synchronize sources and prepare the available lab software. Check the setup summary for failures or hardware skips, then review Versions and environment and the readiness checks, then run:

sbatch slurm/01_timing_basics.sbatch --workload small

Distributed transport, scaling and profiling practice belongs to Advanced Labs, which qualifies the two-worker, sixteen-H100 fabric before those experiments.

Completion

Complete the profiler-backed capstone with a baseline, one controlled change, correctness checks, independent repeated measurements and a scoped keep/reject decision. Diagnostic captures explain behavior; use unprofiled runs for timing.

Use Where to Go Next for optional reading after the core route.

Reference guides

Versions and environment

Completed prepared-environment runs

All 14 practical labs completed both small and large profiles (28 verified exports) on the prepared NVIDIA H200 cluster. See lab results and the catalog validation record for evidence scope and limitations.

The recorded framework is PyTorch 2.14.0+cu130 with CUDA runtime 13.0.

The observed profiler CLI/viewer pairs were Nsight Systems 2026.4.1 and Nsight Compute 2026.2.1; the scheduler reported Slurm 25.11.3. These runs qualify the recorded experiments in their prepared environments. They do not establish a clean installation, every optional extension, or performance on H100.

H100 target and installation candidates

The following targets and pending checks describe the H100 teaching environment. Keep them separate from the completed H200 evidence above.

ComponentCourse targetEvidence status
Python3.12Installed locally; cluster parity pending
PyTorch2.14.0 manifest authorityClean Linux/H100 install and qualification pending; no fallback approved
Nsight Systems and ComputeSite-compatible current toolsLive profiler activation pending
GPUOne full non-MIG H100; distributed labs use the separate advanced courseLive validation pending

Exact profiler and framework versions belong in every benchmark record because trace schemas, kernel dispatch, and compiler behavior can change.

Networking workshop qualification

NCCL Tests v2.20.0, source commit b4d5beebca8a76cf01335f724d154b9b9d394d96, is the reviewed external benchmark candidate. Its MPI-enabled build, exact per-node binary hashes and loaded CUDA/NCCL/MPI libraries still require Linux/H100 qualification. The course does not install it or change the PyTorch environment. Current official NCCL documentation describes 2.31.2; this is a research context, not a runtime pin. Record torch.cuda.nccl.version() separately from the external benchmark's nccl_headers and nccl_library records.

Advanced Lab 10 accepts the v2.20.0 float/sum standard table with eight ranks on one eight-H100 node or sixteen ranks across two eight-H100 nodes. The site supplies a qualified MPI/Slurm integration. Optional per-iteration and tuning-report columns are separate diagnostics, not accepted by the stable parser. RoCE/GDR/QP trials require a qualified fabric and registration path; they are not implicit core platform features.

Transfer-pipeline qualification

Labs 19 and 20 use the existing PyTorch candidate environment. Their source contracts follow the documented transfer and profiling APIs, but CUDA stream ordering, buffer lifetimes and overlap still require H100 qualification. CPU control tests check loop logic; they do not establish concurrent device execution.

Shared profiling qualification

Use the Lab Guide for the preparation and cluster-managed profiling route. Keep the matching CLI/viewer identities recorded with each run. Installation does not qualify the driver, either worker, the selected native runtime or optional container, or hardware-counter access; those claims require the relevant canaries and report inspections. Keep the existing AI runtime identities above; changing a profiler does not authorize changing those environments or adding collectors and metrics databases.

Prepared H200 runtime and applicable live profiler captures are recorded above. This campaign did not rerun the complete infrastructure installer or qualify the H100 target.

Advanced fabric qualification

The documented base target uses two one-H100 workers; all distributed GPU experiments now belong to the separate two-eight-H100 route. Eight-/sixteen-rank launchers require full devices with MIG disabled, NVLink peer paths and active InfiniBand. Physical topology checks do not replace Fabric Manager health, MPI/NCCL compatibility or GPUDirect registration qualification. No live 16-H100 qualification is claimed by these source changes.

The advanced course owns these fabric experiments and their selected native tool dependencies. Use the Lab Guide for preparation, retain the component build receipts, and qualify the same runtime on both nodes before accepting a comparison.

Readiness checks

Hardware scope: local GPU checks use one full, non-MIG H100. A qualified advanced cluster can supply one-GPU allocations. Distributed work follows the advanced course's separate fabric qualification.

This is a target-qualification checklist, not the lesson execution order. Follow the course for the learning route and complete each exercise's relevant safety/setup gate before running it. Distributed and optional checks qualify those paths; they are not prerequisites for earlier single-GPU lessons that do not use them.

Run from the gpu-optimizations course root. Keep JSON results, Slurm output, profiler reports, and environment metadata private. Share only a sanitized summary that follows evidence-security.md. A profiler run explains behavior; its instrumented duration is not acceptance timing.

Complete shared preparation in the Lab Guide and review its completion summary. Follow the Lab Guide’s guidance for any failures or hardware skips before submitting. Preparation creates private result/log directories and records installed runtime identities; launchers restore that runtime. Retain its receipts with the qualification evidence. Directory permissions do not replace the cluster's storage and access-control policy.

Compute-node tooling

sbatch slurm/tooling_preflight.sbatch

Record PyTorch, CUDA, driver, Nsight, and DCGM versions or explicit absence. Serving-client qualification belongs to the LLM Inference environment. Do not record hostnames, executable paths, GPU UUIDs, or other asset identifiers in the shareable summary. Stop only the dependent profiler exercise when a command or permission is unavailable; do not replace missing evidence with a guess.

Measurement discipline

sbatch slurm/01_timing_basics.sbatch --workload small
sbatch slurm/02_sync_trap.sbatch --workload small

Stop if the learner cannot explain the timed boundary or locate each synchronization.

Practical profiler workshop

First preserve unprofiled baseline and candidate distributions:

sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case sync --mode baseline
sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case sync --mode optimized
sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case memory --mode baseline
sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case memory --mode optimized
sbatch slurm/14_profiler_bottlenecks.sbatch --workload small --case compute --mode optimized

Use Nsight Systems to compare synchronization and launch mechanisms:

sbatch slurm/14_profiler_bottlenecks.sbatch --profiler nsys --workload small --case sync --mode baseline
sbatch slurm/14_profiler_bottlenecks.sbatch --profiler nsys --workload small --case sync --mode optimized
sbatch slurm/14_profiler_bottlenecks.sbatch --profiler nsys --workload small --case launch --mode baseline
sbatch slurm/14_profiler_bottlenecks.sbatch --profiler nsys --workload small --case launch --mode optimized

Use Nsight Compute only after selecting the material range and kernel:

NCU_SET=roofline NCU_SECTIONS=MemoryWorkloadAnalysis,SchedulerStats,WarpStateStats,Occupancy sbatch slurm/14_profiler_bottlenecks.sbatch --profiler ncu --workload small --case memory --mode baseline
NCU_SET=roofline NCU_SECTIONS=MemoryWorkloadAnalysis,SchedulerStats,WarpStateStats,Occupancy sbatch slurm/14_profiler_bottlenecks.sbatch --profiler ncu --workload small --case memory --mode optimized
NCU_SET=roofline NCU_SECTIONS=MemoryWorkloadAnalysis,SchedulerStats,WarpStateStats,Occupancy sbatch slurm/14_profiler_bottlenecks.sbatch --profiler ncu --workload small --case compute --mode optimized

Confirm every requested set and section name in the preflight output before submitting the Nsight Compute jobs; names and composition are tool-version dependent. The Nsight Systems evidence must identify timeline gaps, blocking APIs, kernel spacing, copies, or overlap. The Nsight Compute evidence must name the selected kernel and distinguish defensible algorithmic estimates from report-derived arithmetic intensity, achieved throughput, traffic, scheduler, stall, and occupancy evidence. The pointwise case has no portable algorithmic FLOP count. If profiler access is unavailable, record the exact blocker and do not claim those findings.

Optimization mechanisms

sbatch slurm/10_shape_precision.sbatch --workload small
sbatch slurm/03_compile_fusion.sbatch --workload small
sbatch slurm/04_cuda_graphs.sbatch --workload small
sbatch slurm/05_input_pipeline.sbatch --workload small
sbatch slurm/12_allocator_lifetime.sbatch --workload small

Keep a change only if its correctness check and the predeclared end-to-end metric pass. For Lab 05, retain the batch-ready gap, H2D event time, device-consumption event time, and end-to-end wall time for every variant. These single-stream component measurements are serialized evidence, not a claim of overlap; use a profiler to prove overlap. Activation checkpointing is now Training Lab 14, where matched-state loss and all trainable parameter gradients must pass before memory or timing is interpreted. Attention/SDPA practice is now Inference Lab 24; these specialized exercises remain in the learning path with their own course environments.

Qualify complete transfer paths separately from Lab 05's serialized components:

sbatch slurm/19_h2d_pipeline.sbatch --mode serial --slots 2
sbatch slurm/19_h2d_pipeline.sbatch --mode pipeline --slots 2
sbatch slurm/20_d2h_pipeline.sbatch --mode serial --slots 2
sbatch slurm/20_d2h_pipeline.sbatch --mode pipeline --slots 2

Follow the complete Lab 20 guide for the intervening workers, pooled and nonblocking modes; the endpoints alone do not isolate their causes. Require every batch to match, every output to be consumed once and the final drain to complete. Keep workload, slot count and sink delay fixed between comparisons. Use separate short Nsight runs to establish copy/compute overlap; CPU controls or a lower wall time alone do not prove concurrency. Record bounded pool capacity separately from measured host memory. The synthetic sink is not a storage-throughput experiment.

Scale and capstone

sbatch slurm/09_capstone.sbatch --workload small

Run the capstone on one GPU. Retain correctness, equivalent work and repeated unprofiled timings before accepting a change.

Tails and library-first escalation

sbatch slurm/15_tail_load_balance.sbatch --workload small
sbatch slurm/16_library_first_decision.sbatch --workload small

Distinguish warp divergence, variable block work, rank skew, and a partial final wave. A proposed custom kernel must address a measured residual hotspot after framework, compiler, and library options have been evaluated. Repeat accepted candidates across independent trials and keep unavailable profiler or H100 evidence pending.

Distributed practice

Use Advanced Labs for placement, transport, collective and application checks on its qualified two-worker, sixteen-H100 fabric. Follow its lab-specific acceptance criteria; two one-GPU TCP workers do not establish fabric performance. These checks are not gates for the local experiments above.

Lab mechanisms and evidence

A causal comparison worksheet for every optimization

Objective: turn a plausible performance explanation into a controlled decision. Use this procedure with the library-first lab and tail/load-balance lab, then apply it to the optimization capstone. The method also prepares you for the specialized courses without duplicating their labs.

Start with one testable mechanism

Write three statements before running anything: what stays fixed, what changes, and what observation would contradict the proposed explanation. For launch overhead, hold tensor shape, dtype, result, and iteration count fixed while changing submission or fusion. For a memory-layout experiment, preserve logical values and include layout conversion cost when the application must pay it. For load imbalance, preserve total useful work and change its distribution. In every case, decide whether the primary boundary is a kernel, a repeated operation, or an application step.

HypothesisSupporting evidenceControl or counterexample to examine
Launch-bound pointwise chainGaps between short kernels; fewer launches after fusionLarger tensors remove most of the gain
Memory traffic limits the regionFewer intermediate writes and lower measured trafficMore arithmetic without less traffic does not help
Final wave wastes capacityFew blocks remain while most SMs are idleComparable work with a better-balanced grid removes the tail
Register pressure limits latency hidingResource/stall evidence changes with launch choiceHigher occupancy with spills is slower

Do not derive a hardware diagnosis from one aggregate number. Occupancy says how much work can be resident, not whether it is eligible to issue. Bandwidth depends on the memory level and traffic definition. Utilization may be modeled or measured, and a high value can coexist with a poor end-to-end design.

Worked decision

Given a 10-millisecond application step containing a 2-millisecond candidate region, halving only that region saves at most one millisecond: the new step is nine milliseconds, or about 1.11 times the original throughput. If the optimization requires a 1.5-millisecond conversion each step, the total becomes 10.5 milliseconds and should be rejected under the original boundary. These are arithmetic predictions, not H100 measurements. They show why the region and application must both be measured.

  1. Run the relevant smoke lab and validate the output before retaining timings.
  2. Use warm-up plus repeated CUDA-event samples for the microbenchmark; retain minimum, median and tail statistics rather than one favorable number.
  3. Inspect a short profiler region to test the mechanism. Keep profiling and primary timing runs separate because instrumentation changes execution.
  4. Change only one factor. Repeat the comparison in counterbalanced order, holding work, correctness tolerances, environment, and data preparation fixed.
  5. Record a keep, reject, or investigate decision in the benchmark worksheet. Include a slower candidate if it disproved the original hypothesis; that is a useful engineering result.
Library-first escalation and scope

Check framework operators, compilation, tensor layout, and supported library paths before proposing a custom kernel. A kernel is justified by a missing operation or demonstrated limitation, not by a desire to increase a benchmark number. The proof burden includes reference correctness, sanitizers, kernel timing, total application impact, and maintenance across shapes and versions.

The Fundamentals lane model predicts inactive-lane opportunities; its GPU tail probe measures a different scheduling effect. Training FLOP estimates count the backward GEMMs actually requested. Inference scheduling models explain policy but cannot supply real TTFT. CUDA logical arithmetic intensity excludes hidden traffic. The general lesson is the same: name the numerator, denominator, assumptions and excluded costs before interpreting any ratio.

Review answer: a locally faster kernel is a candidate, not an accepted change. Accept it only when equivalent work is correct and the chosen end-to-end boundary improves under the stated constraints. If a result conflicts with the model, refine the model using evidence instead of discarding the measurement.

Read profiler results at their captured scope

Systems timelines establish overlap; one Compute kernel cannot. Compute captures for Labs 07, 19 and 20 select a warmup matrix operation with default arguments. Lab 15 selects only the first measured grid. Use the owning source's range and kernel filters to identify the captured work before interpreting counters.

Lab 14's compute comparison deliberately changes FP32 to BF16 while keeping width, scaling and useful operations fixed. Lab 16 compares both BF16 paths against an independent FP64 reference with its declared rounding budget. Keep these correctness contracts with any performance decision.

For Labs 09, 16 and 19, the run-labs campaign uses three independent jobs per variant and workload, reversing order in the middle repetition. Lab 09's rounds inside one process are additional observations, not independent trials.

Benchmark worksheet

Record the immutable workload, correctness criterion, independent variable, software and H100 environment, timer boundary, warm-up, raw sample summary, memory, profiler evidence, observation, inference, and keep/reject decision.

Microbenchmarks must use CUDA events and an end-to-end wall-time check. Distributed trials must include per-rank work, topology, message volume, and exposed communication. Never publish one best sample as the result.

Comparison worksheet

Copy this worksheet into the private experiment record before changing one factor. Fill both columns for equivalent work; mark unavailable evidence explicitly. Retain raw artifacts privately and publish only separately reviewed aggregates following evidence-security.md.

FieldBaselineCandidate / observation
Date and random course run ID (keep artifact location private)To recordTo record
Lab, source/commit identity, exact arguments, single changeTo recordTo record
H100 SKU, node/rank count, MIG state, topology class (no asset IDs)To recordTo record
Approved environment lock or immutable image; driver/CUDA/framework/NCCL/Slurm versionsTo recordTo record
Input shapes, layouts, dtype, seeds, batch/workload semanticsTo recordTo record
Primary metric, timer, included operations, completion condition, correctness/quality tolerancesTo recordTo record
Warm-up, measured iterations, three independent trial IDs and orderTo recordTo record
Correctness result and maximum error; missing/non-finite dataTo recordTo record
Raw timing distribution, minimum, median, p90/p95 and dispersionTo recordTo record
Baseline allocated memory, peak allocated/reserved memory, incremental peakTo recordTo record
Sanitized profiler observation, selected range/kernel, tool versionTo recordTo record
Supporting observation and disconfirming controlTo recordTo record
Decision: keep, reject, or investigate; limitation and next experimentTo recordTo record
Suspected limiter and measured critical-path fractionTo recordTo record
Exposed collective time, fixed total work, scaling efficiencyTo recordTo record
Copy-ready gaps, allocation lifetime, compile/capture/replay costsTo recordTo record
Labs 19/20 stream mode, slots, batches, work/sink, whole-loop distribution and final-drain correctness; separate timeline overlap and pool capacityTo recordTo record

A faster result is accepted only when its declared correctness, workload, timed operations, and environment constraints all hold. Record rejected hypotheses and slower candidates; they are useful evidence for the next choice.

Networking comparison addendum

Before a tuning run, record the effective site configuration privately, then freeze one profile difference. Record IP interface and RDMA HCA selection separately; do not publish their identifying names or raw logs.

Networking evidenceBaselineCandidate
Platform capability versus selected transport versus qualified GDR pathTo recordTo record
Benchmark source, per-node binary hashes, MPI mode, NCCL headers and loaded libraryTo recordTo record
Message bytes, float/sum, buffer mode, rank count, validation enabledTo recordTo record
Time unit, algbw, normalized busbw, both incorrect-element countsTo recordTo record
Three independent per-size values, median and range across runsTo recordTo record
Diagnostic versus timing run, exit status and complete size curveTo recordTo record
Single job-local override and unchanged QP splitting/interface policyTo recordTo record
Follow-up application time and exposed collective timeTo recordTo record

A parsed log proves only the validated content. A benchmark run does not prove fabric administration, remote binary parity or application benefit. Keep negative or inconclusive results and missing evidence visible.

Evidence and privacy

The course source is designed to be public, but runtime evidence is sensitive by default. Slurm output, PyTorch traces, Nsight reports, DCGM discovery, and serving benchmarks can contain infrastructure identifiers, filesystem paths, command lines, workload shapes, model names, or request content even when the course labs themselves use synthetic data.

Collect privately

  1. Use synthetic or explicitly public inputs. Do not profile customer prompts, proprietary model inputs, credentials, or regulated data.
  2. Complete software preparation in the Lab Guide and review its completion summary. Follow the Lab Guide’s guidance for any failures or hardware skips before submitting. Its private parent directories protect scheduler logs even when Slurm opens them before the job body starts.
  3. Keep results/, original profiler reports, traces, and Slurm output in storage that only the learner or approved course reviewers can read.
  4. Do not pass credentials on command lines or enable shell tracing. Remove unrelated secret-bearing environment variables before profiling, following the cluster owner's approved procedure.
  5. Never commit generated evidence. The course .gitignore reduces accidental staging; it is not an access-control or redaction boundary.

Shared viewer copies

A successful profiling stage automatically delivers a verified copy of its native reports to the installed Nsight viewer directory. These copies are readable by the existing shared viewer audience; the viewer does not provide per-user report isolation. Submit only workloads whose report contents are approved for that audience. Private originals, logs and other results remain in the job directory. Check viewer_delivery and use the exact viewer paths printed by the job; no manual copy or permission change is needed after sbatch.

Share summaries, not raw artifacts

Before material leaves the approved environment, create a separate summary that excludes:

  • hostnames, node lists, job IDs, GPU UUIDs, serial numbers, and account or project identifiers;
  • usernames, home directories, executable paths, internal endpoints, and private repository paths;
  • environment-variable values, tokens, cookies, request headers, and command lines containing credentials;
  • customer data, prompts, model names that are not public, raw traces, and raw logs.

Report only the evidence needed for the learning decision: anonymized run ID, node count, GPU family, software versions, public workload definition, correctness result, aggregate timing, and a written interpretation of relevant profiler evidence. A reviewer should inspect the sanitized copy before it is shared. Redact by producing a new file; do not overwrite the private original.

Course-specific safeguards

  • Lab JSON uses the canonical gpu-course-result/v1 schema and a random run ID instead of a Slurm job ID.
  • New result files are created exclusively with owner-only permissions.
  • Profiler launchers create owner-only, randomly named result directories.
  • The tooling preflight suppresses hostnames, executable paths, GPU UUIDs, and DCGM discovery output.
  • The normal course validator performs static validation and does not execute Python labs or Slurm launchers.
  • The portable tree rejects Python bytecode and Ruff cache directories, and every launcher disables Python bytecode creation before Python starts.
  • requirements.txt is a direct compatibility constraint. The prepared runtime records the installed package and component identities; retain those receipts with qualification evidence. Optional containers also have immutable image identities.

Live site policy remains authoritative. If a profiler or telemetry command is not approved, record a sanitized blocker and ask the cluster owner rather than weakening permissions.

Diagnostic tooling reference

The Lab Guide owns software preparation and the private Grafana handoff. Its separate “Browsing Grafana and Nsight Profilers” section explains how to qualify Systems and Compute captures on allocated GPUs. Use the same qualified versions throughout the courses. Soperator supplies the existing DCGM collectors, VMAgent, and local VictoriaMetrics database; do not deploy another collector or database for these exercises.

PyTorch Profiler remains useful for operator dispatch in the advanced labs. Use the explicit external-only branch when collecting a separate Nsight trace, so two CUDA profilers do not compete for the same process. Profiling, sanitizers, and telemetry answer different questions; confirm an optimization with repeated unprofiled runs and the lab's correctness contract.

What each tool can prove

ToolAppropriate evidenceWhat it cannot prove alone
nvidia-smiDevice visibility, allocation, memory use, clocks, power, temperature, coarse activityKernel efficiency or a source-level bottleneck
DCGMHealth and interval activity across GPUs, nodes, ranks, and timeWhich operator, kernel, or instruction caused the interval
DCGM ExporterA protected, time-series view of selected DCGM fields for dashboards and alertsA kernel root cause, even when an interval correlates with a slowdown
PyTorch ProfilerOperator CPU/CUDA time, call count, shapes, copies, allocations, and framework-to-kernel mappingWhole-system scheduling outside its collection scope
NVTXSemantic phase labels such as forward, backward, prefill, or profile_regionAny performance metric by itself
Nsight SystemsCPU gaps, CUDA APIs, kernels, copies, synchronization, NCCL, rank imbalance, and overlapArithmetic intensity or detailed kernel pipeline limits
Nsight ComputeOne selected kernel's roofline position, throughput, memory traffic, scheduler, stalls, and occupancyEnd-to-end latency or throughput by itself
nvbandwidthBandwidth or latency for a declared host/device or device/device copy path, size, direction, and concurrencyNCCL collective performance or application throughput
NCCL TestsCorrectness and algorithm/bus-bandwidth curves for a named collective and message-size sweepFramework scheduling, overlap, useful model progress, or an application speedup
vLLM BenchStartup, latency, throughput, or online-serving behavior for one versioned vLLM engine workloadA cross-engine standard or a kernel-level explanation
AIPerfRequest distribution, TTFT, ITL, end-to-end latency, request rate, and token throughputKernel root cause without server and profiler evidence
MLPerfA comparable full-system result only when the official rules, scenario, dataset, quality target, audit, and checker are followedThat an informal course experiment is an MLPerf result

For NCCL Tests, select the operation from the training or serving design rather than running only all-reduce by habit. DDP commonly motivates an all-reduce; FSDP-style sharding uses all-gather and reduce-scatter; tensor-parallel layouts may use all-reduce, all-gather, or reduce-scatter; expert routing motivates all-to-all. Sweep realistic message sizes and report both algorithm bandwidth and bus bandwidth with the exact operation, rank count, topology, and build. Then profile the real PyTorch workload, because a good synthetic curve does not prove that the framework overlaps the same collective with useful compute.

Use nvbandwidth before NCCL Tests when the question is the underlying copy path itself. Use NCCL Tests when the question is a collective. Use the PyTorch or serving workload when the question is application behavior. Use an engine-native client such as vllm bench for a focused vLLM study, an endpoint load client for service-level latency and throughput, and MLPerf only when the formal benchmark contract is actually being reproduced.

Permissions and profiler coordination

Inside an allocated worker, nsys status -e reports capture prerequisites and ncu --list-sets lists the installed collection sets. These are diagnostic checks. Software preparation does not run captures; execute the Lab Guide's profiling canaries and inspect their reports to establish capture readiness for the selected runtime.

An ERR_NVGPUCTRPERM-style error is a recorded permission blocker. Escalate it to the cluster owner; do not weaken host security. DCGM profiling fields and developer profilers can compete for the same counters. DCGM pause and resume are host-engine-wide operations, so only the site owner should coordinate them. Profile one short, representative workload and preserve an unprofiled timing run because profiling overhead invalidates acceptance timing.

Evidence privacy

Profiler reports, exporter series, benchmark reports, and telemetry can contain host paths, command lines, device identifiers, model metadata, or request content. Treat every raw artifact as private even when the lab uses synthetic data. Follow evidence-security.md before sharing any result.

Apply the networking tools in lesson order

The advanced communication course owns the bounded networking experiments: Lab 01 checks topology, Lab 09 measures the NCCL message-size curve and Lab 10 runs NCCL Tests. First map topology and selected transport, then read the message-size curve, then change one job-local setting in a new process. Advanced Labs 12 and 13 own the follow-up application scaling and overlap checks. NCCL Tests uses its own MPI-enabled binary and launcher; the PyTorch labs use torchrun. The two runtimes must record their loaded NCCL versions independently. Optional upstream tuning reports and per-iteration columns are diagnostic extensions, not the standard table accepted by the course parser.

Where to Go Next

These optional reading directions combine recent developments with established advanced concepts; they do not add required labs or change the pinned H100 environment. Select a topic that matches an observed bottleneck, not merely a new product name. Read its current support requirements before trying it separately; documentation availability is not course qualification.

Choose one direction and apply the course’s reasoning to a new example. Keep its stated scope and qualification limits in your comparison.

  • Regional and ahead-of-time compilation

    Regional compilation compiles selected reusable parts of a model instead of treating the whole model as one compilation unit. Ahead-of-time compilation moves compilation work before deployment. Together, these approaches extend the course's warm-up discussion into the trade-off between startup cost, reusable compiled regions and steady-state execution. Investigate: How many executions are needed to repay compilation cost, and do new shapes invalidate that calculation? Scope: Evolving PyTorch compiler tooling, not Blackwell-only. Export and backend constraints vary by release; the reading does not upgrade PyTorch or add a deployment lab. Study regional ahead-of-time compilation.

  • CUPTI range profiling and performance-monitor sampling

    CUPTI is NVIDIA's instrumentation interface beneath many profiling tools. Range profiling collects counters for a selected region of work; performance-monitor sampling observes counters at intervals over time. These answer different questions from a single kernel-duration measurement and help explain why profiler replay and observation overhead matter. Investigate: When would a time series reveal behavior hidden by one aggregate measurement, and how would you measure the observer's overhead? Scope: Evolving profiling APIs; NVIDIA recommends Range Profiling instead of the older Profiling API deprecated in CUDA 13.0. Check device, tool and counter-access requirements; do not change administrator permissions. Explore the current CUPTI interfaces.

  • GPUDirect Storage and the end-to-end input path

    GPUDirect Storage can transfer data between storage and GPU memory without an intermediate CPU-memory copy on supported paths. It extends input-pipeline analysis beyond workers and pinned buffers to storage, filesystems and topology. It does not remove application preprocessing or guarantee that every transfer takes a direct path. Investigate: Is the bottleneck storage bandwidth, preprocessing, transfer or GPU work, and does the selected path actually avoid CPU staging? Scope: Established advanced technology with evolving support. H100 is not sufficient by itself: filesystem, driver and topology requirements must be qualified. Cluster storage changes are outside this course. Read the GPUDirect Storage design guide.

  • Device-initiated communication and NCCL GIN

    NCCL's device API lets CUDA kernels initiate communication instead of relying only on host-issued collectives. GPU-Initiated Networking (GIN) extends this idea to supported network paths. This changes where communication is scheduled and how its progress can overlap computation; it is not simply another host-side collective setting. Investigate: Which synchronization and buffer-lifetime responsibilities move into the kernel, and when would that improve end-to-end overlap? Scope: Recent communication interface; device API support begins with NCCL 2.28, while GIN requires an appropriate later version and supported transport. Conceptual reading only here: the Python labs and two-node baseline do not assume the required connectivity or implement device-side primitives. Study NCCL device-initiated communication.

  • Energy per useful result

    Energy efficiency measures the energy required to finish useful, correct work, not just instantaneous power or GPU utilization. NVIDIA Management Library (NVML) exposes device telemetry, including energy counters on supported devices. Connecting those measurements to completed work broadens optimization from elapsed time alone to time, energy and quality constraints. Investigate: Can a lower-power configuration consume more energy because it runs longer, and what is excluded from a GPU-only measurement? Scope: Established advanced measurement concept, not a new hardware feature. Check counter support and sampling boundaries; GPU telemetry does not include the entire host or data center. Keep exploration read-only. Consult the NVML device-query reference.

Glossary

Algorithmic bandwidth
Logical collective payload divided by operation time, using a declared unit convention.
Aliasing
Two pointers or tensor views referring to overlapping storage; it changes safe read/write ordering.
Amdahl bound
The maximum end-to-end gain possible when only one fraction of the critical path is accelerated.
Arithmetic intensity (AI)
Work divided by data movement for the same boundary, expressed in FLOP/byte. An algorithmic estimate and a profiler's measured traffic are different quantities and must be labeled.
Backpressure
A producer wait imposed when bounded slots are still owned by transfers or consumers.
Baseline
The frozen, correct workload and environment against which one controlled change is compared.
Benchmark configuration
The workload, correctness tolerance, timed operations and success metric held fixed during a comparison.
BF16
Bfloat16, a 16-bit floating-point format with FP32-like exponent range and fewer significand bits.
Collation
Combining individual examples into the batch structure consumed by the model.
Compiler guard
A runtime check of assumptions used by compiled code, such as tensor shape or dtype; a failed guard can cause recompilation.
Copy engine
Dedicated transfer hardware that moves bytes without executing the copy as a kernel on streaming multiprocessors.
CPU timer
A host-side clock used to measure elapsed time; GPU completion must be established before stopping it when timing a complete GPU request.
CPU/GPU pipeline
Dependent host preparation, transfer, device computation and output stages; optimizing only a kernel may leave the end-to-end bottleneck unchanged.
Critical path
The dependency chain that determines completion time.
CUDA event
A stream-ordered marker used to track completion or enforce dependencies; timing-enabled events can measure elapsed intervals.
CUDA Graph
A reusable graph of operations and dependencies, created explicitly or through stream capture and instantiated for launch. This course's PyTorch capture retains compatible shapes and referenced storage.
CUDA stream
An ordered sequence of device operations; callers must respect dependencies across streams and buffer lifetimes until completion.
D2H
Device-to-host transfer; copying GPU results to CPU-accessible memory.
DCGM
NVIDIA Data Center GPU Manager, which provides health, job, and interval telemetry; its averages do not identify a source operator or kernel.
DCGM Exporter
An operator-owned service that exposes selected DCGM fields for Prometheus; it provides time-series telemetry, not source-level attribution.
Distribution
Multiple measurements summarized with median and tail or dispersion information rather than a single sample.
DMA-BUF
A Linux kernel mechanism for sharing buffers between device drivers; support must be established for the intended GPU and network path.
Drain
Completion of all required asynchronous work and consumers before a loop is declared complete.
Eager execution
Running PyTorch operations as the program reaches them, without first compiling a larger sequence.
Effective workload TFLOP/s
Declared useful floating-point operations divided by elapsed time. It is an application estimate, not hardware peak throughput or a count of all issued instructions.
Egress stream
A CUDA stream dedicated here to copying completed GPU outputs toward the CPU.
Epilogue
Work applied to matrix-accumulation results before final storage.
Exposed communication
Collective time that remains on the critical path after any useful overlap.
Fabric
The connected links and switches carrying traffic among endpoints.
FP32
32-bit floating point; storage dtype and the arithmetic used by an operation must be distinguished.
FP64
64-bit floating point, offering greater precision and range at a higher storage cost than FP32.
Fusion
Combining operations so intermediate traffic or launch overhead is reduced.
GEMM
General matrix multiplication, often expressed as C = alpha × A × B + beta × C.
GID
Global identifier used in RDMA addressing; modern NCCL selects RoCE GIDs dynamically.
Good benchmark
Equivalent work measured with explicit correctness checks and specified timed operations.
GPUDirect RDMA
Qualified NIC access to GPU memory without a host staging copy for the payload.
Graph break
A point where PyTorch cannot represent code in one compiler graph and resumes Python execution. This is distinct from CUDA stream capture, although it can reduce optimization opportunities.
Graph-private pool
Memory retained at stable virtual addresses for CUDA Graph capture and replay.
HCA
Host channel adapter; an RDMA-capable network adapter, whose device name differs from an IP-interface name.
Host-to-device transfer
Copying input bytes from CPU-accessible memory into GPU memory; distinct from submitting the command that starts a kernel.
In-place / out-of-place
Whether the collective result reuses input storage or uses distinct output storage.
Inactive split bytes
Allocator-reserved bytes in split blocks that are not currently serving a live allocation; useful fragmentation evidence only in context.
Inductor
PyTorch's default compiler backend for many torch.compile workflows.
InfiniBand
A switched network architecture supporting RDMA with compatible adapters, links and a subnet manager.
Kernel launch-bound
Dominated by dispatch overhead rather than device execution.
Layout
The mapping from logical tensor indices to storage addresses.
Limiter
The resource or dependency most constraining the declared workload boundary under the measured conditions.
Maintained library
A supported implementation such as cuBLAS, cuDNN, CUB/CCCL or CUTLASS that should be evaluated before owning a custom implementation.
Materialization
Writing an intermediate result into storage rather than keeping it within an executing kernel.
MLPerf
MLCommons benchmark suites with defined scenarios, quality targets, rules, and result checks; an informal course run is not an MLPerf result.
MPI / PMIx
Message Passing Interface and Process Management Interface for Exascale, respectively; MPI supports communication between processes, while PMIx supports process-management integration. The site must qualify MPI launch compatibility with Slurm.
NCCL
NVIDIA Collective Communications Library, software implementing GPU collectives and point-to-point communication using available topology-aware paths.
NCCL Tests
NVIDIA collective microbenchmarks used to sweep operations and message sizes independently of framework scheduling.
NCCL transport
The selected communication path, such as Socket or the IB transport that can use InfiniBand or RoCE.
NIC
Network interface controller connecting a host to a network.
Normalized bus bandwidth
NCCL Tests' collective-specific scaling of algorithmic bandwidth, not measured NIC wire traffic.
Nsight Compute
A kernel profiler used for selected-kernel metrics, including roofline, traffic, instruction, scheduler, stall, and occupancy evidence.
Nsight Systems
A system profiler used to inspect the temporal relationship among CPU work, CUDA APIs, kernels, copies, synchronization, NVTX ranges, and communication.
Numerical tolerance
The allowed difference between a result and its reference, usually stated with absolute and relative error bounds.
nvbandwidth
NVIDIA's copy-path utility for measuring declared host/device and device/device bandwidth or latency cases.
NVLink
A high-bandwidth interconnect between supported GPU endpoints; not a generic server-network configuration switch.
NVSwitch
Switching hardware connecting endpoints within a supported NVLink fabric; different from an InfiniBand switch.
NVTX
NVIDIA Tools Extension Library, an annotation API for semantic markers and ranges that connect profiler timelines to application phases such as input, forward, backward, prefill, or decode. It does not synchronize or time GPU work by itself.
Occupancy
Active warps relative to the SM limit; one diagnostic dimension, not an optimization target by itself.
Padding
Adding unused or neutral values to reach a selected shape while preserving the intended result.
Pinned buffer
Page-locked host memory used for asynchronous host/device transfers; pinning and allocation have costs.
Prefetch
Preparing future batches before the consumer requests them.
PyTorch Profiler
The framework profiler that attributes CPU and CUDA activity, calls, shapes, memory, and stacks to PyTorch operators.
Queue depth
The amount of queued or outstanding work: prepared batches in an input pipeline, or submitted transfers awaiting completion in an RDMA queue.
Queue pair (QP)
Adapter send/receive work queues; changing their count can affect flow distribution and overhead.
Rank
The index identifying one process in a distributed application.
Rank skew
Different participants arriving at a collective at different times, exposing waiting that is not cable-transfer time.
RDMA
Remote direct memory access using supported network hardware and registered memory; not assumed by this course.
Registration
Establishing the memory region, permissions and mapping that an adapter may use for data transfer.
Reserved bytes
CUDA memory held by the framework allocator, including both live allocations and eligible cached space retained for reuse.
RoCE
RDMA over Converged Ethernet; an RDMA transport over a suitably configured Ethernet fabric.
Roofline model
A plot of achieved FLOP/s against arithmetic intensity with memory-bandwidth and compute ceilings. It classifies a measured kernel or boundary; it does not prove the end-to-end bottleneck.
SM
Streaming multiprocessor, the GPU unit that schedules warps and contains registers, shared memory, and execution resources.
Speedup
Baseline time divided by candidate time for an equivalent declared boundary.
Starvation
A wait caused by the next required input batch not being ready.
Strong scaling
Adding ranks while total useful work remains fixed.
Synchronization
A dependency or wait that ensures required work has completed before dependent work proceeds.
Tail wave
A final scheduling wave with fewer blocks than available execution slots.
Tensor Core
Specialized matrix-multiply-accumulate hardware used only when an eligible operation, dtype, shape, and software kernel select it.
Throughput
Completed useful work per unit time, defined only after the unit and boundary are declared.
Tile
A smaller region of data handled cooperatively by an implementation.
torch.compile()
A PyTorch entry point that captures supported operations and generates optimized execution; compilation costs, graph breaks and recompilation can affect the outcome.
Unnecessary synchronization
A wait that delays submission or prevents useful overlap without being required at that point.
Warm-up
Untimed execution used to exclude initialization, compilation, allocation, and cache setup according to a declared policy.
Weak scaling
Adding ranks while useful work per rank remains fixed, increasing total work.

Official references

  1. CUDA programming model and CPU/GPU responsibilities
  2. PyTorch performance tuning guide
  3. PyTorch scalar extraction with Tensor.item
  4. PyTorch Profiler
  5. torch.compile
  6. PyTorch CUDA Graphs
  7. NVIDIA CUDA Graphs: nodes, dependencies, capture, instantiation and updates
  8. NVIDIA Nsight Systems
  9. NVIDIA Nsight Compute Profiling Guide
  10. CUDA C++ Best Practices Guide
  11. CUDA Runtime event timing
  12. NVIDIA DALI user guide
  13. CUDA Runtime memory-pool API
  14. NCCL documentation
  15. Slurm sbatch
  16. NCCL overview and supported communication paths
  17. NVIDIA DGX H100 system and network topology
  18. NVIDIA RDMA architecture, registration and work queues
  19. NVIDIA DGX SuperPOD H100 compute and management fabrics
  20. NCCL GPU-to-NIC registration and topology troubleshooting
  21. NCCL network diagnostics and RoCE GID guidance
  22. NCCL environment-variable definitions and warnings
  23. NCCL performance triage and tuning
  24. NVIDIA NCCL Tests v2.20.0 build and CLI
  25. NCCL Tests collective bandwidth formulas
  26. NCCL Tests v2.20.0 table writer and environment-export behavior
  27. NCCL Tests timing and device mapping implementation
  28. Slurm MPI integration guide
  29. CUDA asynchronous execution
  30. CUDA pinned memory and overlapping transfers
  31. PyTorch pinned and nonblocking transfer safety
  32. CUDA timing with CPU timers and CUDA events
  33. PyTorch compiler graph breaks
  34. Nebius GPU platforms and presets
  35. NVIDIA nvbandwidth, reviewed source
  36. RDMA perftest, reviewed source
  37. GPUDirect RDMA
  38. PyTorch profiler recipe
  39. Nsight Systems user guide
  40. Study regional ahead-of-time compilation
  41. Explore the current CUPTI interfaces
  42. Read the GPUDirect Storage design guide
  43. Study NCCL device-initiated communication
  44. Consult the NVML device-query reference