GPU Fundamentals builds the hardware and system model needed to explain GPU behavior before changing code. Learn how CPUs and GPUs cooperate, how an H100 executes and stores work, and how timing, memory access, precision and communication shape measured performance.
Read GPU Performance Tools before practical work. Start here if you can read a small Python program; no CUDA or model-training experience is assumed. The worked examples introduce the PyTorch operations used in practice and prepare you for GPU Performance Optimization and the specialized training, inference and kernel courses.
Local exercises use one full H100, and operational exercises are read-only. Lesson 12 applies distributed concepts in Labs 02 and 08 of Advanced Labs. Follow Lab Preparation in the shared Lab Guide. Its single command prepares the available lab software; read the completion summary before running experiments. Hardware checks remain part of the labs.
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. CPU–GPU cooperation
Objective
Decide which work belongs on the CPU, which belongs on the GPU, and where launch or transfer overhead dominates.
How it works
What this course is about
A CPU (central processing unit) runs the operating system and the ordinary instructions of your application. A GPU (graphics processing unit) is a processor designed to make progress on many similar pieces of work at once. This course explains how the two cooperate, how an NVIDIA H100 stores and executes work, and how to tell whether a workload is using it effectively. An array is an ordered collection of numbers; a tensor is a multidimensional array, such as a matrix of image pixels or model weights. You do not need prior CUDA knowledge to begin. Familiarity with a small Python program is enough for the explanations; the practical exercises introduce the relevant PyTorch operations.
Why use a GPU rather than a CPU
CUDA is NVIDIA's platform for programming its GPUs. PyTorch is a numerical-computing and machine-learning framework that expresses operations on tensors and can use CUDA to execute supported work on NVIDIA devices. A tensor's shape gives its dimensions, while its dtype specifies how each value is represented, such as 32-bit floating point. Batching means processing several items together; synchronization means waiting for required work to finish before using its result. These names describe different parts of execution, not interchangeable ways of saying that a GPU is busy.
Consider applying the same formula to one million independent values. A CPU can perform this correctly, using optimized vector instructions and several cores. A GPU can schedule far more concurrent arithmetic work and has high-bandwidth device memory, so sufficiently large parallel workloads may finish sooner. It does not calculate an entire large matrix in one instant: work is divided into many pieces and takes many execution cycles. GPUs are useful for matrix algebra, image processing, scientific simulation and neural networks because these problems often expose substantial parallelism and data reuse.
The CPU remains a good choice for small jobs, branch-heavy control logic, irregular pointer chasing, file handling and tasks whose data would cost more to move than to process. A CPU-only implementation does not become incorrect merely because the GPU is available; it may simply take longer for a suitable large workload, or it may win for a small one. Both latency (time for one result) and throughput (completed work per second) matter. The right device is an evidence-based choice, not a property of the programming language.
How the CPU, memory and GPU cooperate
The CPU is the host and the GPU is the device. Host RAM and the H100's high-bandwidth memory, or HBM, are distinct storage resources in the discrete-device model used here. A kernel is a function executed by GPU threads. A launch submits that work; it is not the same thing as copying its input data. A CUDA stream is a sequence of operations that execute in order. PyTorch uses the tensor's device and the available implementation to dispatch an operation: CPU tensors use a CPU path; CUDA tensors use a GPU path when supported. Moving a CPU tensor with to("cuda") transfers its data; it does not move the Python interpreter onto the GPU.
A GPU-resident tensor has its data stored in device memory: HBM on the H100 used here. The data may have been copied from the host, initialized on the GPU or produced by an earlier kernel. Residency describes where the data is stored, not whether it is being processed. Later, a resident thread block will mean something different: work assigned execution resources on an SM.
GPU architecture: based on H100 GPU
Start with three resources: SMs compute, L2 caches, and HBM stores the large data set. An SM (streaming multiprocessor) runs groups of GPU threads. L2 is an on-chip cache shared across SMs; it retains data to reduce requests to HBM. HBM (high-bandwidth memory) holds inputs, outputs and other large allocations. The first diagram shows just these three resources. It is a simplified data-access map, not a silicon floorplan or a sequence that every access must traverse.
H100 SXM 80 GB: SMs, L2 cache and HBM
A simplified whole-device view shows representative SM boxes for 132 streaming multiprocessors, linked to the shared 50 MB L2 cache and then 80 GB HBM3. Lines mean data-access connections, not timing or a mandatory path for every access. The ellipsis omits repeated SMs. This is not a silicon floorplan.
Use the H100 SXM 80 GB as a concrete example. Its enabled resources differ from the H100 PCIe 80 GB, which has 114 SMs, and from the full GH100 die design, which has 144. The numbers below describe the SXM product, not every H100 allocation.
Physical resource
H100 SXM 80 GB
GPCs
8
TPCs
66 enabled in total; 2 SMs per TPC
SMs
132
SM subpartitions
4 per SM; 528 in total
32-bit floating point (FP32) CUDA cores
128 per SM; 16,896 in total
Fourth-generation Tensor Cores
4 per SM; 528 in total
L2 cache
50 MB
HBM
80 GB HBM3
Hardware hierarchy: GPC → TPC → SM → SMSP
Each arrow here means contains. GPC stands for graphics processing cluster; NVIDIA's Hopper architecture description also calls it a GPU processing cluster. TPC means texture processing cluster. These historical names describe groups of hardware even when the GPU is doing numerical computation. A GPC contains TPCs, each TPC contains two SMs, and each H100 SM contains four SM subpartitions (SMSPs). The 66 enabled TPCs are a device total; dividing by eight does not describe an identical layout in every GPC.
Each SMSP has a warp scheduler, registers and execution units. A scheduler chooses ready work; registers hold working values. FP32 CUDA cores perform ordinary single-precision arithmetic, while Tensor Cores perform supported matrix operations. They are physical execution units, not software threads. Level-one (L1) caching and explicitly managed shared memory share a resource within each SM. Shared memory is temporary storage for cooperating threads, not an obligatory stage between L2 and registers. The second diagram enlarges one SM to show these details.
H100 overview: physical resources and logical work
A CPU prepares host data and submits command launches separately from data transfers. H100 HBM backs ordinary global allocations and a device-wide L2 serves SMs grouped in GPCs and TPCs. One SM is enlarged: unified L1 and shared memory plus four SM subpartitions with schedulers, registers and execution units. A logical grid contains blocks, warps and threads. Blocks are scheduled onto SMs. This is a conceptual map, not a silicon floorplan; shared memory is not a compulsory cache stage and product resource counts vary.
Work hierarchy: grid → blocks → warps → threads
A thread is one execution of the kernel with its own index and working values. A block contains threads that can cooperate, and a grid contains all blocks in one kernel launch. Within each block, hardware groups consecutive threads into warps of 32. Thus the programming hierarchy is grid → blocks → threads; including execution grouping gives grid → blocks → warps → threads. A thread does not contain warps. A partial final warp has unused lanes, and a warp never combines threads from different blocks.
For a worked example, follow A × B = C.
Matrix dimensions are written as rows × columns. To multiply A by B, the number of columns in A must equal the number of rows in B. Each output combines one row of A with one column of B: multiply corresponding entries, then add the products. This sum is a dot product. Here A is 2 × 3 and B is 3 × 2. Their shared dimension is three, so every dot product has three terms; the two rows of A and two columns of B give a 2 × 2 result C. Indices start at zero: C[0,1] means row 0, column 1.
For example, C[0,1] combines row 0 of A, [1, 2, 3], with column 1 of B, [2, 4, 6]: 1 × 2 + 2 × 4 + 3 × 6 = 28. The diagram highlights that row and column in blue. Matrix multiplication combines a whole row and column for each output; multiplying entries at matching positions would be a different operation.
A simple GPU kernel can assign one thread to each output element. Each thread reads its row of A and column of B, accumulates all three products in its own running sum, and writes one entry of C. Here the inputs are already in GPU memory and space for C is allocated. The kernel's indexing defines the assignment; the hardware does not infer it from the matrix equation.
Choose one grid containing one block of 2 × 2 threads. Each thread has two coordinates within the block, threadIdx.x and threadIdx.y, each either 0 or 1. In this example, the kernel uses the x coordinate as the output column and the y coordinate as the output row, so that thread computes C[threadIdx.y, threadIdx.x].
CUDA also assigns each thread a single number by counting across the x positions before moving to the next y position. Because this block has two threads along x, that number is threadIdx.x + 2 * threadIdx.y. The table labels these threads T0 through T3: T0 and T1 compute the first output row, and T2 and T3 compute the second. This numbering identifies threads; it does not specify their execution order.
GPU thread
(x, y)
Output and complete calculation
T0
(0, 0)
C[0,0] = 1 × 1 + 2 × 3 + 3 × 5 = 22
T1
(1, 0)
C[0,1] = 1 × 2 + 2 × 4 + 3 × 6 = 28
T2
(0, 1)
C[1,0] = 4 × 1 + 5 × 3 + 6 × 5 = 49
T3
(1, 1)
C[1,1] = 4 × 2 + 5 × 4 + 6 × 6 = 64
The GPU assigns the whole block to one SM. A lane is a position within a warp, numbered 0–31. This block occupies one partial warp: T0–T3 use lanes 0–3, while lanes 4–31 are unused. No extra 28 threads are launched. A warp scheduler in one of the SM's subpartitions selects ready warp instructions, such as loads, arithmetic and stores, and the participating lanes apply each instruction to their own values. Each thread computes all three terms of its dot product. A multiply and its addition may be fused into one instruction, so the arithmetic expression alone does not specify the emitted instruction count or execution time. Four outputs therefore do not imply completion in one clock cycle, four SMs, or four permanent assignments to CUDA cores.
Follow the diagram downward: first form a dot product, then map the four outputs to threads, group those threads into a warp on one SM, and store the results. Arrows between panels connect these conceptual views; they do not represent separate launch phases or clock cycles. Enclosing boxes show which work belongs together. Thread labels and four colors preserve the T0–T3 identities from assignment through the active lanes to C. The grid describes the launch; the SM hosts its resident block and warp. This is a teaching schematic, not a measured schedule.
In the output panel, the axis arrows show x increasing horizontally across columns and y increasing downward through rows. Matrix indices name the row first, column second, so this kernel's position (x, y) corresponds to C[y, x]. For example, (x=1, y=0) selects the top-right element, C[0,1] = 28. This is the mapping chosen by this kernel; CUDA does not require x to represent columns or y to represent rows.
Matrix multiplication: from four outputs to one scheduled warp
Read downward. Dimensions mean rows by columns: A (2 by 3) times B (3 by 2) gives C (2 by 2). The highlighted row 0 of A and column 1 of B give C[0,1] = 1×2 + 2×4 + 3×6 = 28. This example kernel assigns T0 to C[0,0], T1 to C[0,1], T2 to C[1,0] and T3 to C[1,1]. A one-block grid contains a 2-by-2-thread block, with x selecting columns and y selecting rows. That block resides on one SM. Its warp has 32 lane positions: T0–T3 use lanes 0–3; lanes 4–31 have no threads from this block. The scheduler issues ready instructions; each thread accumulates all three products and stores one result. C=[[22,28],[49,64]]. In the output panel, x increases to the right across columns and y increases downward across rows. Matrix indices name the row first and column second: C[row, column] = C[y, x] for this kernel. For example, (x=1, y=0) selects C[0,1] = 28. The kernel chooses this mapping; CUDA does not require it. Output-axis arrows show increasing coordinates; arrows between panels show conceptual assignment and result flow, not clock cycles. One output per thread is a kernel design choice; optimized kernels can use different mappings.
The one-to-one mapping is a kernel design choice, not a universal matrix rule. For a larger C, a simple version uses many blocks, each covering a rectangular output region, and checks edge indices before accessing memory. Optimized kernels often work on tiles, smaller rectangular pieces of a matrix: a thread may accumulate several outputs, and cooperating threads may contribute to an output. Tensor Core kernels use specialized matrix instructions with cooperative mappings. A PyTorch matrix multiplication therefore does not promise one thread per output. This four-thread launch makes the mapping easy to see, but leaves most warp lanes unused and is far too small to demonstrate GPU speed.
Logical work or residency limit
H100, compute capability 9.0
Grid
One per kernel launch; block count is chosen for the workload
Threads per block
Up to 1,024, equivalent to 32 full warps
Threads per warp
32
Resident warps per SM
Up to 64, equivalent to 2,048 resident threads
Resident blocks per SM
Up to 32; at most 2 with 1,024 threads per block. Other resource limits can reduce these counts
Resident work across 132 SMs
At most 8,448 warps or 270,336 threads
Here, a block is resident on an SM when the GPU has placed it on that SM and reserved register space for its threads, plus any shared memory the block needs. The SM keeps their register values and tracks where they are in the kernel.
For example, one resident warp may be waiting for a memory read while a scheduler lets another ready warp execute. Both remain resident. Therefore, 2,048 resident threads means the SM can keep track of that many threads at once; their warps share the execution units over time rather than all executing an instruction in the same clock cycle. The thread, warp and block limits all apply together.
A block's size is chosen by the program; it does not always contain 1,024 threads. With 1,024 threads per block, the 2,048-thread capacity allows at most 2 blocks per SM: 2,048 / 1,024 = 2. Each block uses 32 warps, so two blocks also reach the 64-warp limit. Smaller blocks can allow more blocks to reside together, up to the separate 32-block ceiling.
Threads per block
Upper bound on resident blocks per SM
1,024
2
512
4
256
8
128
16
64
32
32
32; the block-count limit applies
These bounds apply only the thread, warp and block limits. Register and shared-memory requirements can reduce how many blocks fit. For these block sizes, all of which are multiples of 32, calculate the smaller of 32 and 2,048 divided by the threads per block. At 32 threads per block, 32 resident blocks use only 1,024 threads: reaching the block limit does not necessarily fill the thread capacity. Smaller blocks therefore do not automatically keep more warps resident or improve performance.
The grid can be much larger than the resident work: pending blocks wait for resources, so a GPU has no fixed lifetime total of grids, blocks or threads.
For example, one kernel processing 1,048,576 values with one thread per value and 256 threads per block launches one grid of 4,096 blocks. Each block has 8 warps, giving 32,768 warps over the whole launch. Even if no other resource limits apply, the 2,048-thread limit permits only 8 such blocks per SM, or 1,056 across this GPU at once. The remaining blocks run as resources become available. This arithmetic describes work coverage and an upper bound, not a measured schedule.
The overview and enlargement connect the two hierarchies: blocks are placed on SMs, their warps use SMSP execution resources, and the SMs access data through the memory system. Lesson 3 develops scheduling in more detail; Hopper's optional thread-block clusters are introduced later as an additional grouping, not a requirement for an ordinary launch.
Execution and dependencies
Start with ordinary program latency: a result is ready only after every required operation finishes. In a CUDA program, distinguish host submission, memory transfers, kernel execution and synchronization. These operations can overlap when their dependencies permit; they are not four mandatory consecutive GPU phases.
Follow one calculation from the application to its result. The CPU prepares the input and asks CUDA to run a kernel. CUDA submits the request to a stream, which keeps device operations in order. The GPU executes the kernel when its dependencies and resources allow. The CPU can continue before that execution finishes: returning from the launch means the work was submitted, not that the answer is ready.
Where the data starts and where the answer is needed determine how much work this request involves. If the input is in host RAM, it must be copied to GPU memory before the kernel uses it. If the CPU needs the output, that output must be copied back after the kernel finishes. If the next operation also runs on the GPU, the output can stay there and become its input.
The CPU requests these transfers through CUDA; dedicated copy hardware usually moves the bytes between CPU and GPU memory. Synchronization enforces dependencies: a CPU thread can wait for GPU work to finish, or a GPU operation can wait for earlier work it depends on. Waiting for a calculation to finish and copying its result are separate operations.
Choose a timer and state exactly which operations it measures. A CPU timer records elapsed time between two points in the host program. Timing-enabled CUDA events record timestamps when the GPU reaches them in a stream; their difference measures that stream interval. Waiting for the end event makes the timestamps available, but does not copy a result to host memory. Lab 01 uses these tools for three comparisons:
CPU execution time: use a CPU timer around the CPU calculation.
GPU time with device-resident inputs: record CUDA events before and after the GPU operations. Input copies happened earlier, and the result stays on the device. The interval can include waits and idle gaps between the events; it is not necessarily the sum of kernel execution times.
End-to-end time including transfers: use a CPU timer from the first input copy until the returned output is usable on the CPU. This includes both input copies, host submission, GPU operations, the output copy and required waiting.
A timer stopped immediately after submission misses unfinished GPU work. A completed-work measurement waits for the result required by its chosen comparison. Lesson 8 explains how streams, events and synchronization establish that stopping point.
Host enqueue and device execution timeline
Read downward in each column. This is one possible execution order, not a measured timeline: box heights and gaps do not show how long operations take. The CPU starts a host timer, submits kernel A, kernel B and an event to one stream, then waits. The dashed blue arrow shows submission; the GPU can begin A while the CPU is still submitting work. The GPU executes A, then B, then completes the event. The green arrow shows that event completion lets the CPU finish waiting and stop the host timer. The timer includes submission and waiting. Event completion does not copy results: data remains on the GPU until a separate required copy makes it CPU-readable.
Batching sends more useful work with each launch, so the launch cost is shared across more items. It can improve throughput, but collecting a batch may make an individual request wait longer and requires storage for more inputs and temporary results. Keeping data on the GPU across several operations can avoid paying the transfer cost each time.
“The GPU is faster” is not an engineering rule. A GPU wins when enough independent work amortizes fixed overhead and when data can stay resident long enough to avoid repeated host-device movement. Interactive latency and batch throughput can therefore prefer different placements.
Try a small example
Suppose a CPU operation takes 2 milliseconds. A resident GPU operation takes 0.3 milliseconds, but uploading inputs and obtaining the result add 3 milliseconds. For this hypothetical one-shot request the GPU path takes 3.3 milliseconds, so the CPU wins. If ten dependent operations keep intermediate data on the GPU, the same total transfer cost plus ten 0.3-millisecond operations is 6 milliseconds, compared with ten 2-millisecond CPU operations. These are teaching assumptions, not H100 measurements.
Practice
Run the Lab 10 preflight, then use Lab 01 to compare CPU, resident-GPU and transfer-inclusive timings at the same element count.
The CPU organizes the work, and the GPU performs the calculation. Launch means the CPU asks CUDA to run a kernel on the GPU. The CPU can continue working after submitting that request, before the GPU has finished.
A transfer moves inputs from CPU memory to GPU memory and, when needed, results back. The CPU requests these copies; dedicated hardware usually moves the data. Results can stay on the GPU if the next operation needs them there.
Think of synchronization as waiting until required work has finished so dependent CPU or GPU work can safely proceed. It does not copy results back to the CPU; that requires a transfer. For small jobs, launching work, moving data and waiting can take longer than the GPU calculation itself.
2. GPU execution software layers
Objective
Explain which layer owns compilation, loading, compatibility, and execution.
How it works
The GPU software stack is the set of layers that turns an application into work the device can execute. A driver lets the operating system and programs communicate with the GPU. The CUDA runtime provides callable services—an application programming interface (API)—for allocating memory, submitting work and checking completion. The CUDA Toolkit supplies development tools, including the compiler that translates source code. PyTorch sits above these layers and selects implementations for tensor operations. A Python wheel is an installable package; it may bundle runtime libraries without including the full toolkit.
Parallel Thread Execution (PTX) is an intermediate GPU instruction language; SASS is target-specific machine code. A cubin contains compiled device code, while a fat binary can carry code for multiple targets. Just-in-time (JIT) compilation translates code when needed at load or execution time. Compute capability names a GPU's hardware feature level, not its driver or toolkit version. These separate meanings explain why matching one version number does not establish compatibility.
Lesson 1 distinguished host submission from GPU execution. This lesson names the software layers involved so a version string or error can be traced to the component it describes.
Consider a PyTorch operation on a CUDA tensor. PyTorch first selects an implementation, often from a library shipped with the framework package. That implementation uses CUDA runtime or driver APIs to arrange memory and submit GPU work. The user-mode driver loads the device code, while the kernel-mode NVIDIA driver manages access to the GPU. The device then executes the loaded kernel.
The code may have been compiled long before this call. The CUDA compiler, nvcc, translates CUDA C++ into target-specific device code, an intermediate representation called PTX, or a fat binary containing several versions. A cubin contains compiled device code; SASS names the final machine instructions. If the package supplies suitable PTX instead of a ready machine-code version, a compatible driver can compile it just in time for the GPU.
This explains why running and building have different requirements. A prebuilt framework wheel may include the CUDA runtime, libraries and kernels it needs, so running it does not necessarily require a local nvcc. Building a CUDA extension does require suitable compiler tools and headers. A toolkit installation cannot replace a missing or insufficient driver, and a new driver cannot add kernels absent from the package.
Software compatibility stack
Read downward: a framework or library supplies device code, the CUDA driver loads or translates a compatible version, and the GPU executes it. The toolkit compiler prepares code earlier; installing it is not a substitute for a compatible driver.
The target also matters. H100 has compute capability 9.0. SM90 identifies ordinary code for that architecture; SM90a allows architecture-accelerated features with narrower compatibility. A driver must understand the supplied PTX version before it can translate it. These names describe compatibility requirements; they do not demonstrate that an application ran successfully.
Data copies use a related hardware path. With direct memory access (DMA), a transfer engine moves the payload after software arranges the transfer, rather than requiring CPU instructions to copy every byte.
CUDA failures are often “repaired” at the wrong layer. Installing a local toolkit cannot fix an insufficient kernel-mode driver, and a new driver does not make a Python package contain missing CUDA libraries or kernels for the correct architecture.
Practice
Revisit Lab 10 to identify each software layer, then use Lab 08 to connect a PyTorch operation to its launches and kernels.
PyTorch calls CUDA libraries and runtime APIs; kernels are distributed as machine code or PTX; the driver loads and executes compatible code. The driver and toolkit are related but not interchangeable version numbers.
3. GPU execution architecture
Objective
Trace a PyTorch operation down to blocks scheduled on H100 streaming multiprocessors.
How it works
A GPU has physical execution resources, while a CUDA program describes logical workers. A thread is one worker executing the kernel; a block is a group of threads that can cooperate; a grid is the collection of blocks in one launch. Threads are organized into warps of 32, and a lane is one thread's position within its warp. A streaming multiprocessor (SM) is a physical unit that hosts blocks and executes their warps. A graphics processing cluster (GPC) contains texture processing clusters (TPCs), each with two SMs on H100; an SM itself contains four SM subpartitions (SMSPs) with scheduling and execution resources. These are different levels, not interchangeable names for GPU quadrants.
H100 execution hierarchy
Each enclosing box contains the one inside it: an H100 contains SMs, and each SM contains scheduling and execution resources. Logical blocks and warps are work assigned to this hardware, not additional hardware containers.
Tensor Cores are specialized matrix-arithmetic units within an SM. Different launches need not assign corresponding blocks to the same SM; within an ordinary launch, each block remains on its assigned SM for its lifetime. The later Triton examples use a GPU-programming language and compiler whose program instances describe cooperating work, not a different physical GPU hierarchy.
The software stack loads a kernel, but the kernel still needs a physical execution model. Reuse the grid, block, and warp vocabulary whenever later lessons discuss occupancy, divergence, memory, or Tensor Cores.
A kernel launch specifies a grid of blocks. The GPU assigns a block to an SM that has enough resources for it, and the block stays on that SM until it finishes. Other blocks can run alongside it if resources permit; blocks that do not yet fit wait. The grid describes all the work in the launch, not the amount executing at one instant.
CUDA grid, blocks, SM assignment, and warps
One kernel launch creates a grid of blocks. Blocks are assigned whole to available streaming multiprocessors, where block threads are grouped into 32-thread warps and scheduled on that SM. A later wave of blocks waits until resources become available.
Within the SM, each block's threads are grouped into warps of 32 lanes. Scheduling and execution resources are divided among the SM's four subpartitions, or SMSPs. Schedulers select ready warp instructions, which use the appropriate arithmetic, memory or matrix units. Tensor Cores execute supported matrix instructions issued by warps; they are not a separate place to assign an entire Python operation.
Simplified Hopper SM resource model
Four scheduler and execution subpartitions each contain a warp scheduler, a register-file partition, and execution pipelines. A unified L1, texture, and shared-memory resource spans the SM, while L2 and HBM are outside it.
Threads keep working values in registers. Cooperating threads in a block can use shared memory, while global-memory requests use the cache and high-bandwidth memory (HBM) system. H100's configurable L1 (level-one cache)/shared-memory carveout divides a shared on-chip capacity between caching and explicitly managed storage. The GPC/TPC/SM hierarchy describes hardware containment; it is not a mandatory sequence through which each byte or instruction passes.
Logical H100 device hierarchy
A logical, not-to-scale hierarchy shows host and PCI Express, HBM and memory controllers, shared L2 and on-chip fabric, replicated GPCs, TPCs, and two SMs per TPC.
Triton expresses work using logical blocks of array elements. A program instance handles one such block, and num_warps controls how many warps cooperate in it. BLOCK_SIZE describes logical elements, not a new hardware level or necessarily one element per thread. The instance index, tl.program_id(0), selects its portion of the input.
For N elements and B elements per program, ceil(N/B) instances cover the input. Each forms indices program_id*B + [0, ..., B-1] and masks accesses where index < N is false. With N=1003 and B=256, four programs describe 1024 positions; the final 21 positions must not load or store data. The mask makes the final partial block safe.
A high-level operator can be slow because it dispatches an unexpected kernel, launches too little parallel work, creates a partial final wave, or uses the wrong instruction path. None of those causes is visible from the Python name alone.
Practice
Use Lab 09 to map logical work to launch geometry. Revisit Lab 08 for launch evidence; read Lab 11 as a preview, leaving its full resource and tail investigation until Lesson 6.
A kernel creates a grid of thread blocks. Blocks are assigned to SMs; each block contains warps of 32 threads; warp instructions use scalar, vector, memory, and matrix pipelines according to the instruction mix.
4. GPU memory hierarchy
Objective
Choose the nearest useful memory level and recognize when data movement dominates.
How it works
The memory hierarchy is a set of storage locations with different capacities, access costs and sharing rules. Registers hold a thread's working values. Shared memory is fast on-chip storage explicitly managed by cooperating threads in a block. A cache automatically retains copies of recently accessed data: L1 (level-one cache) is close to an SM and L2 (level-two cache) is shared more broadly across the GPU. Device allocations in the global address space normally live in high-bandwidth memory (HBM). An address space describes which addresses code can refer to, not necessarily a distinct physical memory chip.
An allocation reserves storage for values. Temporal locality means reusing the same values soon; spatial locality means accessing nearby addresses. A spill places values that cannot stay in registers into thread-private local memory, which is backed by device memory despite its name. Understanding ownership and reuse comes before deciding where data should live.
Threads use registers, local memory, shared memory and global memory with different visibility and lifetimes. L1 and L2 caches are hardware storage that services memory accesses; they are not additional CUDA address spaces that the program allocates like a shared-memory array.
Trace a value used by a kernel. Its global-memory allocation normally lives in HBM. When a thread loads the value, caches may satisfy the request without another HBM access. The compiler keeps working values in registers where possible. If values spill into the thread's local-memory address space, they use device-backed storage and caching; the word “local” does not mean on-chip register storage.
Copy path and kernel memory-demand path
The host copy path moves data between host memory and HBM through PCI Express and a copy engine. A separate kernel-demand path moves data between HBM, device-wide L2, the SM unified L1 and shared-memory subsystem, registers, and execution pipelines.
A block can also load values into shared memory so its threads can reuse them. The program explicitly manages that storage and synchronizes cooperating threads before they consume each other's writes. Caches work differently: they retain data automatically and preserve the program's memory semantics. Shared memory is therefore an optional cooperation mechanism, not a compulsory stop between HBM and registers.
Memory hierarchy
Compare three storage roles without treating them as a mandatory path. Caches retain data automatically, shared memory is explicitly coordinated by a block, and registers hold thread working values.
At the framework level, PyTorch's memory_allocated reports live tensor storage and memory_reserved includes segments held by its allocator. These quantities describe allocation ownership. They do not reveal which values a running kernel keeps in registers or shared memory.
Indexing determines which stored value a load requests. A tensor view changes shape or indexing metadata while sharing storage. For a compact 2×3 matrix, strides [3,1] mean that moving one row advances three stored elements and moving one column advances one. A transpose produces a 3×2 view with strides [1,3]; the six values have not moved.
When that layout is not contiguous, contiguous() can create a compact copy. The copy reads the old storage and writes new storage, so it adds data movement before later operations can benefit. Shape, strides and element size let you derive addresses and distinguish input, output and temporary bytes. Lesson 7 connects those addresses to the memory requests made by a warp.
Performance is often limited by repeated movement rather than arithmetic. Correctly naming where a byte lives reveals whether the next change should improve reuse, remove an intermediate, alter layout, or reduce the workload's memory footprint.
Practice
Use Lab 04 to count reads and writes and trace where values live. Preview the byte-count reasoning in Lab 05; its full roofline experiment belongs to Lesson 10.
Registers are thread-local, shared memory is explicitly managed per block, caches capture reuse, and HBM provides large capacity with much higher latency. Useful reuse should occur before data returns to HBM.
5. Parallel control flow
Objective
Explain how one warp handles branches and why imbalanced lanes waste issue opportunities.
How it works
Single instruction, multiple threads (SIMT) is CUDA's execution model: a warp issues an instruction for the threads participating in it. A branch chooses a path, such as the body of an if statement. Warp divergence occurs when threads in that warp choose different paths; the required paths run with different participating threads. An active mask records which lanes participate in an instruction. Predication similarly prevents selected lanes from committing an instruction's effect, while reconvergence brings paths back together.
For example, if some lanes need a long calculation and others need a short one, finishing the short work does not make those lanes perform the long work for their neighbors. Divergence concerns cooperation within a warp. Unequal work between blocks and a partly filled final grid wave are different problems, even when all three leave some capacity unused.
A block becomes warps of 32 lanes. This lesson focuses on what happens when those lanes do not request the same instruction, while later tail analysis focuses on different blocks or ranks finishing at different times.
Imagine a warp reaching an if statement. Each thread evaluates the condition for its own data. If all participating threads choose the same branch, the warp can issue that branch's instructions with all those lanes active.
If the threads choose different branches, each path must still perform its required work. For one path, an active-lane mask selects the lanes that need those instructions; the other lanes do not contribute results. The other path runs with its own mask. Reconvergence brings the participating threads back to a common continuation. Time spent executing one path does not perform useful work for lanes assigned to the other.
SIMT and divergence
Read downward through a divergent branch. Each path runs for the lanes that need it; inactive lanes do not perform useful work for that path. The arrows show execution order, not a measured timeline.
For a short conditional, the compiler may use predication: it issues an instruction but prevents selected lanes from committing its effect. This can avoid an explicit branch, yet inactive lanes still do not produce useful results. The exact instruction sequence depends on compilation.
Independent thread scheduling gives the hardware more flexibility in tracking and scheduling threads around divergence and synchronization. It does not turn divergent paths into free parallel work. Code that exchanges values between lanes must still use the required warp-level synchronization; it cannot assume that all lanes always advance together.
Divergence is commonly blamed for any uneven timeline. That diagnosis produces ineffective fixes when the real cause is block-duration skew, insufficient grid waves, memory dependencies, or rank imbalance.
Practice
Inspect the active-lane model in Lab 11 and predict which lanes do useful work. Run its full launch comparison after Lesson 6 has introduced resource and residency limits.
SIMT executes one instruction over active lanes. Divergent branch paths are executed with different lane masks, and the warp reconverges after the paths complete.
6. Occupancy and latency hiding
Objective
Relate registers, shared memory, block size, active warps, and latency hiding.
How it works
Occupancy is the ratio of active warps on an SM to its maximum supported active warps. Here, active means resident: their execution state has resources assigned, even while they wait. Theoretical occupancy is the maximum permitted by a launch's resource requirements; achieved occupancy is measured during execution. An eligible warp is ready to issue its next instruction. Latency hiding means executing other eligible work while one warp waits, for example for a memory load to complete. More resident warps can provide more choices, but cannot remove a dependency within one calculation.
Instruction-level parallelism (ILP) means independent instructions within a thread can make progress without waiting for one another's results. For example, updating two independent accumulators (variables holding separate running results) offers more scheduling freedom than repeatedly updating one accumulator. This supplies ready work within a warp, whereas scheduling another resident warp supplies ready work from other threads. Keeping more independent values live can require more registers.
Registers and shared memory limit how many blocks fit together. Register pressure is the demand for register storage; allocation granularity means resources are assigned in fixed-size units rather than arbitrary fractions. Spilling stores excess thread-private values in device-backed local memory. Occupancy is therefore a resource and scheduling measure, not the percentage of peak arithmetic achieved or a guarantee that increasing it makes the program faster.
The hierarchy, memory and single-instruction, multiple-thread (SIMT) lessons identified SMs, registers, shared storage and active lanes. Occupancy now asks how those finite resources limit resident blocks and warps, and whether that residency is enough to hide waiting.
Before a block can become resident, the SM must have room for its threads and warps, a free block slot, enough registers and enough shared memory. All these limits apply together. The resource that runs out first determines how many such blocks can reside on that SM.
Occupancy and latency hiding
Read downward: registers, shared memory and hardware limits bound resident work. A scheduler can select a ready warp while another waits. More resident warps help only if they supply useful ready work.
Registers are used by individual threads, so a block with many threads can consume substantial register capacity even when each thread uses a modest number. Hardware allocates registers in fixed-size units, which can make a small source change cross a residency threshold. Shared-memory demand is counted per block. Reducing either demand helps residency only if it allows another block to fit within every remaining limit.
Once blocks are resident, the scheduler chooses among their warps. A warp waiting for a load is resident but cannot issue a dependent instruction. Another warp with ready work may issue while it waits. This is latency hiding: the wait still exists, but independent work uses time that would otherwise be idle. A resident warp may be ready, selected to issue, or stalled; residency alone says nothing about useful work in a particular cycle.
Warp scheduling hides latency
When one warp waits for data, an SM warp scheduler can issue an eligible instruction from another resident warp. Steps are illustrative scheduling opportunities, not measured H100 cycles or memory latencies.
Forcing fewer registers can backfire. Values that no longer fit may spill to device-backed local memory, adding loads, stores and new waits. A kernel with more resident warps can therefore run slower than one with fewer warps and less data movement.
A kernel needs enough independent ready work to cover instruction and memory latency. Chasing the maximum occupancy percentage can instead force spills, shrink useful tiles, or increase synchronization.
For a simple resource example, suppose each 256-thread block needs 32 KiB of shared memory and an SM makes 64 KiB available to these blocks. Shared memory permits only two blocks, or 16 warps, even if the thread and register limits would allow more. Relative to a 64-warp ceiling, that is 16 / 64 = 25% theoretical occupancy. This hypothetical capacity calculation predicts what can fit, not which warps are ready or how fast the kernel runs.
Practice
Revisit Labs 09 and 11 to separate launch size, resident capacity and the final scheduling wave; explain why more launched work does not mean more simultaneous execution.
An SM keeps several warps resident and switches among ready warps. Registers, shared memory, threads, and block slots limit residency.
7. Memory access efficiency
Objective
Connect lane addresses to memory transactions and useful bandwidth.
How it works
Coalescing is the memory system's combination of addresses requested by active lanes of a warp into as few transactions as the access pattern allows. A transaction transfers a chunk of memory, so fetching scattered values can move more data than the useful values alone require. A stride tells how far the storage address advances when a logical index increases. Alignment means starting at a useful address boundary; a sector is a fixed-size portion used in memory-traffic accounting.
A tensor view changes how indices refer to existing storage without copying its values. A copy creates new storage, possibly with a different layout. A contiguous tensor has a compact logical layout, but good coalescing still depends on which indices adjacent lanes actually access. This lesson connects those lane addresses to traffic, rather than treating contiguous storage as a universal performance switch.
The memory hierarchy explains where data can live. Coalescing explains how one warp’s lane addresses are combined when those data must cross the global-memory interface.
Start with the addresses requested by one warp instruction. Suppose all 32 lanes read one 4-byte value, and lane i reads base + 4*i. The useful values occupy 128 consecutive bytes. If the base is suitably aligned, the memory system can cover them with a compact group of sectors and transactions. This does not imply a single 128-byte hardware transaction.
Coalesced access
The arrows connect lane addresses to memory traffic. Adjacent aligned requests can share fetched regions; large strides spread the same useful values across more regions. Fewer logical values alone does not guarantee fewer transactions.
Now separate adjacent lane addresses by a large stride. The warp still requests only 32 useful values, but those values lie in many different memory regions. More sectors must be fetched, including bytes no lane needs. An otherwise compact pattern can also require an extra sector when it starts across an alignment boundary. Coalescing concerns this grouping of lane requests, rather than only the total tensor size.
Adjacent and strided warp memory access
In the upper example, adjacent warp lanes request adjacent words that fit into a small set of memory sectors. In the lower example, strided lanes request one word from many separated sectors, transferring more bytes than the warp uses.
A PyTorch view can expose such a strided pattern without moving any values. The next kernel's mapping from lanes to tensor indices decides the addresses it actually requests, so a view is not automatically slow and contiguous storage is not automatically enough for good coalescing.
Repacking with contiguous() creates a copy when needed. It pays for an extra read and write now in exchange for potentially cheaper later accesses. That trade is useful only when the time saved by later operations exceeds the packing cost.
A kernel can request the same logical number of elements while causing very different physical traffic. Effective bandwidth divides the counted read and write bytes by elapsed time. The lab calls its logical-byte estimate useful bandwidth. Profiler-observed traffic can differ because of cache reuse, intermediate operations and bytes transferred that no active lane uses.
Practice
Revisit Lab 04 to compare strided consumption with repacking, including the copy cost in the complete result.
Memory requests from a warp are combined into transactions. Adjacent, aligned lane addresses usually use fewer transactions than large strides or scattered access.
8. Asynchronous execution and timing
Objective
Measure asynchronous work and distinguish overlap from reordered timestamps.
How it works
A CUDA stream is an ordered sequence of device work: operations in the same stream obey that order, while independent streams may overlap if resources permit. An event marks progress in a stream. The CPU can wait for an event, or another stream can wait for it to enforce a device-side dependency without blocking the CPU. Nonblocking submission means a host call can return before the requested operation finishes; it does not mean the operation is already complete.
Host-to-device (H2D) and device-to-host (D2H) transfers move data between CPU and GPU memory. Pinned host memory is page-locked host memory: its pages cannot be paged out while locked. It supports asynchronous host/device transfers; ordinary pageable memory can require staging through a pinned buffer. Copy engines perform transfers separately from arithmetic execution where supported. Double buffering uses two buffers so a producer can fill the next one while a consumer processes the current one, with events protecting safe reuse.
Lesson 1 separated submission from completion. Streams and events provide the ordering tools needed to make that distinction correct in programs with copies and multiple device operations.
Suppose a copy produces an input and a kernel consumes it. Putting both operations in one CUDA stream orders the kernel after the copy. The CPU may return from submitting them while the device is still working, but the stream preserves their required order.
If the producer and consumer use different streams, the program must connect them explicitly. Record an event in the producer's stream after its work. Make the consumer's stream wait for that event before using the result. Recording the event submits a marker; the event becomes complete only when the preceding work has reached it. A stream wait delays dependent device work, whereas a CPU wait delays the host until completion.
Independent work can overlap when the hardware has resources for both operations. To overlap a host-to-device copy with computation, the copy needs suitable pinned host memory and asynchronous submission, a usable copy-engine path, and compute that does not depend on that same unfinished copy. Unintended synchronization can serialize the operations even when these conditions hold.
Double buffering uses this independence across successive batches. First fill one buffer. Then compute on it while filling the other. Continue alternating, and finally wait for the remaining work to drain. A buffer cannot be overwritten while a copy or kernel still uses it; tensors and staging storage must stay alive through their last asynchronous use.
Double-buffered copy and compute timeline
A fill phase copies batch zero. During steady state, the copy stream transfers the next batch into the free device buffer while the compute stream consumes the current buffer. Events make each consumer wait for its batch and prevent a producer from overwriting a buffer still in use.
Timing follows the same dependencies. Record timing-enabled CUDA events before and after the operations being measured, wait for the end event, then read the elapsed time between them. In PyTorch, these steps use torch.cuda.Event(enable_timing=True), record(), synchronize() and elapsed_time(). For multiple streams, make the stream containing the end event wait for all measured streams first. A CPU timer, such as Python's time.perf_counter(), measures host-observed elapsed time. It must stop after the required GPU work and any output transfer complete when measuring the full request. Stopping it after submission instead measures how quickly the CPU queued work.
Apparent overlap can be a timestamp illusion, and accidental synchronization can erase real overlap. Incorrect stream dependencies can also expose partially produced tensors or surface an earlier asynchronous error at an unrelated later call.
Practice
Use Lab 03 for host-transfer costs and Lab 07 for submission versus completion; state the start, stop and synchronization boundary of each timer.
CUDA streams order work within a stream while permitting independent work across streams. True copy/compute overlap also requires compatible hardware paths, pinned host memory, independent copy and compute work, and explicit producer–consumer dependencies.
Floating-point formats represent numbers using a sign, an exponent and a fraction. The exponent controls range—how large or small a value can be—while the fraction controls precision, or the spacing between representable values. 32-bit floating point (FP32), 16-bit floating point (FP16) and 8-bit floating point (FP8) use 32, 16 and 8 bits; bfloat16 (BF16) means brain floating point 16 and distributes its bits differently from FP16. Rounding selects a representable approximation. Overflow exceeds the available range; underflow makes very small values lose precision or become zero.
Accumulation is the running combination of partial arithmetic results, such as sums in a dot product, and can use a wider format than the inputs. Tensor Cores accelerate supported matrix operations; TensorFloat-32 (TF32) is an arithmetic mode for FP32 inputs, not a separate tensor storage dtype. Scaling changes magnitudes to fit a chosen representation. A format decision must consider both the stored values and the arithmetic actually performed.
Arithmetic pipelines consume values fetched through the memory system. Precision changes both the representation of those values and which library or Tensor Core instruction can implement an operation.
Separate stored values from the arithmetic used on them
A precision choice affects two stages. First, storing or converting an input rounds its values to a representation. Then the selected kernel performs arithmetic, possibly using a wider format for intermediate sums. The output may be rounded again when it is stored. Input, multiplication, accumulation and output precision therefore need not match.
FP32 offers a broad range and relatively fine precision. FP16 uses fewer bytes but has a narrower range, so some computations need scaling to keep important values representable. BF16 keeps the FP32-sized exponent but fewer fraction bits: it preserves a similar range with coarser spacing. FP8 uses fewer bits again and needs a suitable scaling recipe and higher-precision accumulation or surrounding state.
TF32 is different: it is a Tensor Core compute mode for selected operations on FP32 inputs, not a storage dtype. Matrix dimensions, alignment, operation type, framework policy and library selection determine the actual kernel. Pointwise operations may still run on ordinary CUDA cores inside a mixed-precision program.
Fit values into the chosen representation
An encoding determines which numbers can be represented. FP formats allocate bits to sign, exponent and fraction; 8-bit integer (INT8)/INT4 quantization instead represents values through integer codes and scale/zero-point conventions. Four-bit weights are not automatically FP4 training. Smaller formats trade range or spacing between values for fewer bytes. A scale maps values into the available range; large outliers can make small values hard to preserve. In integer quantization, a zero point is the integer code that represents real zero. Per-tensor scaling shares one scale across the whole tensor; per-channel scaling assigns scales along a selected feature dimension; block scaling assigns a scale to each bounded group of values. Sharing one scale is simple, while smaller groups can improve local fit at the cost of metadata and extra operations. Keep sensitive reductions and accumulations in suitable higher precision, and measure the complete conversion-plus-compute path.
Follow the framework policy to the selected implementation
A matmul precision policy chooses which internal arithmetic a framework may use for FP32 matrix products. torch.set_float32_matmul_precision("highest") requests FP32 internal computation; "high" permits supported faster reduced-precision internal algorithms. It does not convert the stored tensors to BF16 or guarantee one kernel. The policy affects eligible operations after it is set, but identifying the selected kernel requires separate dispatch evidence. Explicit BF16 or FP16 inputs are different cases because their values have already been rounded to those storage formats.
Conditions for a Tensor Core execution path
Storage format is only the first condition. The operation must be matrix-oriented, shapes and layouts must be supported, and the selected library or compiled kernel must issue a compatible Tensor Core instruction. Pointwise operations take a different execution path. Both paths require numerical and application validation.
Understand what the error measure captures
The Euclidean (L2) norm is the square root of the sum of squared elements. Relative L2 error divides the norm of candidate-minus-reference by the reference norm, measuring aggregate discrepancy rather than the worst element. Reference [3,4] and candidate [3,4.1] give 0.1/5 = 0.02. Choose the reference and near-zero denominator rule before testing; Lab 02 uses a random reference expected to have a nonzero norm. A zero-reference extension needs a declared absolute-error or guarded-denominator policy, as explained in its guide. Compare each candidate with the appropriate reference, keep finite checks, and report both timing and error. An aggregate threshold does not establish task quality or bound every individual element.
Lower precision can reduce bytes and accelerate matrix operations, but a dtype annotation does not guarantee Tensor Core dispatch or acceptable training/inference behavior. Storage, input, multiply, accumulation, and output precision can differ.
Practice
Run Lab 02 with its fixed operation and error checks, then relate numerical format to observed kernel execution and throughput.
H100 Tensor Cores accelerate supported matrix operations and dtypes, but dispatch depends on shapes, alignment, library selection, and framework policy. Accumulation precision and scaling still determine numerical behavior.
10. Arithmetic intensity and performance limits
Objective
Decide whether another byte or another operation is the more valuable optimization target.
How it works
The roofline model relates a workload's arithmetic rate to how much data it must move. A FLOP is one floating-point operation; FLOP/s measures operations completed per second. Bandwidth measures bytes transferred per second. Arithmetic intensity is operations per byte at a stated memory boundary, such as high-bandwidth memory (HBM). A roofline plot puts intensity on the horizontal axis and achieved arithmetic rate on the vertical axis. Its sloped bandwidth ceiling and horizontal compute ceiling meet at the ridge point.
A low-intensity calculation may have to wait for bytes even when arithmetic units are available; a high-intensity one can reuse enough data to approach a compute limit. The ceilings describe upper bounds under declared assumptions, not expected measurements. The chosen precision, operation type and byte-count boundary must match the plotted workload before the model can explain a result.
Roofline reasoning for two workloads
A rising bandwidth ceiling meets a flat compute ceiling; a vector workload lies on the rising side and matrix multiplication lies farther right.
The previous lessons explained how to count data reads and writes and identify the arithmetic performed. Roofline combines those counts into a performance bound that helps choose the next experiment without pretending to predict every kernel detail.
Begin with a count of useful floating-point operations and the bytes needed to perform them. Choose one memory boundary, such as HBM, and include the reads, writes and intermediate traffic that cross it. Dividing operations by bytes gives arithmetic intensity: how much useful arithmetic is performed for each byte moved.
The bandwidth ceiling follows directly. If the memory system supplies a given number of bytes per second, and each byte supports a given number of operations, multiplying those quantities gives the maximum arithmetic rate that data supply can sustain. As intensity increases, this ceiling rises: more reuse lets each transferred byte support more work.
The arithmetic units impose a second ceiling, the attainable compute rate for the relevant operation and precision. Performance cannot exceed either ceiling, so the roofline uses the lower of the two. Their intersection is the ridge point. Below that intensity, the bandwidth bound is lower; above it, the compute bound is lower. Independently measured sustainable rates are usually more informative than marketing peaks, which remain upper bounds.
Roofline classification
The horizontal axis is operations per byte and the vertical axis is operations per second. The sloped bandwidth ceiling meets the flat compute ceiling at the ridge point. This is a schematic bound with no measured workload points.
A measured point far below both ceilings needs another explanation. Launch gaps, dependent instructions, uneven work, an unsuitable instruction path or too little parallelism can all prevent a kernel from approaching either bound. The model narrows the possibilities; it does not diagnose the bottleneck by itself.
GPU performance bottleneck map
The learner starts with a user-visible metric, inspects the critical-path timeline, classifies host, input, transfer, memory, compute, parallelism, synchronization, communication, or capacity limits, and chooses a discriminating experiment.
Optimizing arithmetic in a bandwidth-limited kernel or compressing bytes in a compute-limited kernel may not move elapsed time. A roofline position turns a vague utilization observation into a falsifiable resource hypothesis.
For example, suppose a kernel performs 2 billion floating-point operations and transfers 1 billion bytes at the memory boundary being modeled. Its arithmetic intensity is 2 operations per byte. With an assumed sustainable bandwidth of 1 trillion bytes per second, the bandwidth bound is 2 trillion operations per second. If the assumed compute ceiling is 10 trillion operations per second, the lower bound on elapsed time is the larger of 1 millisecond for traffic and 0.2 milliseconds for arithmetic: 1 millisecond. These illustrative assumptions describe a bound; dependencies, launches and inefficient access can make the measured time longer.
Practice
Run the full Lab 05 experiment: calculate bytes and operations first, derive a bound, then explain the measured result against it.
Arithmetic intensity is operations divided by bytes transferred. Roofline compares that intensity with attainable memory bandwidth and compute throughput to bound performance.
11. GPU sharing and operational health
Objective
Distinguish full GPU, MIG, MPS, and time-slicing and collect non-intervening health evidence.
How it works
GPU sharing determines which applications can use physical resources at the same time. Multi-Instance GPU (MIG) partitions supported hardware into isolated GPU instances. Multi-Process Service (MPS) coordinates work from multiple CUDA processes so compatible work can share execution resources. Time-slicing alternates access over time. A CUDA context holds a process's device-execution state; it is not itself a hardware partition. These sharing modes differ from an application merely launching several streams.
Health monitoring reports whether the device is operating normally. Error-correcting code (ECC) detects or corrects certain memory errors; Xid messages are driver-reported diagnostic events. Clock frequency is the rate at which hardware operates, and throttling reduces it in response to limits such as power or temperature. NVIDIA Data Center GPU Manager (DCGM) gathers operational metrics and health checks. A counter's scope identifies which device, instance or time interval it describes; an observation alone does not prove exclusive access.
The single-GPU lessons explain useful work and timing, while the initial preflight checks the allocated device before every run. Now interpret sharing and operational signals in more depth, before adding two-node communication. These observations never authorize changing the cluster.
First separate resource allocation from the way work is shared. A full-GPU allocation assigns a scheduler-visible device to a workload; that allocation alone does not prove that no other process can access it. MIG divides supported compute and memory resources into hardware-isolated instances. MPS instead coordinates concurrent work from CUDA processes. On H100 those clients retain separate CUDA contexts and GPU address spaces while sharing scheduling resources. Time-slicing gives workloads turns on shared resources without creating MIG-style hardware partitions.
Sharing modes
Compare allocation and sharing choices. MIG partitions supported hardware; MPS coordinates CUDA processes; time-slicing alternates access. A full-GPU scheduler allocation alone does not prove that no other process uses the device.
These arrangements affect how much work can run and which counters describe it. A reading for a physical GPU may cover a different scope from a reading for one instance. Before interpreting a change, identify the device or instance and the time interval represented by the observation.
Next distinguish the health signals. ECC counters describe corrected or uncorrectable memory errors; a change during a trial has a different meaning from a lifetime total. Xid events are driver error classifications that require further diagnosis. Retired-page and row-remapping information records memory-reliability handling; interpret only fields supported on the device, including H100's row-remapping information. Clocks, power, temperature and link state describe operating conditions. A nearby change can be relevant without proving what caused an application slowdown.
Health context
Compare reliability signals with operating-state signals, then relate both to the same trial interval. ECC/Xid changes, power and clocks provide context; temporal correlation alone does not identify the cause of a slowdown.
Activity and capacity counters also answer different questions. Sampled GPU activity reports whether work was active during a sampling window, not the fraction of peak arithmetic achieved. Memory-controller activity concerns time serving traffic, while allocated bytes describe occupied high-bandwidth memory (HBM) capacity. Neither capacity nor an activity percentage is a transfer rate. A one-second sample can hide repeated short busy and idle bursts.
A useful interpretation connects signals from the same interval to the application's execution timeline. Passive DCGM health watches interpret collected fields; active diagnostics can alter execution and belong to a separate workflow. More detailed profiling counters require coordination with other collectors. These labs keep observations read-only and escalate concerning changes to an administrator rather than changing sharing or monitoring configuration.
Sharing or clock/thermal events can change variance and throughput enough to invalidate a benchmark. They are context, not automatic root causes, and observing them must not silently reconfigure the node.
Practice
Use Lab 12 to collect read-only health and sharing evidence, keeping unavailable measurements distinct from zero activity.
MIG creates hardware-isolated instances, MPS coordinates CUDA processes, and scheduler time-slicing shares execution over time. ECC, Xid, retired-page, power, clock, thermal, and link signals provide system context but do not by themselves prove an application cause.
12. GPU communication and distributed execution
Objective
Explain the networking layers, trace GPU-to-GPU data movement, and select meaningful collective measurements on the separate advanced fabric cluster.
How it works
A node is a machine in the cluster; a rank identifies one participating process; topology describes how machines, GPUs and network interfaces connect. A collective is a communication operation performed by a group of ranks. NVIDIA Collective Communications Library (NCCL) supplies GPU-oriented collectives: all-reduce combines values and returns the combined result to every rank, all-gather assembles each rank's piece, and broadcast sends one rank's values to the group. A shard is one piece of a larger tensor; the payload is the data being communicated.
GPU networking lets separate devices exchange the values needed to cooperate on one problem. The names in this lesson describe different layers, not competing products that all do the same job. NVLink is a GPU interconnect; NVSwitch connects NVLink endpoints; InfiniBand and Ethernet are network fabrics; RDMA over Converged Ethernet (RoCE) carries remote direct memory access (RDMA) over Ethernet; GPUDirect RDMA makes supported GPU memory accessible to a network adapter; NCCL is communication software that uses available paths. A fabric is the connected collection of links and switches carrying traffic between endpoints.
Single-GPU execution, timing, roofline and read-only health checks now provide a local baseline. Two-node work adds process placement and network collectives; verify both allocated devices before interpreting their shared critical path.
Follow a value from one GPU to another. First identify the local device connections, then the network between machines, and finally the software operation that uses that path. Each layer adds a different part of the explanation.
First locate the devices and their connections
A network interface controller (NIC) connects a machine to a network. In InfiniBand documentation, an endpoint adapter is also called a host channel adapter (HCA); NVIDIA ConnectX adapters provide supported networking capabilities. PCI Express (PCIe) connects devices through switches and host root complexes. Non-uniform memory access (NUMA) means that the access cost to host memory depends on the CPU/socket attached to that memory. A nearby GPU and NIC may have a different path from a pair whose traffic crosses CPU sockets. Placement therefore matters even when the endpoint GPUs have the same model name.
Two-node topology
Double-ended arrows represent communication in either direction between the nodes. The GPU-to-NIC attachment and network are part of the path; this schematic does not establish RDMA use or NVSwitch scaling.
NVLink carries communication between supported GPU endpoints at high bandwidth. NVSwitch is switching hardware for NVLink: it gives several GPUs paths to one another instead of requiring every pair to have a dedicated direct link. A supported multi-GPU DGX H100 system has this scale-up connectivity as well as network adapters for communication beyond the system. NVSwitch is not an InfiniBand switch, and NVLink is not a setting that creates a connection between arbitrary servers. Special NVLink Switch System deployments can extend supported NVLink domains; their dedicated hardware is not part of this course's two-node target.
Supported scale-up and the course scale-out target
The left comparison depicts multiple GPUs connected by an NVSwitch inside a supported system. The right depicts the course's two nodes, each with one GPU connected through a NIC to a network fabric. This target contains no intra-node GPU pair to test NVLink.
Then identify the inter-node fabric
InfiniBand is a switched networking architecture with its own link and transport mechanisms. Its subnet manager discovers and configures the fabric's forwarding paths; that service belongs to the cluster operator. NVIDIA Quantum switches and compatible ConnectX adapters are examples of components in an NVIDIA InfiniBand deployment. An H100 GPU alone does not supply an InfiniBand fabric.
RoCE means RDMA over Converged Ethernet. It brings RDMA communication to compatible Ethernet adapters and networks. RoCEv2 uses UDP/IP encapsulation and can traverse a routed IP fabric. It is not ordinary application UDP socket I/O: the RDMA adapter executes the transfer protocol. Ethernet traffic does not automatically become RoCE traffic, and a TCP connection over an InfiniBand IP interface is not proof that an application used RDMA. NVIDIA Spectrum Ethernet and Quantum InfiniBand switches serve different fabric roles.
Congestion is competition for a link or queue whose capacity is temporarily insufficient. On RoCE networks, operators may use ECN (explicit congestion notification) to mark congestion, CNPs (congestion notification packets) to notify senders, and PFC (priority flow control) to pause selected traffic classes. These mechanisms require a coordinated design; indiscriminate pausing or mismatched configuration can hurt latency. Learn what the counters mean, but do not change NIC or switch policies as a course exercise.
Understand RDMA before adding GPU memory
Remote direct memory access (RDMA) allows a network adapter to transfer data into or out of registered memory on a remote machine without the receiving CPU copying each payload through the ordinary socket path. Registration establishes which memory the adapter may access and how. A queue pair (QP) holds send and receive work queues; a completion queue reports completed work requests and their status. CPUs and drivers still create connections, register buffers and coordinate work. RDMA does not mean that the application has no CPU activity or synchronization requirements.
RDMA can operate on host memory. GPUDirect RDMA adds a supported direct path between a network adapter and GPU memory, avoiding a host-memory staging copy for that transfer. Conceptually, the host-staged path is GPU memory → host buffer → NIC → network → NIC → host buffer → remote GPU memory. A qualified direct path is GPU memory → NIC → network → NIC → remote GPU memory. PCIe attachment and registration remain involved; the NIC is not magically connected to GPU high-bandwidth memory (HBM) without an interconnect. GPUDirect peer-to-peer concerns local device access, while GPUDirect Storage concerns supported storage I/O. Those names do not prove that a particular network transfer is GPU-direct.
Host staging versus qualified GPUDirect RDMA
The top path stages GPU payloads through host RAM on each side of an RDMA network. The bottom path allows supported NICs to access GPU memory without those host staging buffers. Both still require adapter setup, interconnects, registration and correct completion ordering.
Finally place NCCL above those paths
NCCL supplies topology-aware communication operations; frameworks such as PyTorch invoke it instead of implementing the network protocol themselves. It can use supported local GPU links, PCIe, RDMA network transports or IP sockets. The physical path and collective algorithm are separate choices. A ring organizes communication in neighbor-to-neighbor steps, whereas a tree organizes hierarchical exchanges. Neither word identifies the installed fabric. Even an RDMA data path may use IP connectivity to exchange setup information.
GPU networking layers and their roles
Applications request collectives from NCCL. NCCL can use local GPU interconnects or network transports. InfiniBand and Ethernet with RoCE provide RDMA fabrics; GPUDirect RDMA describes direct access to GPU memory, not a separate fabric.
All-reduce combines values and returns the result to every rank; reduce-scatter combines and shards; all-gather reconstructs shards; all-to-all exchanges distinct partitions. For example, rank 0 holds [1, 2] and rank 1 holds [3, 4]. Sum all-reduce gives both [4, 6]; it does not concatenate them into [1, 2, 3, 4]. Every participant must agree on the operation, datatype, count and collective ordering. A mismatch can hang or fail rather than produce a useful benchmark.
Small messages emphasize fixed latency and launch/synchronization overhead, while large messages emphasize sustained transfer. Algorithmic bandwidth divides the logical payload by elapsed time. NCCL Tests' bus bandwidth applies a collective-specific normalization; it is not a direct measurement of physical NIC traffic. Strong scaling holds total work fixed as ranks increase; weak scaling grows total work with rank count. Both require the slowest-rank step time and identical correctness semantics.
Coordinate the participating processes
Slurm is the cluster workload manager: a job requests resources, and a job step starts processes inside that allocation. A launcher assigns each process a rank, a local device and the information needed to find its peers. PyTorch's torchrun supplies such process coordination; a process group is the set of ranks participating in its collectives. All ranks must call matching collectives in the same order. A barrier waits for the group to arrive, while an all-reduce combines payload values; they serve different purposes. Report the maximum elapsed rank time because the group result is not ready while one required rank is unfinished.
Separate a possible path from the path actually used
Capability, transport selection and memory registration are distinct claims. An active RDMA port establishes capability; a runtime trace can identify the transport selected by NCCL. Direct GPU-memory registration is an additional requirement, provided only through a supported platform integration such as DMA-BUF (Linux’s framework for sharing buffers between device drivers) or a peer-memory driver path. A selected RDMA transport alone does not prove that payloads avoided host staging.
Discovered two-node communication path
Rank zero owns one H100 on node zero and rank one owns one H100 on node one. Data traverses each node's GPU-to-host or network path and the inter-node fabric. The diagram deliberately does not assume NVLink, InfiniBand, RoCE, or GPUDirect RDMA; those capabilities must be discovered and preserved as run evidence.
A fast local kernel cannot improve a step dominated by synchronization or network transfer. Two ranks can teach collective mechanics and placement, but they cannot establish dense-node or large-cluster scaling.
Practice
After reading through this lesson, complete Advanced Lab 02 on the prepared sixteen-H100 fabric cluster. Check its placement and correctness results before running Advanced Lab 08. These two labs complete this lesson's distributed practice; GPU Performance Optimization, a training or inference specialization, and Advanced Labs 01 and 03–07 are not prerequisites for this assignment. Explain the placement and collective evidence without extrapolating from the base cluster, then return here to complete Fundamentals.
Collectives move and combine data across ranks. The bounded two-rank lab selects one GPU per node on the advanced cluster. Its path includes GPU, host interconnect, network and the remote node; use the eight-/sixteen-rank fabric labs to measure local NVLink/NVSwitch and full inter-node placement. GPUDirect RDMA and GPUDirect Storage can remove selected CPU-staging paths only when the NIC, storage, driver, topology, and software stack support them.
Lab 01: Find the CPU–GPU crossover for vector work
A GPU can execute arithmetic quickly while still losing an application comparison because transferring data and launching work take time. This lab evaluates the same expression, x * y + x, on the CPU, on tensors already stored in GPU memory, and on the GPU with input and output transfers included.
Complete source: labs/01_cpu_gpu_crossover.py
"""Compare CPU, transfer-inclusive GPU, and resident-GPU vector work."""
from __future__ import annotations
import argparse
import os
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, evidence_phase
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
return parser.parse_args()
def cpu_time_ms(x: object, y: object, iterations: int) -> float:
samples = []
for _ in range(iterations):
with evidence_phase("cpu_expression"):
start = time.perf_counter()
_ = x * y + x
samples.append((time.perf_counter() - start) * 1_000)
return statistics.median(samples)
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)
sizes = [1_024, 1_000_000]
if args.workload == "large":
sizes.append(32_000_000)
rows = []
all_correct = True
for size in sizes:
# Create the synthetic tensors used by this experiment.
x_cpu = torch.randn(size, dtype=torch.float32)
y_cpu = torch.randn(size, dtype=torch.float32)
x_gpu = x_cpu.to("cuda")
y_gpu = y_cpu.to("cuda")
resident = cuda_times_ms(
torch,
lambda x_gpu=x_gpu, y_gpu=y_gpu: x_gpu * y_gpu + x_gpu,
warmup=args.warmup,
iterations=args.iterations,
)
transfer_samples = []
if os.environ.get("COURSE_CAPTURE") == "1":
for _ in range(args.iterations):
start = time.perf_counter()
with evidence_phase("h2d_inputs"):
transferred_x = x_cpu.to("cuda")
transferred_y = y_cpu.to("cuda")
with evidence_phase("gpu_expression"):
result_gpu = transferred_x * transferred_y + transferred_x
with evidence_phase("d2h_output"):
result = result_gpu.cpu()
transfer_samples.append((time.perf_counter() - start) * 1_000)
else:
# Keep annotation machinery completely outside acceptance intervals.
for _ in range(args.iterations):
start = time.perf_counter()
transferred_x = x_cpu.to("cuda")
transferred_y = y_cpu.to("cuda")
result_gpu = transferred_x * transferred_y + transferred_x
result = result_gpu.cpu()
transfer_samples.append((time.perf_counter() - start) * 1_000)
reference = x_cpu * y_cpu + x_cpu
correct = bool(torch.allclose(result, reference, rtol=1e-5, atol=1e-6))
all_correct = all_correct and correct
rows.append(
{
"elements": size,
"cpu_median_ms": round(cpu_time_ms(x_cpu, y_cpu, args.iterations), 4),
"gpu_resident": summarize_ms(resident),
"gpu_with_transfers_median_ms": round(
statistics.median(transfer_samples), 4
),
}
)
if not all_correct:
raise SystemExit("CPU and GPU results diverged.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="01_cpu_gpu_crossover",
environment=environment,
measurements={"sizes": rows},
correctness={"allclose": True},
)
print(f"Completed crossover benchmark: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/01_cpu_gpu_crossover.sbatch --workload small
# Optional profiling
sbatch slurm/01_cpu_gpu_crossover.sbatch --workload small --profiler all
Lab 02: Compare matrix precision, error, and throughput
Reduced precision can unlock faster matrix paths, but a faster multiplication is useful only when its numerical error is acceptable. This lab compares four concrete PyTorch matmul modes on H100.
Complete source: labs/02_tensor_core_precision.py
"""Measure H100 matrix multiplication across practical training precisions."""
from __future__ import annotations
import argparse
import math
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
resolve_int_override,
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("--matrix-size", type=int, default=None)
return parser.parse_args()
def main() -> None:
# Read the experiment controls before allocating inputs.
args = parse_args()
validate_common_args(args)
size = resolve_int_override(
args.matrix_size,
2_048 if args.workload == "small" else 8_192,
option="--matrix-size",
minimum=256,
)
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.
a32 = torch.randn((size, size), device="cuda", dtype=torch.float32)
b32 = torch.randn((size, size), device="cuda", dtype=torch.float32)
torch.set_float32_matmul_precision("highest")
reference = a32 @ b32
modes = [
("fp32_highest", torch.float32, "highest"),
("tf32_high", torch.float32, "high"),
("bf16", torch.bfloat16, "high"),
("fp16", torch.float16, "high"),
]
rows = []
for name, dtype, matmul_mode in modes:
torch.set_float32_matmul_precision(matmul_mode)
a = a32.to(dtype)
b = b32.to(dtype)
def operation(a: object = a, b: object = b) -> object:
return a @ b
samples = cuda_times_ms(
torch,
operation,
warmup=args.warmup,
iterations=args.iterations,
)
output = operation().float()
median_ms = summarize_ms(samples)["median_ms"]
tflops = 2 * size**3 / (median_ms / 1_000) / 1e12
relative_l2 = (output - reference).norm() / reference.norm()
rows.append(
{
"mode": name,
"timing": summarize_ms(samples),
"achieved_tflops": round(float(tflops), 2),
"relative_l2_error": round(float(relative_l2), 7),
}
)
torch.set_float32_matmul_precision("highest")
valid_errors = all(
math.isfinite(row["relative_l2_error"]) and row["relative_l2_error"] < 0.1
for row in rows
)
if not valid_errors:
raise SystemExit(
"A precision mode produced a non-finite or unexpectedly inaccurate result."
)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="02_tensor_core_precision",
environment=environment,
measurements={"matrix_size": size, "modes": rows},
correctness={"finite_outputs_within_teaching_tolerance": True},
)
print(f"Completed precision benchmark: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/02_tensor_core_precision.sbatch --workload small
# Optional profiling
sbatch slurm/02_tensor_core_precision.sbatch --workload small --profiler all
Lab 03: Measure pageable and pinned host transfers
Pinned memory can help the GPU transfer data directly, but allocating pinned buffers and requesting a nonblocking copy do not automatically overlap transfers with computation. This lab measures four host-to-device copy combinations using a CPU timer that includes waiting for each copy to finish.
Complete source: labs/03_transfer_and_pinning.py
"""Compare pageable, pinned, blocking, and nonblocking host-to-device copies."""
from __future__ import annotations
import argparse
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 parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--size-mib", type=int, default=None)
return parser.parse_args()
def measure_copy(
torch: object,
source: object,
destination: object,
non_blocking: bool,
warmup: int,
iterations: int,
) -> float:
for _ in range(warmup):
destination.copy_(source, non_blocking=non_blocking)
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
samples = []
for _ in range(iterations):
start = time.perf_counter()
destination.copy_(source, non_blocking=non_blocking)
torch.cuda.synchronize()
samples.append((time.perf_counter() - start) * 1_000)
return statistics.median(samples)
def main() -> None:
# Read the experiment controls before allocating inputs.
args = parse_args()
validate_common_args(args)
size_mib = resolve_int_override(
args.size_mib,
64 if args.workload == "small" else 512,
option="--size-mib",
)
torch = load_torch()
# Keep random inputs repeatable across comparable runs.
seed_everything(torch, args.seed)
environment = require_course_gpu(torch)
elements = size_mib * 2**20 // 4
# Create the synthetic tensors used by this experiment.
pageable = torch.randn(elements, dtype=torch.float32)
pinned = torch.empty(elements, dtype=torch.float32, pin_memory=True)
pinned.copy_(pageable)
destination = torch.empty(elements, device="cuda", dtype=torch.float32)
rows = []
for label, source, non_blocking in (
("pageable_blocking", pageable, False),
("pageable_nonblocking", pageable, True),
("pinned_blocking", pinned, False),
("pinned_nonblocking", pinned, True),
):
median_ms = measure_copy(
torch, source, destination, non_blocking, args.warmup, args.iterations
)
rows.append(
{
"mode": label,
"median_ms": round(median_ms, 4),
"effective_gib_per_s": round(
(size_mib / 1024) / (median_ms / 1_000), 2
),
}
)
correct = bool(torch.equal(destination.cpu(), pageable))
if not correct:
raise SystemExit("Copied data did not match the source.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="03_transfer_and_pinning",
environment=environment,
measurements={"size_mib": size_mib, "modes": rows},
correctness={"exact_copy": True},
)
print(f"Completed transfer benchmark: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/03_transfer_and_pinning.sbatch --workload small
# Optional profiling
sbatch slurm/03_transfer_and_pinning.sbatch --workload small --profiler all
Lab 04: Evaluate strided access and the cost of repacking
Tensor shape does not reveal how neighboring values are arranged in memory. This lab compares a contiguous tensor, a transposed strided view, and a contiguous copy of that view while preserving each case's mathematical meaning.
Complete source: labs/04_layout_and_coalescing.py
"""Measure how a strided view changes a pointwise GPU workload."""
from __future__ import annotations
import argparse
import math
import statistics
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 break_even_reuses(
copy_ms: float, strided_ms: float, packed_ms: float
) -> int | None:
per_use_savings_ms = strided_ms - packed_ms
if per_use_savings_ms <= 0:
return None
return max(1, math.ceil(copy_ms / per_use_savings_ms))
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)
side = 4_096 if args.workload == "small" else 8_192
# Create the synthetic tensors used by this experiment.
contiguous = torch.randn((side, side), device="cuda")
strided = contiguous.transpose(0, 1)
packed = strided.contiguous()
operations = {
"contiguous": lambda: torch.sin(contiguous) * 0.5 + contiguous,
"strided_view": lambda: torch.sin(strided) * 0.5 + strided,
"repacked_contiguous": lambda: torch.sin(packed) * 0.5 + packed,
}
timing_samples = {}
for name, operation in operations.items():
timing_samples[name] = cuda_times_ms(
torch,
operation,
warmup=args.warmup,
iterations=args.iterations,
)
timing_samples["repack_copy"] = cuda_times_ms(
torch,
lambda: strided.contiguous(),
warmup=args.warmup,
iterations=args.iterations,
)
timings = {name: summarize_ms(samples) for name, samples in timing_samples.items()}
raw_medians = {
name: float(statistics.median(samples))
for name, samples in timing_samples.items()
}
reuse_count = break_even_reuses(
raw_medians["repack_copy"],
raw_medians["strided_view"],
raw_medians["repacked_contiguous"],
)
logical_tensor_bytes = contiguous.numel() * contiguous.element_size()
useful_bytes = logical_tensor_bytes * 2
useful_bandwidth = {
name: round(useful_bytes / (median_ms / 1_000) / 2**30, 4)
for name, median_ms in raw_medians.items()
}
reference = operations["strided_view"]()
correct = bool(
torch.allclose(
reference, operations["repacked_contiguous"](), rtol=1e-5, atol=1e-6
)
)
if not correct:
raise SystemExit("Strided and packed results diverged.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="04_layout_and_coalescing",
environment=environment,
measurements={
"shape": [side, side],
"dtype": str(contiguous.dtype),
"element_size_bytes": contiguous.element_size(),
"logical_tensor_bytes": logical_tensor_bytes,
"useful_bytes_per_operation": useful_bytes,
"useful_bytes_definition": "logical input bytes plus output bytes",
"layouts": {
"contiguous": {
"strides": list(contiguous.stride()),
"is_contiguous": contiguous.is_contiguous(),
},
"strided_view": {
"strides": list(strided.stride()),
"is_contiguous": strided.is_contiguous(),
},
"repacked_contiguous": {
"strides": list(packed.stride()),
"is_contiguous": packed.is_contiguous(),
},
},
"timings": timings,
"useful_bandwidth_gib_per_s": useful_bandwidth,
"repack": {
"break_even_reuses": reuse_count,
"break_even_reason": (
None if reuse_count is not None else "packed_not_faster"
),
"calculation_median_ms": raw_medians,
},
},
correctness={
"allclose": True,
"strided_view_confirmed": not strided.is_contiguous(),
"repacked_contiguous_confirmed": packed.is_contiguous(),
},
)
print(f"Completed layout benchmark: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/04_layout_and_coalescing.sbatch --workload small
# Optional profiling
sbatch slurm/04_layout_and_coalescing.sbatch --workload small --profiler all
Lab 05: Contrast memory-oriented and compute-oriented work
Roofline reasoning starts by counting work and data movement before looking at achieved speed. This lab provides two contrasting points: an elementwise vector expression and a matrix multiplication.
Complete source: labs/05_roofline_microbench.py
"""Contrast a bandwidth-oriented vector kernel with a compute-oriented GEMM."""
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)
vector_elements = 16_000_000 if args.workload == "small" else 128_000_000
matrix_size = 2_048 if args.workload == "small" else 8_192
# Create the synthetic tensors used by this experiment.
x = torch.randn(vector_elements, device="cuda")
y = torch.randn(vector_elements, device="cuda")
a = torch.randn((matrix_size, matrix_size), device="cuda", dtype=torch.bfloat16)
b = torch.randn((matrix_size, matrix_size), device="cuda", dtype=torch.bfloat16)
bandwidth_samples = cuda_times_ms(
torch,
lambda: torch.add(y, x, alpha=1.25),
warmup=args.warmup,
iterations=args.iterations,
)
compute_samples = cuda_times_ms(
torch,
lambda: a @ b,
warmup=args.warmup,
iterations=args.iterations,
)
bandwidth_ms = summarize_ms(bandwidth_samples)["median_ms"]
compute_ms = summarize_ms(compute_samples)["median_ms"]
bytes_moved = vector_elements * 4 * 3
achieved_gib_s = bytes_moved / (bandwidth_ms / 1_000) / 2**30
achieved_tflops = 2 * matrix_size**3 / (compute_ms / 1_000) / 1e12
finite = bool(
torch.isfinite(torch.add(y, x, alpha=1.25)).all()
and torch.isfinite(a @ b).all()
)
if not finite:
raise SystemExit("A roofline workload produced non-finite output.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="05_roofline_microbench",
environment=environment,
measurements={
"bandwidth_kernel": {
"timing": summarize_ms(bandwidth_samples),
"estimated_gib_per_s": round(achieved_gib_s, 2),
"arithmetic_intensity_flop_per_byte": round(2 / 12, 4),
},
"gemm": {
"timing": summarize_ms(compute_samples),
"achieved_tflops": round(achieved_tflops, 2),
},
},
correctness={"finite_outputs": True},
)
print(f"Completed roofline microbenchmark: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/05_roofline_microbench.sbatch --workload small
# Optional profiling
sbatch slurm/05_roofline_microbench.sbatch --workload small --profiler all
Lab 07: Separate submission time from device completion
GPU work is normally queued asynchronously, so a short Python call does not mean a short GPU operation. This lab compares host submission time, serial device execution, and independent-stream execution for matrix work.
Complete source: labs/07_async_streams.py
"""Contrast host enqueue time, device time, and independent CUDA streams."""
from __future__ import annotations
import argparse
import statistics
import time
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
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)
width = 1_024 if args.workload == "small" else 4_096
tensors = [
torch.randn((width, width), device="cuda", dtype=torch.bfloat16)
for _ in range(4)
]
a, b, c, d = tensors
stream_a = torch.cuda.Stream()
stream_b = torch.cuda.Stream()
def sequential() -> tuple[object, object]:
return a @ b, c @ d
def concurrent() -> tuple[object, object]:
ready = torch.cuda.Event()
ready.record()
stream_a.wait_event(ready)
stream_b.wait_event(ready)
with torch.cuda.stream(stream_a):
first = a @ b
with torch.cuda.stream(stream_b):
second = c @ d
current = torch.cuda.current_stream()
current.wait_stream(stream_a)
current.wait_stream(stream_b)
return first, second
for _ in range(args.warmup):
sequential()
concurrent()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
host_enqueue_samples = []
sequential_samples = []
concurrent_samples = []
sequential_result = None
concurrent_result = None
for _ in range(args.iterations):
host_started = time.perf_counter()
sequential_result = sequential()
host_enqueue_samples.append((time.perf_counter() - host_started) * 1_000)
torch.cuda.synchronize()
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
sequential_result = sequential()
end.record()
end.synchronize()
sequential_samples.append(float(start.elapsed_time(end)))
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)
start.record()
concurrent_result = concurrent()
end.record()
end.synchronize()
concurrent_samples.append(float(start.elapsed_time(end)))
assert sequential_result is not None and concurrent_result is not None
correct = all(
torch.allclose(expected, observed, rtol=1e-2, atol=1e-2)
for expected, observed in zip(sequential_result, concurrent_result, strict=True)
)
if not correct:
raise SystemExit("Sequential and stream-based results diverged.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="07_async_streams",
environment=environment,
measurements={
"matrix_width": width,
"host_enqueue_median_ms": round(statistics.median(host_enqueue_samples), 4),
"sequential_device": summarize_ms(sequential_samples),
"independent_streams_device": summarize_ms(concurrent_samples),
},
correctness={"allclose": True},
)
print(f"Completed asynchronous stream experiment: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/07_async_streams.sbatch --workload small
# Optional profiling
sbatch slurm/07_async_streams.sbatch --workload small --profiler all
Lab 08: Map PyTorch operations to GPU activity
One line of tensor code can trigger several framework operations and many GPU kernels. This lab profiles a small projection, normalization, and activation chain so you can relate high-level intent to execution cost. Normal execution uses the built-in PyTorch collector; external captures disable it.
Complete source: labs/08_operator_to_kernels.py
"""Map a PyTorch operator chain to CPU launches and CUDA kernel activity."""
from __future__ import annotations
import argparse
from contextlib import nullcontext
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 parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
add_common_args(parser)
parser.add_argument("--external-only", action="store_true", help="Skip the internal CUDA profiler during a separate Nsight capture.")
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)
width = 1_024 if args.workload == "small" else 4_096
batch = 64 if args.workload == "small" else 256
# Create the synthetic tensors used by this experiment.
values = torch.randn((batch, width), device="cuda", dtype=torch.bfloat16)
weight = torch.randn((width, width), device="cuda", dtype=torch.bfloat16)
bias = torch.randn((width,), device="cuda", dtype=torch.bfloat16)
def workload() -> object:
projected = values @ weight
normalized = torch.nn.functional.layer_norm(projected, (width,))
return torch.nn.functional.gelu(normalized + bias).square().mean()
for _ in range(args.warmup):
workload()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
measured_workload = annotated_operation(workload, "course_measure")
if not args.external_only:
os.environ["COURSE_PROFILE_TOOL"] = "torch"
with (nullcontext() if args.external_only else torch.profiler.profile(
activities=[
torch.profiler.ProfilerActivity.CPU,
torch.profiler.ProfilerActivity.CUDA,
],
record_shapes=True,
)) as profiler:
loss = None
for _ in range(args.iterations):
loss = measured_workload()
if profiler is not None:
profiler.step()
assert loss is not None
events = (profiler.key_averages() if profiler is not None else [])
cuda_events = [event for event in events if event.self_device_time_total > 0]
top_cuda = sorted(
cuda_events, key=lambda event: event.self_device_time_total, reverse=True
)[:10]
rows = [
{
"event": event.key,
"calls": int(event.count),
"self_cuda_time_us": round(float(event.self_device_time_total), 3),
}
for event in top_cuda
]
finite = bool(torch.isfinite(loss).item())
if not finite or (not args.external_only and not rows):
raise SystemExit("Profiler did not capture finite CUDA work.")
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="08_operator_to_kernels",
environment=environment,
measurements={
"shape": [batch, width],
"unique_profile_events": len(events),
"cuda_events_with_device_time": len(cuda_events),
"top_cuda_events": rows,
},
correctness={"finite_loss": True, "captured_cuda_events_or_external_capture": bool(rows) or args.external_only},
)
if profiler is not None:
print(events.table(sort_by="self_cuda_time_total", row_limit=10))
print(f"Completed operator-to-kernel map: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/08_operator_to_kernels.sbatch --workload small
# Optional profiling
sbatch slurm/08_operator_to_kernels.sbatch --workload small --profiler all
Lab 09: Sweep logical work per Triton program
Launch geometry determines how a problem is divided among GPU programs and how much work remains in the final partial program. This Python/Triton lab sweeps logical elements per program while holding four warps per program fixed.
"""Write and sweep a small Python Triton kernel to expose launch geometry."""
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
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 scale_kernel(
source,
target,
element_count,
scale,
BLOCK_SIZE: tl.constexpr,
):
program = tl.program_id(axis=0)
offsets = program * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offsets < element_count
values = tl.load(source + offsets, mask=mask)
tl.store(target + offsets, values * scale, mask=mask)
else:
scale_kernel = None
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)
if triton is None or scale_kernel is None:
raise SystemExit(
"This lab needs the Triton package supplied with a compatible "
"Linux CUDA PyTorch environment."
)
element_count = 8_000_003 if args.workload == "small" else 64_000_003
# Create the synthetic tensors used by this experiment.
source = torch.randn(element_count, device="cuda", dtype=torch.float32)
target = torch.empty_like(source)
reference = source * 1.25
measurements: dict[str, object] = {"elements": element_count, "sweeps": {}}
correctness: dict[str, bool] = {}
warps_per_program = 4
for block_size in (128, 256, 512):
grid = (triton.cdiv(element_count, block_size),)
def launch() -> None:
scale_kernel[grid](
source,
target,
element_count,
1.25,
BLOCK_SIZE=block_size,
num_warps=warps_per_program,
)
samples = cuda_times_ms(
torch,
launch,
warmup=args.warmup,
iterations=args.iterations,
)
launch()
# Wait for queued GPU work to finish at this measurement boundary.
torch.cuda.synchronize()
correct = bool(torch.equal(target, reference))
if not correct:
raise SystemExit(f"BLOCK_SIZE={block_size} produced an incorrect result.")
summary = summarize_ms(samples)
median_seconds = summary["median_ms"] / 1_000
logical_bytes = 2 * element_count * source.element_size()
measurements["sweeps"][str(block_size)] = {
"programs": triton.cdiv(element_count, block_size),
"elements_per_program": block_size,
"covered_element_lanes": triton.cdiv(element_count, block_size)
* block_size,
"masked_tail_elements": (
triton.cdiv(element_count, block_size) * block_size - element_count
),
"warps_per_program": warps_per_program,
"cuda_threads_per_program": warps_per_program * 32,
"time": summary,
"logical_gib_per_second": round(logical_bytes / median_seconds / 2**30, 3),
}
correctness[f"block_{block_size}_exact"] = True
# Save the actual measurements together with their correctness checks.
target_path = write_result(
args,
lab_id="09_triton_launch_geometry",
environment=environment,
measurements=measurements,
correctness=correctness,
)
print(f"Completed Triton launch-geometry sweep: {target_path}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/09_triton_launch_geometry.sbatch --workload small
# Optional profiling
sbatch slurm/09_triton_launch_geometry.sbatch --workload small --profiler all
Lab 10: Identify the software layer behind GPU execution
Driver, CUDA runtime, compiler toolkit, and PyTorch versions answer different questions. This lab records them separately and launches a small framework operation on H100.
Complete source: labs/10_compatibility_stack.py
"""Capture the framework, runtime, driver, compiler, and H100 compatibility stack."""
from __future__ import annotations
import argparse
import re
import shutil
import subprocess
from common import (
add_common_args,
load_torch,
require_course_gpu,
validate_common_args,
write_result,
)
def first_line(command: list[str]) -> str | None:
"""Return a bounded first output line for a public version command."""
if shutil.which(command[0]) is None:
return None
result = subprocess.run(
command, capture_output=True, text=True, timeout=15, check=False
)
text = result.stdout.strip() or result.stderr.strip()
return text.splitlines()[0][:240] if text else None
def nvcc_release() -> str | None:
"""Return nvcc's release/build line instead of its generic banner."""
if shutil.which("nvcc") is None:
return None
result = subprocess.run(
["nvcc", "--version"], capture_output=True, text=True, timeout=15, check=False
)
for line in (result.stdout + result.stderr).splitlines():
if re.search(r"\brelease\s+\d", line, flags=re.IGNORECASE):
return line.strip()[:240]
return None
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)
versions = {
"framework": torch.__version__,
"framework_cuda_runtime": torch.version.cuda,
"driver_query": first_line(
["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"]
),
"cuda_compiler_release": nvcc_release(),
"framework_compiled_arches": list(torch.cuda.get_arch_list()),
}
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="10_compatibility_stack",
environment=environment,
measurements={
"layers": versions,
"framework_kernel_execution": "passed",
"ptx_or_sass_image_path": (
"not-proven-by-this-lab; inspect a retained profiler trace or "
"cuobjdump output before claiming native SASS versus driver JIT"
),
},
correctness={
"h100_contract": True,
"framework_kernel_executed": bool(torch.ones(1, device="cuda").item() == 1),
},
)
print(f"Wrote compatibility evidence: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/10_compatibility_stack.sbatch --workload small
# Optional profiling
sbatch slurm/10_compatibility_stack.sbatch --workload small --profiler all
Lab 11: Separate lane utilization from grid-tail behavior
Uneven work can waste execution capacity at more than one level. This lab deliberately separates a Python model of loop work within warps from an H100 probe of partial grid waves.
Complete source: labs/11_scheduler_tail.py
"""Model lane utilization, then measure Triton grid tails with estimated residency."""
from __future__ import annotations
import argparse
from common import (
add_common_args,
cuda_times_ms,
load_torch,
require_course_gpu,
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 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:
tail_probe = None
def wave_model(blocks: int, slots: int) -> dict[str, float | int]:
"""Return full waves and final-wave utilization for known resident slots."""
if blocks < 1 or slots < 1:
raise ValueError("blocks and slots must be positive")
waves = (blocks + slots - 1) // slots
tail_blocks = blocks - (waves - 1) * slots
return {
"blocks": blocks,
"waves": waves,
"tail_blocks": tail_blocks,
"tail_utilization": round(tail_blocks / slots, 4),
}
def lane_work_model(iterations: list[int]) -> dict[str, float | int]:
"""Model a common loop body with per-lane exit; not a GPU measurement.
One warp issues until its longest-running lane exits. Branch overhead,
memory latency, compiler predication, and grouping cost are not modeled.
Distinct branch bodies require summing paths, not taking this maximum.
"""
if not iterations or any(value < 0 for value in iterations) or not sum(iterations):
raise ValueError("lane work must be nonnegative with some useful work")
issued = sum(max(iterations[i : i + 32]) for i in range(0, len(iterations), 32))
useful = sum(iterations)
return {
"warps": (len(iterations) + 31) // 32,
"useful_lane_iterations": useful,
"issued_warp_iterations": issued,
"modeled_lane_utilization": useful / (32 * issued),
}
def tail_reference(torch: object, blocks: int, work: int) -> object:
"""Evaluate the kernel formula for every program 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 tail_probe is None:
raise SystemExit(
"This lab requires the Triton package from the course environment."
)
properties = torch.cuda.get_device_properties(0)
mixed_lanes = lane_work_model([20, 4] * 32)
grouped_lanes = lane_work_model([20] * 32 + [4] * 32)
num_warps = 16
threads = num_warps * 32
work = 256 if args.workload == "small" else 2_048
probe_output = torch.empty(1, device="cuda", dtype=torch.float32)
compiled = tail_probe[(1,)](probe_output, work=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
limits = [properties.max_threads_per_multi_processor // threads]
register_capacity = int(getattr(properties, "regs_per_multiprocessor", 0))
if registers and register_capacity:
limits.append(register_capacity // (registers * threads))
shared_capacity = int(getattr(properties, "shared_memory_per_multiprocessor", 0))
if shared_bytes and shared_capacity:
limits.append(shared_capacity // shared_bytes)
architectural_block_limit = int(
getattr(properties, "max_blocks_per_multi_processor", 0)
)
if architectural_block_limit:
limits.append(architectural_block_limit)
blocks_per_sm = min(limit for limit in limits if limit > 0)
resident_slots = properties.multi_processor_count * blocks_per_sm
output = torch.empty(2 * resident_slots + 1, device="cuda", dtype=torch.float32)
cases = []
all_cases_correct = True
for blocks in (
resident_slots,
resident_slots + 1,
2 * resident_slots,
2 * resident_slots + 1,
):
def operation(blocks: int = blocks) -> None:
tail_probe[(blocks,)](output, work=work, num_warps=num_warps)
timing = summarize_ms(
cuda_times_ms(
torch,
operation,
warmup=args.warmup,
iterations=args.iterations,
)
)
output.fill_(float("nan"))
operation()
torch.cuda.synchronize()
observed = output[:blocks].cpu()
expected = tail_reference(torch, blocks, work)
finite = bool(torch.isfinite(observed).all())
correct = bool(
finite and torch.allclose(observed, expected, rtol=1e-5, atol=1e-6)
)
all_cases_correct = all_cases_correct and correct
if not correct:
raise SystemExit(
f"Tail probe failed sentinel/reference validation for {blocks=}"
)
cases.append(
{
"model": wave_model(blocks, resident_slots),
"timing": timing,
"max_absolute_error": float((observed - expected).abs().max()),
}
)
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="11_scheduler_tail",
environment=environment,
measurements={
"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": cases,
"lane_work_model": {
"mixed": mixed_lanes,
"grouped": grouped_lanes,
"scope": (
"analytical common-loop model, not measured branch efficiency; "
"tail_probe has uniform work; Custom Kernels Lab 06 measures "
"real divergent/grouped kernels including packing cost"
),
},
"profiler_confirmation_required": True,
},
correctness={
"all_grid_programs_completed_and_match_reference": all_cases_correct,
"lane_comparison_preserves_useful_work": mixed_lanes[
"useful_lane_iterations"
]
== grouped_lanes["useful_lane_iterations"],
},
)
print(f"Wrote scheduler-tail evidence: {target}")
if __name__ == "__main__":
annotated_operation(main, "lab_workload")()
# Normal execution
sbatch slurm/11_scheduler_tail.sbatch --workload small
# Optional profiling
sbatch slurm/11_scheduler_tail.sbatch --workload small --profiler all
Lab 12: Read GPU health and sharing signals safely
A slow result may coincide with thermal, power, error, or sharing conditions that deserve investigation. This lab collects a bounded read-only snapshot and states what cannot be inferred from it.
Complete source: labs/12_read_only_health.py
"""Collect a bounded read-only H100 sharing and health snapshot."""
from __future__ import annotations
import argparse
import csv
import io
import shutil
import subprocess
from common import (
add_common_args,
load_torch,
require_course_gpu,
validate_common_args,
write_result,
)
from course_evidence import gpu_family
FIELDS = (
"name",
"driver_version",
"temperature.gpu",
"power.draw",
"clocks.sm",
"pstate",
"clocks_throttle_reasons.active",
"ecc.errors.uncorrected.volatile.total",
"retired_pages.pending",
"mig.mode.current",
"compute_mode",
)
def query_nvidia_smi() -> dict[str, str]:
if shutil.which("nvidia-smi") is None:
raise SystemExit("nvidia-smi is required for the read-only health snapshot")
result = subprocess.run(
[
"nvidia-smi",
f"--query-gpu={','.join(FIELDS)}",
"--format=csv,noheader,nounits",
],
capture_output=True,
text=True,
timeout=20,
check=False,
)
if result.returncode:
raise SystemExit(f"read-only nvidia-smi query failed: {result.stderr.strip()}")
rows = list(csv.reader(io.StringIO(result.stdout)))
if len(rows) != 1 or len(rows[0]) != len(FIELDS):
raise SystemExit("expected exactly one allocated GPU from nvidia-smi")
return dict(zip(FIELDS, (value.strip() for value in rows[0]), strict=True))
def describe_mig_mode(value: str) -> str:
"""Report only recognized management state; absence is not device proof."""
return {
"enabled": "MIG enabled",
"disabled": "MIG disabled; verify allocated-device identity in preflight",
}.get(value.strip().lower(), "MIG mode unavailable or unrecognized")
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)
snapshot = query_nvidia_smi()
sharing = {
"full_or_mig": describe_mig_mode(snapshot["mig.mode.current"]),
"mps": "not inferable from a non-intervening per-process query",
"time_slicing": "scheduler policy evidence required",
}
# Save the actual measurements together with their correctness checks.
target = write_result(
args,
lab_id="12_read_only_health",
environment=environment,
measurements={
"snapshot": snapshot,
"sharing_evidence": sharing,
"xid_history": "requires a separately authorized, sanitized system-event source",
"dcgm_health": "run the documented read-only cluster procedure when DCGM access is available",
"configuration_changed": False,
},
correctness={
"single_full_gpu": gpu_family(snapshot["name"])
== environment["gpu_family"],
"read_only": True,
},
)
print(f"Wrote read-only health evidence: {target}")
if __name__ == "__main__":
main()
# Normal execution
sbatch slurm/12_read_only_health.sbatch --workload small
# Optional profiling
sbatch slurm/12_read_only_health.sbatch --workload small --profiler all
Follow the lessons in order: CPU/GPU cooperation and timing, the software and execution stack, memory and occupancy, then access patterns, precision, roofline and read-only health. Lab numbers identify files, not execution order.
After Lesson 3, explain the CPU-to-device path and a trustworthy timer.
After Lesson 7, distinguish memory layout, active lanes and block residency.
After Lesson 10, derive a roofline bound before comparing measurements.
Before the first lab
Use one full, non-MIG H100 per local lab. A qualified advanced cluster can also provide these one-GPU allocations. Follow the Lab Guide, check Versions and environment, then run from this course directory. Complete Lab 10 successfully before submitting Lab 01:
sbatch slurm/10_compatibility_stack.sbatch --workload small
sbatch slurm/01_cpu_gpu_crossover.sbatch --workload small
For Lab 01 diagnostics, add --profiler all to run Systems followed by Compute. Check both stage statuses and report paths in the exact job's result.json; profiled timings are diagnostic and do not replace the normal benchmark.
After reading through Lesson 12, complete Advanced Lab 02, check its placement and correctness results, then run Advanced Lab 08. This assignment requires shared preparation and the advanced course's qualified sixteen-H100 fabric; two one-GPU TCP workers do not qualify that path. Optimization, a training or inference specialization, and Advanced Labs 01 and 03–07 are not prerequisites for these two labs. Return here afterward to complete Fundamentals.
Completion
Complete the local labs with their correctness checks. Explain a measured result using timing, hardware and health evidence, keeping observation, inference and unverified hypothesis separate.
All 11 practical labs completed both small and large profiles (22 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.
Component
Course target
Evidence status
Python
3.12
Installed locally; target-cluster parity pending
PyTorch
2.14.0 manifest authority
Clean Linux/H100 install and qualification pending; no fallback approved
CUDA runtime
PyTorch-qualified H100 runtime
Target activation pending
GPU
One full non-MIG NVIDIA H100, compute capability 9.0
Live validation pending
Slurm
Site-supported version
Live validation pending
Do not infer driver compatibility from a toolkit version alone. Record the actual framework runtime, driver, GPU, and executed kernel path with results.
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.
Run from the gpu-fundamentals course root with the prepared runtime described in VERSIONS.md; launchers restore it automatically. Keep each Slurm output file and JSON result private; never overwrite an earlier run. Share only a sanitized summary that follows evidence-security.md.
Complete shared software preparation in the Lab Guide. Review its completion summary and follow the Lab Guide’s guidance for any failures or hardware skips before submitting. Keep runtime evidence in those private result directories.
This runbook is a complete platform-qualification checklist, not the teaching order. Follow the course for the learning route. Run Lab 10 before the first local experiment; later gates check the additional mechanisms you use.
Check the local runtime
sbatch slurm/10_compatibility_stack.sbatch --workload small
Confirm successful completion and the recorded device/runtime before continuing.
Isolate one-GPU fundamentals
Submit in this order:
sbatch slurm/01_cpu_gpu_crossover.sbatch --workload small
sbatch slurm/02_tensor_core_precision.sbatch --workload small
sbatch slurm/03_transfer_and_pinning.sbatch --workload small
sbatch slurm/04_layout_and_coalescing.sbatch --workload small
sbatch slurm/05_roofline_microbench.sbatch --workload small
sbatch slurm/07_async_streams.sbatch --workload small
sbatch slurm/08_operator_to_kernels.sbatch --workload small
sbatch slurm/09_triton_launch_geometry.sbatch --workload small
For each job, write the prediction first, require the lab's correctness result, and compare distributions rather than one sample. For Lab 04, preserve the logical layouts and strides, raw operation distributions, bandwidth estimates based on logical input/output bytes, repack-copy cost, and computed reuse break-even. A result where the packed operation is not faster is valid evidence and must report that no finite break-even exists.
Broaden only after smoke passes
Repeat selected labs with their supported small or large profiles. Change one factor at a time. A changed dtype, shape, rank count, power state, process placement, or software version starts a new comparison series.
Compatibility, scheduling, and read-only health
sbatch slurm/11_scheduler_tail.sbatch --workload small
sbatch slurm/12_read_only_health.sbatch --workload small
Record the wheel/runtime/driver/toolkit roles separately. The lane-work model preserves total useful work; the grid-tail probe preserves work per program but varies total program count. Keep that distinction and the stated SM count with the result. Read-only health evidence must not change clocks, sharing modes, or error state. Missing operational fields mean unavailable evidence. Review health changes alongside timing rather than attributing a slow run to one isolated counter.
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
Lab 11: distinguish inactive lanes from idle block slots
Objective: explain two different reasons why a GPU can have unused capacity. The scheduler lab contains an executable Python lane-work model and a separate measured H100 grid-tail experiment. They answer different questions; neither substitutes for the other.
Predict the lane-work model
Imagine 64 tasks. Half repeat the same loop body 20 times; half repeat it four times. The useful work is 32 × 20 + 32 × 4 = 768 lane-iterations in either ordering. A warp can stop issuing this common loop only after the lane with the most iterations exits. With alternating long/short lanes, both warps issue 20 iterations. That provides 2 × 20 × 32 = 1280 lane-opportunities, of which 768 are useful: 60 percent modeled utilization. With one all-long warp and one all-short warp, the warp issue counts are 20 and four: 768 opportunities, all useful.
Ordering
Useful lane-iterations
Warp loop iterations
Modeled utilization
Alternating 20,4 across two warps
768
40
60%
One 20-iteration warp, one 4-iteration warp
768
24
100%
These are exact answers under the stated model, not measured H100 speedups. This model applies to a common loop with per-lane exits. Two different branch bodies generally require issuing each path under its own mask: their costs cannot simply be replaced by the maximum loop length. Compilers can also predicate short branches. Independent thread scheduling does not eliminate these instruction and active-mask effects. See the official control-flow discussion.
Run and interpret the GPU experiment
Predict the values above. After completing Lesson 6's occupancy explanation, run Lab 11 through the course single-GPU launcher as shown in the smoke runbook.
Read lane_work_model.mixed and lane_work_model.grouped. They must have equal useful work; only modeled issue cost changes.
Separately inspect cases. The Triton GPU kernel performs uniform work per program while grid size crosses one and two estimated resident-slot boundaries. CUDA events measure these kernels, not the lane-work model.
Compare a full wave with one additional block. A nearly empty final wave can increase duration even though the work inside every block is uniform. Check all-program reference correctness before interpreting timing.
Confirm residency with compiler resource output and Nsight. The simple resource calculation is a planning estimate: register allocation granularity, achieved residency and scheduling can differ from the estimate.
Retain the modeled utilization, estimated resident slots, grid sizes, correct output checks, and timing distributions in separate columns. Do not label the model as branch efficiency or use the timing ratio as a measured divergence penalty. In the Custom CUDA course, Lab 06 supplies real divergent and grouped kernels, independent references, grouping-only timing, and end-to-end timing including pack/scatter; it is an optional later follow-on, not a Fundamentals prerequisite or a copied runtime dependency.
Review and failure analysis
In a later experiment that actually groups GPU work, improved modeled utilization can coexist with worse end-to-end time if grouping adds memory traffic or leaves a few expensive blocks at the end. Fundamentals Lab 11 does not measure grouping cost. The model intentionally excludes grouping cost, memory stalls, compiler choices and block scheduling. It supports a hypothesis, not an optimization decision. If a tiny grid-tail difference disappears inside measurement variance, report that result rather than manufacturing a cliff.
Review answer: improve lane similarity for the modeled loop; improve work distribution or grid coverage for a tail wave. Raising occupancy alone proves neither remedy. Use the diagram of SIMT masks for the first question and the execution/tail diagram for the second.
Benchmark worksheet
Record the lab ID, run ID, public software versions, GPU family, compute capability, profile, shapes, dtypes, seed, warm-up, repetitions, correctness, raw sample summary, memory, profiler evidence, observation, inference, and keep/reject decision. Keep raw artifacts private.
Apply the lab's declared correctness criterion. For elementwise comparisons without a different declared criterion, use FP32 rtol=1e-5, atol=1e-6 and FP16/BF16 rtol=1e-2, atol=1e-2. Broader teaching checks or finite-value checks support only their stated diagnostic scope; they do not establish production numerical equivalence.
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.
Field
Baseline
Candidate / observation
Date and random course run ID (keep artifact location private)
To record
To record
Lab, source/commit identity, exact arguments, single change
To record
To record
H100 SKU, node/rank count, MIG state, topology class (no asset IDs)
To record
To record
Approved environment lock or immutable image; driver/CUDA/framework/NCCL/Slurm versions
Collective message size, algorithm/bus bandwidth, slowest-rank time
To record
To 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.
Evidence and privacy
The course source is designed to be public, but runtime evidence is sensitive by default. Slurm output, PyTorch traces, and benchmark results can contain infrastructure identifiers, filesystem paths, command lines, workload shapes, or environment details even when the labs use synthetic data.
Collect privately
Use synthetic or explicitly public inputs. Do not benchmark customer data, credentials, proprietary inputs, or regulated data.
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.
Keep results/, traces, and Slurm output in storage that only the learner or approved course reviewers can read.
Do not pass credentials on command lines or enable shell tracing. Remove unrelated secret-bearing environment variables according to site policy.
Never commit generated evidence. The course .gitignore 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, credentials, and customer or proprietary data;
raw traces, raw logs, and command lines that expose cluster details.
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. Redact by creating a new file; do not overwrite the private original.
Course-specific safeguards
Lab JSON uses a random run ID instead of a Slurm job ID.
New result files are created exclusively with owner-only permissions.
The normal course validator performs static validation and does not execute CUDA labs or Slurm launchers.
The portable tree rejects generated caches, and launchers disable Python bytecode creation before Python starts.
Live site policy remains authoritative. If an evidence-collection command is not approved, record a sanitized blocker and ask the cluster owner rather than weakening permissions.
Where to Go Next
These optional reading directions combine recent developments with established advanced concepts; they are not additional lessons or lab requirements. The course remains H100-based. Check the linked release and hardware requirements before experimenting in a separate environment: current documentation does not mean that a feature is qualified in this course. Start with the architecture comparison, then choose a direction that matches the systems you expect to use.
Choose one direction and apply the course’s reasoning to a new example. Keep its stated scope and qualification limits in your comparison.
Blackwell architecture and portable performance reasoning
Blackwell is a newer NVIDIA GPU architecture that retains the CUDA execution model but changes resource limits, memory capacities and supported operations. Comparing its tuning guide with Hopper's helps you distinguish durable ideas, such as locality and latency hiding, from chip-specific tuning decisions. Investigate: Which assumptions in an H100 occupancy or roofline calculation must be replaced when moving to a particular Blackwell GPU? Scope: Newer-hardware comparison, not an H100 feature upgrade; different Blackwell compute capabilities do not have identical resources. Read NVIDIA's Blackwell tuning guide.
Vera Rubin and rack-scale computing
NVIDIA's Vera Rubin platform combines CPUs, GPUs and interconnects into a larger computing system. Its NVLink 6 fabric connects GPUs within a scale-up system, while network technologies connect systems at scale-out. This extends the course's topology vocabulary beyond reasoning about one GPU in isolation. Investigate: Which communications stay inside the scale-up fabric, and which cross a network boundary? Scope: Current vendor platform direction; hardware, deployment availability and topology must be checked separately. Two independent H100 nodes do not reproduce this platform. Explore NVIDIA's Vera Rubin platform.
Unified Memory, HMM and hardware coherence
Unified Memory provides a shared programming view of memory accessible to CPUs and GPUs. Heterogeneous Memory Management (HMM) is Linux support for coordinating CPU and device access to process memory, allowing supported GPUs to use ordinary system allocations. Hardware coherence, available on systems such as Grace Hopper, uses hardware to keep CPU/GPU views of shared data consistent under the platform's memory rules. A page is a fixed-size region managed by the virtual-memory system. Page migration moves a page's physical backing between memory locations; remote access uses data where it remains. These mechanisms have different costs. A common address space does not make every access equally fast: placement and the interconnect still matter. Investigate: How would you distinguish a local GPU-memory access, a remote access and a page migration? Scope: Established concept with evolving platform support. HMM requires an appropriate OS/driver configuration; an ordinary H100 host is not a Grace Hopper system. Study CUDA Unified Memory.
CUDA Python 1.0 and explicit runtime control
CUDA Python exposes CUDA facilities through Python. Its 1.0 release develops the lower-level path beneath tensor frameworks: applications can explicitly manage devices, streams, memory and graphs through components such as cuda.core. Understanding this layer helps explain which responsibilities PyTorch normally handles for you. Investigate: Who owns a device allocation and its lifetime when two Python libraries share it? Scope: Recent software direction, described in NVIDIA's May 26, 2026 CUDA 13.3 announcement. Package, toolkit and driver requirements still need checking; no course dependency changes are required. Read the CUDA Python release overview.
GPU confidential computing and attestation
Confidential computing aims to protect data while it is being processed, not just while stored or transmitted. Attestation checks evidence about the device's identity and security state before a workload trusts it. This adds a security boundary to the course's operational-health model: a healthy GPU and a trusted execution environment are different claims. Investigate: What does successful GPU attestation establish, and what application or host risks remain outside that evidence? Scope: Established advanced security topic with evolving tooling. Supported Hopper configurations exist, but require a qualified confidential-computing platform; do not change cluster security modes for this reading exercise. Study NVIDIA GPU attestation.
Glossary
Arithmetic intensity
Floating-point operations divided by bytes transferred at a specified memory level. State whether bytes are estimated from the algorithm or measured by a profiler.
BF16
Bfloat16, a 16-bit floating-point format with a wide exponent range and fewer significand bits than FP32.
Block
A group of CUDA threads scheduled together on one streaming multiprocessor; a block does not split across SMs.
Coalescing
Combining warp memory requests into efficient transactions.
Collective
A coordinated communication operation, such as all-reduce, involving every rank in a specified group.
Compute capability 9.0
The H100 hardware feature level and resource limits used by these courses; distinct from the CUDA Toolkit version.
Contiguous layout
A tensor layout whose values follow its declared contiguous memory order, without gaps or rearranged strides.
CPU / host
The general-purpose processor and its execution environment, responsible for program control and for submitting GPU work.
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.
CTA
Cooperative thread array, CUDA's architectural term for a thread block.
CUDA Core
A general arithmetic execution resource used by CUDA workloads; it is not a synonym for a thread.
CUDA event
A marker recorded in a CUDA stream to track completion or establish dependencies; timing-enabled events also record timestamps for elapsed-time measurement.
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 data from GPU memory to CPU-accessible memory.
DCGM
NVIDIA Data Center GPU Manager; provides GPU health and telemetry facilities.
Divergence
A warp executing different control-flow paths for different active lanes, usually serializing the paths.
DMA
Direct memory access; transfer hardware moves data without CPU instructions copying each byte.
Dot product
The sum of products of matching entries in two sequences; matrix multiplication combines one row and one column this way.
ECC
Error-correcting code; distinguishes corrected memory errors from errors that could not be corrected.
ECN / CNP / PFC
Explicit congestion notification / congestion notification packet / priority flow control; respectively, congestion marking, sender notification and selected-priority pausing mechanisms used in coordinated network designs.
Eligible warp
A resident warp whose next instruction is ready to issue; residency alone does not make a warp eligible.
Fabric
The connected links and switches carrying traffic among endpoints.
FLOP / FLOP/s
Floating-point operation / floating-point operations per second; a work count and a rate, respectively.
FMA
Fused multiply-add, a × b + c with one final rounding; conventionally counted as two FLOPs.
FP16
16-bit floating point with a smaller exponent range than BF16; numerical range and rounding affect which workloads can use it safely.
FP32
32-bit floating point, commonly used for parameters, accumulations and numerical references; storage dtype alone does not identify the arithmetic path.
FP64
64-bit floating point, offering greater precision and range at a different storage and hardware-throughput cost.
FP8
Eight-bit floating-point formats whose range and precision depend on the selected format and scaling recipe.
GEMM
General matrix multiplication, often expressed as C = alpha × A × B + beta × C.
Global memory
CUDA device-wide address space for data accessible to threads across blocks, normally backed by HBM and serviced through caches.
GPC
Graphics processing cluster, also called GPU processing cluster in the Hopper architecture description; a top-level hardware group containing TPCs, with enabled counts varying by H100 product.
GPU / device
A parallel processor that executes supported kernels; it accelerates suitable workloads, not arbitrary CPU instructions automatically.
GPU-resident tensor
A tensor whose data is stored in GPU memory, independently of whether a kernel is currently using it.
GPUDirect RDMA
Supported direct access between a network adapter and GPU memory, avoiding a host payload-staging buffer.
Grid
All thread blocks launched for one kernel invocation.
H2D
Host-to-device transfer; copying data from CPU-accessible memory to GPU memory.
HBM
High-bandwidth memory, the device memory that stores tensors, temporary buffers and other device allocations.
HCA
Host channel adapter, an RDMA endpoint adapter term; its device name is distinct from an IP-interface name.
ILP
Instruction-level parallelism; independent instructions within one thread that can make progress without waiting on one another’s results.
InfiniBand
A switched network architecture supporting RDMA with compatible adapters, links and a subnet manager.
Issued warp
An eligible warp selected by a scheduler to issue an instruction in the current scheduling opportunity.
JIT
Just-in-time compilation, such as translating compatible PTX when loading GPU code.
Kernel
A function launched for parallel execution on the GPU.
L1 / L2 cache
Hardware-managed storage that can serve repeated accesses with less traffic to lower memory levels; L1 is local to an SM and L2 is shared across SMs.
Lane
A thread position within a warp, numbered 0–31; positions without a thread in a partial warp are unused.
Latency hiding
Issuing eligible work from another resident warp while a warp waits for a dependency.
Layout
The mapping from logical tensor indices to storage addresses.
Local memory
Thread-private CUDA address space normally backed by device memory; register spills can create local-memory traffic.
MIG
Multi-Instance GPU, hardware partitioning that exposes isolated GPU instances.
MPS
Multi-Process Service, NVIDIA software that coordinates work from multiple CUDA processes.
NCCL
NVIDIA Collective Communications Library, software implementing GPU collectives and point-to-point communication using available topology-aware paths.
NIC
Network interface controller connecting a host to a network.
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.
NUMA
Non-uniform memory access; host-memory cost depends on CPU/socket locality.
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; annotation API for named markers and ranges. Nsight Systems displays these labels; Nsight Compute can use ranges to select GPU work. Annotations neither synchronize nor measure GPU execution by themselves.
Occupancy
Active (resident) warps per SM relative to its maximum supported active warps. Theoretical occupancy is a resource limit; achieved occupancy is measured during execution.
Pinned memory
Page-locked host memory that enables efficient DMA and is required for truly asynchronous host-to-device copies in common CUDA paths.
PTX
Parallel Thread Execution, NVIDIA’s virtual instruction-set representation that a compatible driver can translate.
PyTorch Profiler
The framework profiler that attributes CPU and CUDA activity, calls, shapes, memory, and stacks to PyTorch operators.
Queue pair (QP)
Associated send and receive work queues used by an RDMA adapter.
Rank
The identity of one participating process within a distributed process group.
RDMA
Remote direct memory access using supported network hardware and registered memory; not assumed by this course.
Register
Fast storage holding values used by a thread during kernel execution.
Registration
Establishing the memory region, permissions and mapping that an adapter may use for data transfer.
Relative L2 error
The Euclidean norm of an output error divided by the reference norm, with a declared convention for a zero reference; distinct from an L2 hardware cache.
Resident thread
A thread assigned to an SM that keeps its register values and tracks its progress through the kernel. It remains resident while its warp waits for data or its next turn to execute.
RoCE
RDMA over Converged Ethernet; RoCEv2 carries its transport over UDP/IP on a qualified Ethernet fabric.
Roofline model
A model that relates attainable work rate to arithmetic intensity, a bandwidth ceiling, and a compute ceiling.
Row remapping / page retirement
GPU memory reliability mechanisms and associated status; supported fields depend on hardware and driver. Record the status through read-only checks; do not attempt repairs in a lab.
SASS
The machine instructions executed by a specific NVIDIA GPU architecture.
Shared memory
Explicitly managed, block-scoped on-chip storage; on H100 its capacity shares a physical resource with L1, so it is not an extra serial cache level.
SIMT
Single-instruction, multiple-thread execution in which a warp issues an instruction for active lanes.
SM
Streaming multiprocessor, the GPU unit that schedules warps and contains registers, shared memory, and execution resources.
SMSP
Streaming multiprocessor subpartition; one of four H100 SM scheduling and execution subdivisions, with a warp scheduler, dispatch resources, register-file partition and associated execution resources.
Stride
The step in stored elements associated with increasing an index by one along a tensor axis.
Subnet manager
The operator-owned InfiniBand service responsible for discovering and configuring subnet paths.
Synchronization
A dependency or wait that ensures required work has completed before dependent work proceeds.
Tail wave
A final partially filled scheduling wave that leaves resources idle.
Tensor
An array of numbers with a shape, data type and device placement.
Tensor Core
Specialized matrix-multiply-accumulate hardware used only when an eligible operation, dtype, shape, and software kernel select it.
Tensor view
A tensor interpretation that shares underlying storage with another tensor instead of copying its values.
TF32
TensorFloat-32, a Tensor Core compute mode for selected FP32 matrix operations, not a tensor storage dtype.
Thread-block cluster
A group of thread blocks guaranteed to be co-scheduled on one GPC, supporting cluster synchronization and distributed shared memory on Hopper.
Tile
A rectangular piece of a matrix processed as a unit of work; its elements need not map one-to-one to threads.
TPC
Texture processing cluster; an H100 hardware group containing two SMs within a GPC.
Triton program
One instance of a Python-authored Triton kernel launched over a grid; it typically processes a tile of logical tensor elements and uses a mask for any out-of-range tail.
Warm-up
Representative untimed work before measurement to reduce initialization and other first-run effects.
Warp
32 CUDA threads scheduled as an execution group on current NVIDIA GPUs covered by this course.
Xid
An NVIDIA driver error classification that guides investigation; the code alone is not a diagnosis.