Custom CUDA Kernels for GPU Optimization

Estimated guided hours: 36

Course overview

Custom CUDA Kernels teaches when writing a kernel is justified and how to prove its correctness, safety and end-to-end value. Build CUDA C++20 implementations, inspect their hardware behavior and compare them with mature library operations before deciding which implementation to keep.

Read GPU Performance Tools before practical work. Complete GPU Fundamentals and GPU Performance Optimization first, or bring their execution, memory and profiling skills, together with basic C++ knowledge. Neither LLM specialization is a prerequisite. The course progresses from a correct vector kernel through memory, fusion and reduction techniques to a measured optimization decision.

All executable labs use one full H100; even Hopper thread-block clusters operate within one GPU. Optional extensions retain their own prerequisites. Start with Lab Preparation in the shared Lab Guide. Read the single setup command's completion summary, then follow the course's readiness checks and lab order. Setup builds software; GPU jobs check correctness.

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

How to use this course

Learn

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

Practice

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

Review

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

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

Optional further study

  • CUDA Tile C++ lesson

1. Custom kernel decision making

Objective

Test framework, compiler, cuBLAS, cuDNN, CUB/CCCL, and CUTLASS options before committing to handwritten CUDA.

How it works

What a GPU kernel is

A kernel is a function whose device code executes across many GPU threads. The host application launches that function with a grid and block configuration; each thread identifies its own part of the work. For vector addition, one thread might calculate one output element, while a matrix-multiplication kernel assigns cooperating threads to tiles. A kernel is not the whole application, a GPU core, or a Python function that automatically moved to another processor.

This course teaches CUDA C++20: C++ host code plus CUDA device functions for NVIDIA GPUs. GPU Fundamentals explains threads, memory and execution; GPU Optimizations explains how to identify a worthwhile hotspot. You can study this opening without already having a performance problem. Before attempting production specialization, however, you must establish a correct reference and measured reason for the change.

Why use library kernels or write a custom one

Most applications should begin with maintained implementations. cuBLAS provides dense linear algebra; cuDNN provides deep-learning primitives; CUB, part of CUDA Core Compute Libraries (CCCL), supplies reusable parallel primitives such as reductions; CUTLASS provides composable templates for high-performance linear algebra. Obtain their documented APIs, examples and supported releases from the official resources at the end of this course. A library call may select and launch several internal kernels; there is no single universal collection of source files called the standard CUDA kernels.

Custom means you own the device implementation or a specialized composition. It can help when an important operation has unsupported semantics, unusual shapes, or avoidable intermediate memory traffic that the existing framework/compiler/library path cannot remove. It also makes you responsible for races, out-of-bounds access, numerics, portability and maintenance. A small local speedup is not enough if integration slows the overall application or excludes required inputs.

The first decision example uses general matrix multiplication (GEMM), which combines rows and columns through multiply-and-sum operations. Its epilogue is output processing performed after the matrix product, such as adding a bias offset and applying the rectified linear unit (ReLU), which replaces negative values with zero. Later lessons implement these stages; here they give a concrete example of separating maintained library work from a possible customization.

How the application chooses CPU or GPU execution

Ordinary host C++ executes on the CPU. A CUDA kernel is marked with __global__ and launched with CUDA launch syntax; it does not run on the CPU as an ordinary function call. A host reference implementation uses a separate CPU path. The application chooses which implementation to invoke, allocates accessible storage, arranges transfers when needed, and waits before consuming an unfinished result. Compiling with nvcc does not automatically parallelize every C++ loop or copy every host object to device memory.

For the ordinary explicit-memory path, allocate host inputs and device buffers, copy inputs to the device, launch the kernel in a stream, check submission errors, and wait for the required GPU work and output transfers before inspecting results on the host. Device buffers can remain resident across many launches. Production wrappers usually accept existing device pointers and a stream so they do not force unnecessary copies or device-wide synchronization.

How another application can reuse your kernel

Expose a host-facing application programming interface (API) rather than asking every consumer to reproduce launch geometry. Its contract names supported shapes, strides, dtypes, alignment, pointer/device ownership, stream ordering, error reporting and numerical tolerance. It should reject unsupported inputs explicitly. A consumer is simply another program that calls that API.

A source package lets consumers compile for their declared toolkit and GPU targets. A compiled static/shared library needs matching headers, linkage and an explicit binary support matrix. A framework extension additionally needs operator registration and, where applicable, gradient and compiler integration; wrapping a pointer is not sufficient. Shipping an sm_90a binary does not promise forward compatibility. A license, documented build, examples, clean consumer test and correctness/sanitizer evidence are release requirements, not optional polish. Later lessons return to these decisions after the kernel has been validated; nothing in this course publishes an artifact on your behalf.

The diagram connects the host-facing API and application orchestration to the kernel's device work.

From a CPU application to a reusable GPU kernel A CPU application selects a CPU implementation or a CUDA host-facing API. The CUDA API validates its contract and submits a grid using device-accessible inputs. GPU threads execute the kernel, producing device outputs. A completion dependency precedes result use; copying back to the host is needed only when the host consumes the result. Reusable APIs accept pointers and a stream instead of forcing transfers on every call. CPU application chooses an implementation for an operation CPU pathHost function or libraryReads host-accessible dataProduces a CPU result CUDA path: host wrapper + device implementation Validate APIdevice pointers / shapedtype / stream / errorsSubmit launchgrid + block geometryCPU queues device workGPU kernelthreads compute outputsin device memory Observe completion before consuming the required resultKeep data resident for another kernel, or copy to host when the CPU needs it Allocation and transfers are application responsibilities unless explicitly included in the API contract. A source package or library needs a documented API, build targets, clean consumer test and release evidence.
From a CPU application to a reusable GPU kernel

A CPU application selects a CPU implementation or a CUDA host-facing API. The CUDA API validates its contract and submits a grid using device-accessible inputs. GPU threads execute the kernel, producing device outputs. A completion dependency precedes result use; copying back to the host is needed only when the host consumes the result. Reusable APIs accept pointers and a stream instead of forcing transfers on every call.

Execution and dependencies

Fundamentals explains SM90 execution and GPU Optimizations proves a hotspot. The introductory explanation can be studied first; production customization begins only after an end-to-end profile identifies missing semantics or performance that maintained framework and library paths cannot supply.

A custom kernel is useful when a required operation leaves an important gap after maintained paths have been considered. The starting point is the operation's contract: supported shapes and value ranges, layouts/strides, dtypes and accumulation, broadcasting, masks, boundaries, aliasing/mutation, determinism, synchronization and numerical tolerances. Without that contract, a faster implementation may simply compute something different.

The missing work determines the next option. Batching or vectorization can remove repeated small calls. Existing PyTorch operators, compiler fusion or graph replay may remove dispatch or intermediates. cuBLAS, cuDNN and CUB/CCCL provide maintained algorithms, while a CUTLASS composition can specialize an epilogue without replacing the matrix-multiply structure. Handwritten CUDA is the remaining option for the smallest important region those paths cannot supply.

Library-first decision Read downward only while the required capability remains unavailable. Use a maintained path when it meets the contract; own a narrow CUDA implementation only for a meaningful residual gap. The arrows show evaluation order, not mandatory execution stages. Diagram concepts: Framework/compiler; cuBLAS, CUB, CUTLASS; Narrow custom kernel. Framework/compilercuBLAS, CUB, CUTLASSNarrow custom kernel
Library-first decision

Read downward only while the required capability remains unavailable. Use a maintained path when it meets the contract; own a narrow CUDA implementation only for a meaningful residual gap. The arrows show evaluation order, not mandatory execution stages.

Each candidate should have an explicit reason to help: fewer launches, less data movement, more useful parallel work or support for otherwise unavailable semantics. Its application value depends on how much of the end-to-end critical path that work occupies. A kernel that halves a negligible stage has negligible overall value.

The decision also assigns ownership. Shape coverage, supported architectures, fallback behavior, implementation effort, tests, portability and future maintenance belong beside the expected gain in the worksheet. Accepting a custom path means taking responsibility for those obligations, not merely selecting the fastest microbenchmark row.

A custom kernel transfers ownership of indexing, masking, synchronization, launch geometry, resource use, numerical behavior, profiling, portability, and version maintenance to your team. A microbenchmark win is insufficient if the hotspot contributes little to application time.

Try a small example

For inputs [1, 2, 3] and [4, 5, 6], both a CPU loop and a GPU kernel should produce [5, 7, 9]. For only three elements, launch and transfer overhead can dominate; the example teaches indexing and correctness, not a speedup. For larger arrays, measure the complete path as well as resident kernel time.

Mental model

A custom kernel adds numerical, architecture, toolchain, maintenance, and integration responsibilities. It is justified only for an important residual gap that narrower supported paths do not solve.

2. CUDA compilation and execution targets

Objective

Compile CUDA C++20 for compute capability 9.0 and verify the selected H100 and toolchain.

How it works

A CUDA build translates a program into CPU code and GPU code, then links the pieces and required libraries into an executable. A compiler performs that translation; nvcc is NVIDIA's CUDA compiler driver. CMake describes and organizes the build, including source files, language standards, libraries and target architectures. C++20 names a language-standard version, while SM90 names the GPU machine-code target associated with compute capability 9.0; these version labels describe different things.

Parallel Thread Execution (PTX) is intermediate device instruction code, the PTX assembler (ptxas) translates it into target machine code, and SASS is the target's machine-instruction representation. A cubin contains compiled device code. An application can also carry PTX for just-in-time translation by a compatible driver. A successful host build therefore does not prove that the right device implementation exists or can run on the intended H100. Toolchain preflight checks those separate layers before performance work begins.

The operation contract states the architecture and software support boundary. A reproducible build turns .cu source into PTX/cubin code the H100 driver can load.

CMake first configures the program's languages, compiler tools, build options and architecture targets. Building then asks nvcc to process CUDA source. It separates host and device compilation, uses the host toolchain for CPU code, and invokes device compilation including PTXAS when producing GPU machine code. Linking combines the resulting objects and required CUDA runtime libraries into an executable.

Architecture selection determines what device code the artifact contains. SM90 is the ordinary H100 target. Architecture-accelerated features have narrower compatibility requirements, so generating an SM90 executable does not establish support for every optional Hopper feature. PTX carried with an application also needs a driver capable of translating it for the target.

CUDA build and load Read downward: compile host and device portions, assemble or retain PTX as selected, then link the program. At execution, the driver loads compatible device code or compiles supported PTX. Build success does not prove that a kernel completed correctly. Diagram concepts: Source and target selection; Compile and link artifact; Driver loads device code. Source and targetselectionCompile and link artifactDriver loads device code
CUDA build and load

Read downward: compile host and device portions, assemble or retain PTX as selected, then link the program. At execution, the driver loads compatible device code or compiles supported PTX. Build success does not prove that a kernel completed correctly.

CTest is a later stage: it runs the checks registered by the CMake project. Configuration succeeding, the executable building and tests running answer different questions. A correct host build alone cannot prove that the intended device code loaded and executed on an H100, and registered tests do not replace sanitizer checks.

A container can package the compiler, headers and libraries under an immutable image digest. The GPU driver still comes from the host environment. Reproducibility therefore requires both a defined build artifact and a compatible execution environment; one compiler-version string cannot stand in for both.

Successful host compilation does not prove device code was generated for SM90, loaded on an H100, or linked against the expected runtime and libraries. Native-only flags also make artifacts irreproducible across build hosts.

Mental model

CMake selects CUDA language, host compiler, toolkit, and architectures. The driver loads compatible code on the device; architecture-accelerated sm_90a features are not forward-compatible.

3. Kernel indexing and execution safety

Objective

Implement indexing, bounds checks, launch geometry, error checks, and CUDA-event timing.

How it works

A vector kernel applies work to elements of an array. In vector addition, element i of the output is the sum of element i from each input. The programmer maps these logical elements onto GPU threads. Launch geometry specifies the number of blocks and threads per block; a global index combines a thread's block position and its local position within that block. A bounds check prevents extra threads in the final block from accessing elements outside the array.

A grid-stride loop lets each thread handle more elements at regular intervals when the grid is smaller than the input. Pointer aliasing means two names refer to overlapping storage; the restricted-pointer promise allows optimizations only when its non-overlap conditions hold. CUDA submission and execution are asynchronous, so checking whether a launch was accepted differs from waiting to learn whether its device accesses completed correctly.

The build produces a kernel, but correctness depends on the mapping from logical elements to grid, blocks, threads, and memory. This vector lab establishes the safety pattern reused by every later kernel.

The host first prepares initialized input buffers and device storage, then transfers any inputs not already resident. It chooses a thread count per block and computes blocks = ceil_div(n, threads), providing enough threads to cover n elements even when n is not an exact multiple of the block size.

Inside the kernel, a thread forms i = blockIdx.x * blockDim.x + threadIdx.x. Only threads with i < n load inputs and write an output. Extra threads in the final block therefore perform no invalid access. A grid-stride loop can extend this mapping so a deliberately bounded grid covers more than one element per thread.

The GPU places blocks on streaming multiprocessors (SMs), which execute their threads in groups of 32 called warps. Those threads issue memory accesses as they load inputs and store outputs. The diagram connects the logical index mapping to these execution and memory resources; it does not assign each thread its own physical core.

CUDA execution Read downward from logical work to hardware execution. Blocks contain warps, blocks are assigned to SMs, and ready warp instructions use memory and arithmetic pipelines. A software thread is not a physical core. Diagram concepts: Grid and blocks; Warps on SMs; Memory and pipelines. Grid and blocksWarps on SMsMemory and pipelines
CUDA execution

Read downward from logical work to hardware execution. Blocks contain warps, blocks are assigned to SMs, and ready warp instructions use memory and arithmetic pipelines. A software thread is not a physical core.

Submission and execution have separate error boundaries. The host checks launch errors immediately, then waits for the required work to complete to surface errors from device execution. It cannot inspect an unfinished result merely because the launch call returned. __restrict__ adds a non-aliasing promise only when the caller truly guarantees that the relevant pointer ranges do not overlap.

Resource Acquisition Is Initialization (RAII) ties C++ cleanup to an owning object's lifetime. That owner must outlast all asynchronous users of the allocation. Keeping it alive does not prevent an early overwrite, so lifetime and execution ordering remain separate responsibilities.

Correctness compares every output with a trusted CPU or maintained CUDA reference, including empty, one-element, prime, partial-block and alignment-relevant cases within the declared application programming interface (API). Warm-up precedes steady kernel timing. CUDA events measure the device interval, while synchronized end-to-end timing includes the orchestration and transfers required by the application.

Most first kernels fail at non-multiple sizes, asynchronous error reporting, aliasing assumptions, or incomplete timing rather than at the arithmetic expression itself.

ceil_div(N, B) means divide N by B and round up to the next whole block. For 1,003 elements and 256 threads per block, four blocks launch 1,024 threads. Indices 0 through 1,002 are valid; the last 21 threads must not access the array. Their output guard must still respect any block-wide synchronization required by the algorithm.

Mental model

Blocks cover the problem in tiles of threads. A ceiling division creates enough blocks, and a bounds check protects the partial final block. A grid-stride loop lets a deliberately bounded grid cover larger arrays; __restrict__ can expose optimization opportunities only when the caller truly guarantees that the named pointer ranges do not alias.

4. Kernel correctness and performance evidence

Objective

Use memcheck, racecheck, initcheck, synccheck, Nsight Systems, and Nsight Compute in a deliberate order.

How it works

A correctness test compares results with an expected answer. A sanitizer observes execution to detect classes of invalid behavior that might accidentally produce the right answer in one test. NVIDIA Compute Sanitizer contains several checkers: memcheck examines memory-access validity, racecheck examines shared-memory hazards, initcheck looks for uses of uninitialized device memory, and synccheck examines synchronization usage. A race occurs when conflicting accesses are not correctly ordered; a barrier coordinates a defined group of participating threads.

Profilers answer a different question. Nsight Systems records the application's execution timeline; Nsight Compute examines selected kernels and hardware counters. A counter is a measurement of hardware activity, not necessarily an elapsed time. Instrumentation and replay can slow or rerun work, so tools explain behavior while separate clean runs supply acceptance timing. Passing a checker supports the exercised inputs and paths, not every possible execution.

Lab 01 now provides a compiled vector kernel, a complete CPU-reference check and event timing. Use that simple program to learn memory checking and focused profiling before optimizing more complex kernels. The shared-memory race and synchronization examples below are previews to revisit with transpose, reduction and stencil.

A reference test first checks that every required output agrees with the intended operation. It can miss invalid behavior that happens to produce the correct answer on the tested schedule, so execution checks add a different form of evidence.

Compute Sanitizer's memcheck detects classes of invalid memory access, including out-of-bounds or misaligned accesses and device exceptions; configured leak checking adds allocation-lifetime evidence. Racecheck examines shared-memory hazards, initcheck examines uninitialized device-memory use, and synccheck examines invalid barrier or warp synchronization. Memory errors should be repaired before interpreting later checker findings, because one bad access can contaminate subsequent behavior. A pass establishes only the exercised paths and each checker's scope.

A sentinel helps detect omitted work. If every valid output must be finite, initializing output storage to not a number (NaN) means an unwritten element remains non-finite and fails validation. A wrong finite write still replaces the sentinel, so every written value must also be compared with the independent reference. Sentinel initialization belongs outside kernel-only timing unless it is part of the measured operation.

Once correctness is established, Nsight Systems locates launches, copies, gaps and synchronization on the application timeline. Nsight Compute then examines a selected kernel with focused metrics. Instrumentation and replay can alter execution, so final acceptance timing comes from a separate unprofiled run. Tool version, command, exit status and sanitized findings define the evidence without exposing raw private traces.

Kernel evidence sequence Arrows show evidence order. Compare results with a trusted reference, check exercised memory and synchronization behavior, then use profiling to explain performance. Separate unprofiled timing determines elapsed-time claims; each step can reveal a reason to stop and repair the candidate. Diagram concepts: Reference output checks; Memory and race checks; Profile, then time alone. Reference output checksMemory and race checksProfile, then time alone
Kernel evidence sequence

Arrows show evidence order. Compare results with a trusted reference, check exercised memory and synchronization behavior, then use profiling to explain performance. Separate unprofiled timing determines elapsed-time claims; each step can reveal a reason to stop and repair the candidate.

A kernel with a race can pass thousands of runs and fail under another schedule or GPU. Profiling incorrect code wastes effort, and profiler overhead must not be mistaken for application timing.

Mental model

Correctness tests compare outputs with expected results; sanitizers detect invalid behavior; Systems locates the critical path; Compute explains a selected kernel's resource, memory, and instruction behavior.

5. Elementwise kernel fusion

Objective

Compare a scale/bias kernel followed by a ReLU kernel with one fused kernel.

How it works

An elementwise operation applies a formula independently to corresponding input elements. Scaling multiplies a value, bias adds an offset, and the rectified linear unit (ReLU) activation replaces negative results with zero. Kernel fusion implements several such stages in one kernel. For scale → bias → ReLU, a thread can load an input, carry its intermediate value in a register, and write only the final result. Separate kernels instead communicate through stored intermediate arrays.

Fusion is an implementation change, not permission to change the formula or numerical behavior. Its potential benefit is fewer launches and less intermediate memory traffic, not removal of the required arithmetic. If another operation still needs an intermediate, or the larger kernel uses too many resources, the trade-off changes. This lesson implements fusion in CUDA after the earlier courses introduced its performance rationale.

The vector kernel established two input reads, one addition, and one output write. Fusion combines a producer-consumer chain so intermediate values remain in registers instead of returning to high-bandwidth memory (HBM).

Follow one element through the supplied Lab 02 expression, y = relu(scale*x + bias). The first kernel combines scale and bias, then writes one intermediate array. The second kernel reads that array, applies ReLU and writes the final output. This baseline uses two launches and one intermediate; the fused path uses one launch and keeps that intermediate value in a register.

A fused kernel loads the required inputs, carries the intermediate value in registers, performs the same stages and writes the final output once. The saving is the removed launches and intermediate reads/writes. It is valid only if broadcasting, aliasing, not a number (NaN)/Inf, signed-zero, precision and activation behavior still satisfy the operation's contract and no external consumer requires the removed intermediate.

Fusion traffic Compare Lab 02's two-kernel baseline with its fused kernel. Keeping the one intermediate in a register removes a logical array write and read. Both paths still write the final output; caches determine the physical HBM traffic saved. Diagram concepts: Two launches; One fused kernel; One output write. Two launchesOne fused kernelOne output write
Fusion traffic

Compare Lab 02's two-kernel baseline with its fused kernel. Keeping the one intermediate in a register removes a logical array write and read. Both paths still write the final output; caches determine the physical HBM traffic saved.

Logical bytes and physical traffic need separate accounting. Global-memory intermediates are backed by HBM, but some accesses may hit caches. Eliminating a logical write or reread therefore does not guarantee an equal reduction in measured dynamic random-access memory (DRAM) bytes. A byte/launch ledger explains the intended change; profiler traffic and unprofiled timing establish its effect.

Fusion can also change rounding. A fused multiply-add computes a*b+c with one final rounding, while separate multiplication and addition round the product first. Fused multiply-add (FMA) counts as two floating-point operations under this course's convention. Compiler contraction may select that path, so the reference comparison needs the allowed numerical result rather than automatic bitwise equality. Register use, occupancy and end-to-end contribution reveal whether the larger kernel introduced a cost that offsets the saving.

Low-intensity elementwise chains often spend more time launching and moving intermediates than computing. Fusion is valuable only when the intermediate has no required external consumer and resource growth does not create a larger limit.

Mental model

Separate elementwise kernels write intermediate arrays to global memory and require multiple launches. Those arrays are backed by HBM, but accesses may be served by caches. Fusion can keep intermediate values in registers between operations.

6. Memory layout and tiled transposition

Objective

Turn strided writes into coalesced transactions with a shared-memory tile.

How it works

A matrix transpose exchanges rows and columns: the value at input position [row, column] belongs at output [column, row]. A tile is a smaller rectangular region processed by a cooperating block. Coalescing combines nearby addresses requested by a warp into efficient global-memory transactions. A transpose is interesting because a simple mapping that reads neighboring input values can write widely separated output values.

Shared-memory tiling first stages the tile on chip, then lets threads read it in a different order before writing the transposed result. Shared memory is organized into banks that serve accesses; different addresses contending for the same bank can cause a bank conflict. Padding adds an unused storage column to change that mapping without changing the logical matrix. A block barrier makes the staged values available before other threads consume them. Correct handling of edge tiles is part of the algorithm, not an optional performance detail.

Fusion removes unnecessary trips to high-bandwidth memory (HBM). Tiling changes the lane-to-address mapping and creates deliberate on-chip reuse or reordering for traffic that must remain.

A naive transpose gives neighboring lanes neighboring input columns, so their loads are coalesced. Those values belong to different output rows, however, so the same lane mapping produces strided stores. One mapping cannot make both sides contiguous without rearranging the data between load and store.

The tiled kernel uses shared memory for that rearrangement. Threads cooperatively load a 32×32 region through contiguous global addresses, then all reach __syncthreads(). After the barrier, threads read transposed shared indices and write a contiguous output row. The barrier ensures each value has been written before another thread consumes it.

Shared-memory layout matters too. In the 32-bit-word case, H100 shared memory has 32 banks. Reading a column of tile[32][32] steps by 32 words, sending different addresses to the same bank. Padding to tile[32][33] changes that stride to 33 words: modulo 32, successive accesses advance one bank. The padding changes storage mapping without adding a logical matrix column.

Coalesced transpose Follow the data downward: load contiguous global rows, synchronize the shared tile, then read its transposed indices for contiguous output stores. A padding column changes the FP32 tile's bank mapping; partial tiles still require every barrier participant. Diagram concepts: Row-wise global load; Padded shared tile; Row-wise global store. Row-wise global loadPadded shared tileRow-wise global store
Coalesced transpose

Follow the data downward: load contiguous global rows, synchronize the shared tile, then read its transposed indices for contiguous output stores. A padding column changes the FP32 tile's bank mapping; partial tiles still require every barrier participant.

Edge tiles still need the full synchronization protocol. Predicate invalid loads and stores instead of letting some threads return before the block barrier. Correctness must cover the partial edges, while sectors/requests, bank-conflict evidence and effective bandwidth distinguish global-access savings from shared-memory costs.

A naive transpose has coalesced reads but strided writes, wasting global-memory transactions. A shared tile can make both sides coalesced, yet its own bank mapping can serialize accesses.

CUDA constant memory is a device memory space that kernels read through a dedicated cache. When participating lanes request the same address, one value can be broadcast to them; different addresses require separate servicing. This suits read-only, warp-uniform values, while divergent addresses or large working sets can favor another path.

Mental model

Threads load contiguous rows into a shared tile, wait for the tile to be ready, then read it in transposed order for contiguous output stores. Padding changes bank mapping; guards and barriers preserve correctness.

7. Parallel reductions

Objective

Compare synchronization and aggregation strategies against a maintained library reference.

How it works

A reduction combines many input values into fewer outputs, such as summing an array into one number. An atomic update performs a read-modify-write indivisibly with respect to competing updates to that location, preventing lost contributions; it does not make all threads finish together or guarantee a chosen floating-point addition order. A hierarchical reduction combines values within a warp, then a block, before combining block results. This reduces the number of workers contending for one global output.

Warp shuffle operations exchange register values between participating lanes without storing them in shared memory. The shuffle's mask names participating lanes; every named, non-exited thread must execute the matching operation with the same mask. This participation mask is distinct from __activemask(), which reports currently active lanes at that instruction. Block-level cooperation may require shared storage and a barrier. CUB, part of CUDA Core Compute Libraries (CCCL), supplies maintained parallel primitives including device-wide reduction. It is a baseline to compare with, not merely a slower reference implementation to replace.

Tiling coordinates threads through shared memory. Reduction coordinates many input contributions into fewer outputs, introducing ordering, synchronization, and floating-point reproducibility questions.

The simplest sum reduction lets each thread atomically add its contribution to one global result. Atomicity prevents lost updates, but all those updates compete for the same location. It also does not impose a reproducible floating-point addition order.

A hierarchical reduction combines values before they reach that bottleneck. Threads first accumulate local values in registers. Participating lanes exchange and combine partials with warp shuffles. Their explicit mask defines participation; every named lane must follow the primitive's rules, and an inactive source cannot be treated as a valid contribution.

Next, warp representatives write their partial sums to shared memory. A block barrier makes those writes visible before the consuming warp combines them. The block then issues one global atomic or writes one partial for a later reduction kernel. Warp synchronization cannot replace a block barrier when values cross warp boundaries.

Hierarchical reduction Read downward through a custom reduction. Local aggregation reduces global contention, with a block barrier before cross-warp reads. CUB is a separate maintained implementation to compare against, not a final stage inside this custom kernel. Diagram concepts: Thread-local contributions; Warp and block partials; Combine block results. Thread-local contributionsWarp and block partialsCombine block results
Hierarchical reduction

Read downward through a custom reduction. Local aggregation reduces global contention, with a block barrier before cross-warp reads. CUB is a separate maintained implementation to compare against, not a final stage inside this custom kernel.

CUB/CCCL DeviceReduce supplies a maintained implementation and is often the appropriate production choice. Comparisons include non-power-of-two, empty/small and multiple-block cases, plus the declared not a number (NaN) behavior. Because floating-point addition is not associative, different valid trees can differ numerically. A higher-precision reference and magnitude-aware tolerance check the result, while deterministic versus nondeterministic ordering remains an explicit part of the contract.

Having every thread atomically update one value is simple but can serialize. A fast tree can still be wrong if inactive lanes, barriers, or numerical order are mishandled.

For a four-value reduction, start with [1, 2, 3, 4]. Two independent pairs produce 3 and 7; the next level adds those partials to produce 10. A larger reduction repeats that tree across thread, warp and block scopes. Every parent must wait until its inputs exist. Integer arithmetic makes this small illustration exact; floating-point regrouping can change rounding, so correctness uses the declared tolerance.

Mental model

Reduce locally in registers and warps, combine per block, and minimize global atomics. Synchronize at the narrowest correct scope: a warp primitive is not a substitute for a block barrier when multiple warps exchange shared data. CUB provides a production baseline with tuned algorithms.

8. Neighborhood reuse and boundary handling

Objective

Load a tile and halo safely, reuse neighbors, and handle boundaries.

How it works

A stencil computes each output from a small neighborhood of input values. A one-dimensional radius-one stencil reads the left neighbor, center and right neighbor for each output; an image filter extends the idea to a two-dimensional neighborhood. Neighboring outputs often need some of the same inputs, creating an opportunity for reuse. A tile is the set of outputs assigned to a block. Its halo contains the additional neighboring inputs just outside that output region that the calculation still needs.

Boundary conditions specify what happens where a neighbor lies beyond the global input, such as substituting zero or copying an edge value. They are part of the mathematical operation. Shared-memory staging loads a tile and its halo once for block-local reuse; all participating threads must follow the synchronization protocol even if some have no valid output to write.

The transpose uses shared memory for reordering. A stencil uses it for overlapping neighborhood reuse, adding halo ownership and boundary conditions.

For a radius-one stencil, each output needs its left neighbor, center and right neighbor. A block owns a tile of outputs, but computing its first and last outputs also needs one input outside each end of that tile. Those extra values form the left and right halo.

The block first loads its interior inputs and halos into shared memory. Threads responsible for out-of-range global positions write the values required by the boundary condition instead of making invalid reads. Once staging is complete, every participating thread reaches the barrier. Valid output threads can then read their three shared values and compute their result.

Stencil tile Arrows show load, synchronize and consume. The interior plus halo supplies overlapping neighborhoods; invalid global positions use the declared boundary value. Threads without an output may still be required at the barrier. Diagram concepts: Interior and halo loads; Shared reuse; Boundary-safe outputs. Interior and halo loadsShared reuseBoundary-safe outputs
Stencil tile

Arrows show load, synchronize and consume. The interior plus halo supplies overlapping neighborhoods; invalid global positions use the declared boundary value. Threads without an output may still be required at the barrier.

Threads with no output in a partial block may still be needed for staging or synchronization. Returning before the block-wide barrier can therefore break the algorithm even if that thread would never store an output. In higher dimensions, edge and corner halo ownership must be assigned just as explicitly.

Cooperative staging reduces repeated global requests for overlapping neighborhoods, but caches may already serve some naive rereads. Logical request counts, measured high-bandwidth memory (HBM) traffic and shared-memory cost answer different questions. Boundary and small-shape reference checks establish correctness first; any naive-versus-tiled performance comparison needs separately timed implementations rather than an assumed speedup from the traffic model.

Neighboring outputs repeatedly read the same inputs. Cooperative staging can reduce repeated global-memory requests and, when those requests miss the caches, HBM traffic, but one incorrect boundary or divergent barrier can deadlock or corrupt rare shapes.

Mental model

A block cooperatively loads its interior and halo into shared memory, synchronizes, and computes several outputs from reused values.

9. Kernel resource use and occupancy

Objective

Sweep launch and compiler resource choices and explain the fastest configuration.

How it works

Resource tuning changes how a kernel uses the finite execution state on each streaming multiprocessor (SM). Registers store per-thread working values, and shared memory supports block-local cooperation. Occupancy is active resident warps per SM divided by its maximum supported active warps. Theoretical occupancy is the resource-limited maximum for a launch; achieved occupancy is measured during execution. Neither is the fraction of peak arithmetic performance achieved. Register pressure describes demand for register storage. A spill places values into device-backed thread-local memory when they cannot remain in registers.

A stack holds thread-local call or temporary state. Instruction-level parallelism (ILP), introduced in Fundamentals, means several instructions can proceed without depending on one another's unfinished results. Updating independent accumulators (variables holding separate running results) exposes this freedom; repeatedly updating one accumulator retains a dependency chain. Loop unrolling expands loop iterations into instructions, which can expose independent work but increase code size and register demand. Launch bounds provide compiler information about intended launch constraints; a register cap limits register use and may induce spills. The kernel's block size changes how these resources are grouped. These choices interact, so a larger occupancy percentage can accompany slower execution rather than indicating a successful optimization.

The vector, transpose, reduction and stencil kernels established launch blocks, registers, shared memory and barriers. Now connect their per-block resource use to resident blocks and warps. This capacity model is the prerequisite for interpreting the next lesson's partial grid waves.

A compiled kernel requests resources before its blocks can become resident. PTXAS reports register use, stack storage, spill loads/stores and shared memory. Combined with a chosen block size, those demands compete with the SM's thread, warp, register, shared-memory and block-slot limits. The first exhausted resource bounds residency; CUDA occupancy APIs apply those limits to the actual kernel.

Residency only provides possible work. A resident warp may be stalled on a dependency and unable to issue. Eligible/issued-warp observations and stall metrics help explain whether the scheduler has useful choices, while unprofiled CUDA-event timing determines whether a variant completes sooner. Theoretical occupancy and achieved execution activity are different quantities.

Changing block size, tile size, unrolling, launch bounds or a register cap can move several costs at once. More live values may improve reuse or instruction-level parallelism but reduce resident blocks. A forced register cap, or some dynamically indexed local arrays, can introduce device-backed local-memory traffic. That added traffic can overwhelm the benefit of higher occupancy, which is why variants change one factor at a time.

Resource tradeoff The arrows connect resource demand to residency, then to possible execution. More resident warps help only when useful work is ready. Register caps may cause spills and extra memory waits instead of a speedup. Diagram concepts: Registers and shared memory; Blocks that fit on an SM; Ready work and elapsed time. Registers and sharedmemoryBlocks that fit on an SMReady work and elapsedtime
Resource tradeoff

The arrows connect resource demand to residency, then to possible execution. More resident warps help only when useful work is ready. Register caps may cause spills and extra memory waits instead of a speedup.

A persisting L2 (level-two cache) access window addresses a separate resource. It gives a bounded memory region preferential cache-retention treatment, not guaranteed residency in L2. That region competes with other data and needs its own reuse evidence; the policy does not repair register spills or alter the SM's occupancy limits.

Occupancy is an input to latency hiding, not a score. Forcing more occupancy can spill registers to local memory, shrink tiles, or reduce instruction-level parallelism.

Mental model

Threads, warps, registers, shared memory, and block slots constrain occupancy. Extra registers may improve local reuse until they reduce residency or spill.

10. Parallel workload balance

Objective

Distinguish warp divergence, task imbalance and tail waves, then evaluate the supplied work-regrouping experiment.

How it works

Divergence, task imbalance and tail waves describe different kinds of uneven execution. Warp divergence occurs when lanes in one warp need different control-flow paths. Task or block imbalance occurs when some independent groups have more work than others. A tail wave occurs near the end of a grid when too few blocks remain to fill the available resident-block slots. None is the same as percentile tail latency across repeated runs.

Regrouping puts similar tasks together, but packing moves their inputs and scattering restores outputs to their original order. A persistent queue lets running workers request more tasks; work stealing lets an idle worker take work from another queue. These scheduling techniques add their own memory and coordination costs. The important question is which level creates the waste, followed by whether a remedy preserves every task and repays its preparation cost.

The resource sweep established how many blocks can reside at once. Now diagnose whether remaining waste comes from active lane masks, unequal block durations or the final partial wave; each is a different scheduling problem.

Unused capacity can arise at three different levels. Within a warp, divergent control paths execute under different active-lane masks. Across blocks, unequal iteration counts, contention or data-dependent work let some blocks finish earlier than others. At the end of a grid, even equal-duration blocks can leave a partial wave with too few blocks to fill the available SM slots.

Imbalance diagnosis Compare three causes of unused execution capacity: divergent paths within warps, unequal block durations and too few remaining blocks. A remedy at one level need not help the others, and regrouping or queues add costs of their own. Diagram concepts: Warp divergence; Block-duration skew; Partial final wave. Warp divergenceBlock-duration skewPartial final wave
Imbalance diagnosis

Compare three causes of unused execution capacity: divergent paths within warps, unequal block durations and too few remaining blocks. A remedy at one level need not help the others, and regrouping or queues add costs of their own.

Each explanation predicts a different control. Uniform branch work versus mixed lanes isolates divergence. Equal task lengths versus skewed lengths isolates block imbalance. Grid sizes near a full-wave boundary expose the scheduling tail, while requiring care about changed total work. Active-lane metrics, task-duration proxies and grid/residency counts should be interpreted at their matching level.

A remedy must remove more cost than it adds. Regrouping similar tasks may reduce divergence but requires packing inputs and scattering outputs back to their original positions. Splitting heavy tasks can balance durations but adds coordination. Persistent queues or work stealing supply remaining tasks to ready workers while introducing queue and atomic overhead. Changing granularity can reduce a partial wave yet alter resource use.

Kernel and end-to-end distributions show whether the complete remedy helps. Preserving every task, its output position and its numerical result is part of that comparison; dropping expensive work or omitting regrouping time changes the question.

Divergence, irregular work, and tail waves can look similar in average utilization while requiring different remedies. One generic “load balance” fix often moves rather than removes cost.

Suppose a hypothetical device can keep eight equally sized blocks resident for this kernel and the grid has 18 blocks. Under the simplifying assumption that block durations match, two groups of eight can fill those slots, while the final two blocks occupy only two of the eight. This last group is a tail wave. It is different from divergence inside a block and from one block running longer than its peers; the device need not schedule real blocks in perfectly separated waves.

Mental model

Branch divergence changes active lane masks; work imbalance changes block duration; a partial tail wave leaves some execution slots idle after full waves complete; the idle fraction depends on remaining work.

11. Asynchronous memory pipelines

Objective

Overlap tile movement with computation using asynchronous copies and double buffering.

How it works

An asynchronous copy starts a data movement operation without requiring its issuer to wait immediately for completion. A software pipeline divides repeated work into stages, such as loading a tile and computing from it. Double buffering uses two storage regions so one tile can be consumed while another is being produced. This lesson concerns device-side global-to-shared movement inside a kernel, not CPU-to-GPU input transfer.

A producer fills a buffer; consumers may read it only after the copy completes, and the buffer can be overwritten only after all readers finish. Priming fills the initial stage, steady state overlaps independent stages, and draining finishes remaining work. These are descriptions of the pipeline's operation. The exact synchronization calls depend on the CUDA API used. Merely removing a wait creates a race, not a pipeline.

Shared tiling currently performs load, barrier, compute, then repeats. A pipeline separates producer and consumer stages so the next tile can move while the current tile computes.

A double-buffered device pipeline reserves two shared-memory buffers. Lab 08 uses Cooperative Groups: cooperative_groups::memcpy_async starts a group-coordinated global-to-shared copy, and cooperative_groups::wait waits for that group's asynchronous copies. The initial copy and wait fill the first buffer before computation reads it.

In steady state, the lab submits the next tile's copy into the alternate buffer before computing from the current buffer. After computation, the group waits for the copy and calls block.sync() before the next iteration. These calls establish copy completion and keep buffer reuse after all participating threads finish reading. Alternating buffer indices repeats the process; the loop completes the remaining work after the last copy.

Double-buffer pipeline Time runs downward. Tile i computes while an independent copy prepares tile i+1. The dependency arrow permits its computation only after that copy completes. Prime before this interval, reuse buffers only after all readers finish and drain at the end; no measured overlap is implied. Diagram concepts: Load next tile; Compute current tile; Swap stages. ComputeAsync copyCompute tileiCompute tilei+1Load tile i+1Copy completeTime runs downward
Double-buffer pipeline

Time runs downward. Tile i computes while an independent copy prepares tile i+1. The dependency arrow permits its computation only after that copy completes. Prime before this interval, reuse buffers only after all readers finish and drain at the end; no measured overlap is implied.

All participants must follow the same copy, wait and barrier protocol. Cooperative Groups names the participating CUDA thread group and supplies coordinated operations for it; a group application programming interface (API) does not excuse a member from the required synchronization. Omitting a wait creates a race, and reusing a stage too early overwrites data still in use.

Another CUDA interface combines cuda::memcpy_async with cuda::pipeline. That interface has explicit producer_acquire(), producer_commit(), consumer_wait() and consumer_release() operations. Those names belong to that API; Lab 08 uses the Cooperative Groups copy/wait interface instead. Hardware acceleration depends on architecture, alignment, byte count and memory spaces. Tensor Memory Accelerator (TMA), introduced later, is a distinct bulk/tensor transfer mechanism.

An asynchronous copy does not automatically overlap with computation. Correct copy completion, synchronization and buffer reuse are required, together with enough independent computation and available hardware resources. Use correctness checks, sanitizers, profiling and unprofiled timing to assess the supplied pipeline.

Warp specialization assigns separate warps to data-production and computation roles so their instruction paths can progress independently; producer/consumer barriers still protect shared stages. A Hopper memory-synchronization domain is an identifier assigned to a kernel launch; its writes and fences carry that identifier. A fence orders memory operations rather than acting as a barrier where all threads meet. Separating independent traffic into domains can keep a fence from waiting for unrelated writes. System scope includes participating host and device threads, rather than only threads on the local GPU. Ordering between different domains requires the documented system-scope fencing, including when both domains are on one GPU. Neither is implemented by this lab; both are advanced extensions requiring a separate correctness design and H100 qualification.

Mental model

A pipeline overlaps a future tile's copy with the current tile's computation. Each stage becomes readable only after its copy completes and reusable only after its consumers finish.

12. Matrix multiplication and output fusion

Objective

Compare cuBLAS plus a separate epilogue with a supported fused library path.

How it works

General matrix multiplication (GEMM) forms a matrix product and may combine it with an existing matrix. Its mainloop computes partial dot products. An epilogue transforms the completed results, for example by scaling, adding bias or applying an activation before storing them. cuBLAS supplies maintained matrix operations. CUTLASS supplies composable CUDA templates that describe matrix kernels and their output processing. Customizing an epilogue can target adjacent work while retaining established matrix-multiplication building blocks.

An M-by-K input multiplied by a K-by-N input produces M-by-N values. Leading dimensions describe the storage step between rows or columns under the chosen layout; alpha and beta scale the product and the additional matrix in the GEMM contract. Single-instruction, multiple-thread (SIMT) and Tensor Core implementations are different arithmetic paths. Fused output processing can use either path; fusion alone does not demonstrate Tensor Core execution.

Fusion removed elementwise intermediates, while the decision gate said not to rewrite mature GEMM. CUTLASS composes a tuned matrix-multiply mainloop with a customized output epilogue.

A GEMM mainloop accumulates the matrix product. Output-side work can then scale it, add another matrix or bias, apply ReLU and store the result. If that epilogue runs as a separate kernel, it must read the GEMM output and write its transformed result. A compatible fused epilogue applies those operations before the final store, potentially removing that intermediate traffic and launch.

The arithmetic policy remains part of correctness. A cuBLAS math mode controls permitted computation choices; pedantic mode follows prescribed precision and standardized arithmetic but does not promise bitwise equality with a CPU reference. A CUTLASS composition must separately support the desired mainloop, epilogue and layout. Using CUTLASS alone does not establish a Hopper Tensor Core path or broadcast-bias implementation. The supplied 32-bit floating point (FP32) SIMT case and its expanded bias remain distinct from those extensions.

Library epilogue Read downward through GEMM and output processing. A compatible fused epilogue can avoid a separate output read/write. Lab 09 compares cuBLAS plus an epilogue with CUTLASS FP32 SIMT and expanded bias; it does not isolate Hopper Tensor Core or epilogue-only gains. Diagram concepts: Library GEMM machinery; Bias plus activation; Final store. Library GEMM machineryBias plus activationFinal store
Library epilogue

Read downward through GEMM and output processing. A compatible fused epilogue can avoid a separate output read/write. Lab 09 compares cuBLAS plus an epilogue with CUTLASS FP32 SIMT and expanded bias; it does not isolate Hopper Tensor Core or epilogue-only gains.

Storage interpretation must also match the call. Row-major arrays place adjacent columns together; column-major arrays place adjacent rows together. To compute row-major C = A @ B through the traditional column-major cuBLAS interface, interpret the same buffers as transposes and compute C.T = B.T @ A.T. This swaps operand roles and M/N dimensions without physically transposing the data.

Each leading dimension comes from the actual buffer's storage stride, not automatically its logical row count. Incorrect layout, alpha or beta changes the operation rather than merely selecting a different implementation. The complete comparison therefore includes numerical policy, layout, output-side work and full operation cost.

Handwritten GEMM is an inappropriate default for a performance course: it must reproduce years of architecture, shape, precision, and numerical tuning. The remaining optimization opportunity is often work adjacent to GEMM.

Mental model

Vendor and template libraries carry sophisticated Tensor Core, tiling, scheduling, and architecture tuning. A custom epilogue targets the missing fusion without replacing GEMM.

13. Residual connections and normalization

Objective

Implement a large language model (LLM)-relevant fused operation with stable reduction and explicit tolerance.

How it works

A residual connection adds an earlier representation to a transformed one, allowing a block to pass information forward through a shortcut. Root mean square normalization (RMSNorm) rescales a vector according to the square root of its mean squared values, then applies learned scale weights. It changes the vector's scale without first subtracting its mean, unlike LayerNorm. Epsilon is a small positive constant added to keep the denominator well behaved, including for a zero vector.

Fused residual addition plus RMSNorm first forms x + skip and then normalizes that sum inside one implementation. Squaring and summing across a row is a reduction, while applying the inverse scale is elementwise work. Combining them can avoid writing and rereading the residual intermediate, but increases the values a kernel must retain or recompute. The supplied 32-bit floating point (FP32) fixed-width lab teaches this combined structure before optional wider-shape or reduced-precision extensions.

Fusion, reduction and resource tuning are now established, with asynchronous pipelines and library epilogues as additional patterns. Residual addition plus RMSNorm combines the core fusion/reduction patterns. Optional Hopper clusters and CUDA Tile C++ are not prerequisites for this case study.

The reciprocal-square-root operation is rsqrt(v) = 1 / sqrt(v). It converts the positive mean-square-plus-epsilon value into the shared normalization scale; epsilon prevents division by zero for an all-zero row.

For each row, the kernel first forms the residual values r = x + skip. RMSNorm needs their mean square, so it squares the row elements, combines them through a warp/block reduction in FP32 and divides by the row width. It then computes inv_rms = rsqrt(mean(r²)+epsilon) and produces each output as its residual value times inv_rms times the learned weight.

Residual normalization Read downward within one row. Form r from the input and residual, compute the mean of r squared, add epsilon and take the reciprocal square root, then multiply each r by that common scale and its learned weight. The reduction must finish before outputs use its scale. Diagram concepts: Add each residual pair; Reduce squared row values; Normalize and apply weights. Add each residual pairReduce squared row valuesNormalize and applyweights
Residual normalization

Read downward within one row. Form r from the input and residual, compute the mean of r squared, add epsilon and take the reciprocal square root, then multiply each r by that common scale and its learned weight. The reduction must finish before outputs use its scale.

Every output depends on the same row reduction. The residual values must therefore remain available until that reduction finishes, either retained in registers/shared memory or reproduced afterward. Fusion avoids writing the residual to global memory solely for the normalization to reread it. If the residual is itself a required external output, its store cannot be removed; that choice belongs in the operation contract.

The supplied lab uses FP32 and a fixed width of 256. Extending it to arbitrary or non-power-of-two widths requires correct reduction participation, aligned vector loads with safe scalar tails, and explicit input/output dtypes, epsilon and aliasing rules. Those cases are qualifications to add, not capabilities implied by a fixed-width pass.

Trusted CPU, CUDA or library results check zero, random and extreme inputs within the supported scope. Wider and reduced-precision extensions need their own tolerances. A read/write ledger explains potential savings, while register/shared-memory use and an independently timed baseline establish whether retaining or recomputing residual values costs less than materializing them.

Separate residual and normalization kernels materialize an intermediate and reread it. A fused kernel can remove traffic, but normalization needs a numerically stable row reduction and correct handling of every supported row width.

Precision-specialized paths may change vector width, accumulation, and math instructions; --use_fast_math changes numerical semantics globally and is never a free speed switch.

Mental model

The kernel adds the residual, computes a row’s mean square, forms an inverse root with epsilon, and scales each element. Fusion keeps the residual sum available for normalization without writing and rereading an intermediate array.

14. Kernel acceptance and integration

Objective

Profile a real hotspot, implement one justified change, and make a keep or reject decision.

How it works

Production acceptance is the decision that an implementation meets its declared correctness, safety, performance and support requirements well enough to integrate. A microbenchmark measures a bounded operation; end-to-end timing measures the complete application path. The baseline is the reference implementation, the candidate contains the change, and a rejection is a valid outcome when evidence does not justify maintenance. Amdahl's law expresses why improving a small part of a program can have only a limited effect on total time.

The operating envelope lists supported inputs, numerical formats, layouts and devices. Counterbalanced trials vary which implementation runs first to reduce order bias. Packaging is a later integration step: a host-facing application programming interface (API) exposes a callable contract, source distribution lets consumers compile it, and binary distribution supplies already-compiled code with an explicit compatibility contract. A passing teaching executable is not yet a tested reusable package or an authorized public release.

Every lab taught one mechanism in isolation. Production acceptance starts from the application again and proves that a correct, safe kernel changes the end-to-end objective across supported cases.

Acceptance begins at the application boundary. Fixed operation semantics, workload, H100/software identity and success thresholds define what a candidate must preserve. An uninstrumented baseline distribution establishes elapsed time, and a Systems profile identifies how much of it belongs to the suspected hotspot. Amdahl's law then bounds the application value available even from a perfect replacement.

Maintained alternatives come before a new implementation. If a gap remains, the smallest candidate receives independent reference checks, edge-shape cases, explicit errors and numerical tolerances. Relevant sanitizers examine memory and synchronization behavior; compiler reports and a focused Compute profile explain resources and the proposed performance mechanism.

At least three independent kernel and end-to-end trials, with counterbalanced order, test whether the saving survives normal variation and integration overhead. Supported shapes, dtypes, layouts and any declared fallback are part of that evidence. Correctness, non-finite handling, p50/p95 timing, memory, launch count and compilation/startup costs determine the result together with ownership, portability and limitations.

Acceptance flow Read downward through evidence before integration. Reference tests check results, sanitizers check exercised memory/synchronization behavior, and profiles explain the candidate. Separate unprofiled end-to-end trials establish useful application value. Diagram concepts: Reference and tests; Sanitizer and profiler; End-to-end decision. Reference and testsSanitizer and profilerEnd-to-end decision
Acceptance flow

Read downward through evidence before integration. Reference tests check results, sanitizers check exercised memory/synchronization behavior, and profiles explain the candidate. Separate unprofiled end-to-end trials establish useful application value.

A reusable release adds another boundary: another program calls a supported interface. That contract specifies input validity, device and stream ownership, completion/error behavior, numerical limits and the build/runtime matrix. A clean consumer test checks use without relying on the teaching executable. Source packages and compiled libraries have different distribution obligations; successful compilation alone does not establish runtime support or authorize publication.

Kernel speed, application speed, capacity, portability, and maintenance are separate axes. A narrow benchmark cannot authorize deployment or a broad performance claim.

Suppose a kernel accounts for 40% of a 10-millisecond application step. Making that kernel twice as fast changes its 4 milliseconds to 2; the other 6 remain, so the step becomes 8 milliseconds and the application speedup is 10 / 8 = 1.25. This is the idea behind Amdahl's law: unchanged work limits the total benefit. Integration overhead can reduce the gain further. A p50 latency is the median; p95 is the 95th percentile, below which approximately 95% of observations fall.

Mental model

Acceptance connects operation contract, numerical correctness, memory/synchronization safety, kernel evidence, and end-to-end product value plus maintenance boundaries.

15. Advanced GPU data movement and cooperation

Objective

Distinguish TMA transfers, thread-block clusters and distributed shared memory, and explain which capability the supplied cluster-launch probe actually tests.

How it works

The Tensor Memory Accelerator (TMA) is a Hopper data-movement mechanism for transferring described tensor regions asynchronously, including global-to-shared copies, with less per-element address work in ordinary threads. A tensor descriptor records the layout, dimensions and related transfer information. Completion must still be tracked before the transferred data is consumed. TMA is not simply another name for every asynchronous CUDA copy.

A thread-block cluster is a group of blocks guaranteed to be co-scheduled on one GPU processing cluster (GPC). Distributed shared memory lets participating blocks access shared-memory regions across that thread-block cluster; distributed here means within one GPU, not across networked nodes. Cluster barriers coordinate the group and protect the lifetime of remotely accessed storage. TMA and clusters are distinct mechanisms that can be combined, but neither automatically makes a kernel faster. This optional lesson separates their definitions from the limited cluster-launch probe actually implemented.

The required single-GPU path and its acceptance capstone are complete. This optional branch extends block-scoped shared pipelines with Hopper movement and coordination mechanisms. It does not gate the core course, and its launch and synchronization contracts require separate qualification.

TMA begins with a descriptor of a multidimensional tensor's layout and extents. A designated thread can issue a bulk asynchronous transfer, including global-to-shared movement, while other threads perform independent work. Alignment, bounds, barriers and completion rules determine when the destination is safe to consume. Correct descriptor construction and edge handling are part of the algorithm, not optional checks around an otherwise ordinary copy.

Thread-block clusters address cooperation between blocks assigned to SMs in the same GPC. Their co-scheduling guarantee allows cluster-wide synchronization and distributed shared-memory access. Blocks must establish the required cluster lifetime and synchronization before remote shared accesses, and keep the target block's storage alive until all such accesses finish. Cluster size and resource use can limit occupancy.

TMA and clusters are distinct mechanisms. The optional course probe tests only a cluster launch: an extended configuration requests two blocks per cluster and a grid of four blocks, producing two clusters if the device supports that arrangement. cudaLaunchKernelEx submits the attributes along with the ordinary grid/block configuration, and checking every recorded block index verifies the bounded launch.

H100 advanced path Compare distinct Hopper capabilities. TMA moves described tiles; cluster blocks are co-scheduled on one GPC; distributed shared memory needs the cluster lifetime and synchronization rules. Lab 10 tests cluster launch only. Diagram concepts: TMA tile movement; Cluster scheduling; Distributed shared memory. TMA tile movementCluster schedulingDistributed shared memory
H100 advanced path

Compare distinct Hopper capabilities. TMA moves described tiles; cluster blocks are co-scheduled on one GPC; distributed shared memory needs the cluster lifetime and synchronization rules. Lab 10 tests cluster launch only.

That result does not demonstrate TMA transfers or distributed shared-memory cooperation. Those extensions need their own descriptor/stride validation, portable reference, supported cluster/occupancy checks, sanitizers and focused profiles. Explicit build and runtime gates keep their narrower qualification separate from the core SM90 course.

TMA and clusters can reduce address-generation work or enable reuse beyond one block, yet unsupported shapes, bad descriptors, cluster occupancy, or missing cluster-wide synchronization can make them incorrect or slower.

Mental model

TMA moves described tensor regions with less per-element address work; thread-block clusters provide co-scheduling on one GPC and access to distributed shared memory. These mechanisms have separate correctness and qualification requirements; a successful cluster launch alone proves neither TMA transfers nor shared-memory cooperation.

16. Tile-level kernel programming

Objective

Decide whether CUDA Tile C++ is useful for a future kernel without making it a prerequisite or silently changing the H100 toolchain.

How it works

Tile-level programming expresses work over blocks of values rather than describing every individual thread's index manipulation. A tile might hold a small matrix region that is loaded, transformed, reduced and stored through collective operations. CUDA Tile C++ provides a C++ interface to NVIDIA's tile-oriented programming model. It is an expression and compiler interface, not an additional physical memory tier, GPU generation or replacement for the CUDA runtime.

In explicit thread/block CUDA, the programmer describes much of the mapping and coordination directly. A tile abstraction delegates more of that mapping to the compiler while retaining requirements about data dependencies, boundaries and numerical behavior. This optional lesson asks whether that abstraction makes a selected kernel easier to maintain on a qualified toolchain. It does not assume the required H100 course build supports it or that a shorter source automatically produces a faster kernel.

The core course uses stable CUDA C++ concepts and explicit thread/block code. Tile-level programming is an optional expression model that still compiles to kernels governed by the same memory, synchronization, and evidence rules.

A tile-oriented version starts with the same accepted operation and expresses it in larger units of data. Instead of spelling out every thread's scalar index, it describes a tile shape, loads a tile, applies transformations or reductions, coordinates dependencies and stores the result. The compiler takes responsibility for more of the mapping onto execution resources.

Tile programming model Arrows show logical data flow. Coordinates select a region, tile operations describe its computation, and guarded stores keep boundary positions valid. The compiler maps these operations to GPU execution resources; a logical tile is not a new physical hardware unit. Diagram concepts: Choose tile coordinates; Load and compute tile; Store valid tile elements. Choose tile coordinatesLoad and compute tileStore valid tile elements
Tile programming model

Arrows show logical data flow. Coordinates select a region, tile operations describe its computation, and guarded stores keep boundary positions valid. The compiler maps these operations to GPU execution resources; a logical tile is not a new physical hardware unit.

That change in expression does not remove the operation's contract. Partial edge tiles still need safe behavior; loads must finish before consumption; reductions need the intended numerical semantics; and outputs must match the accepted CUDA C++ reference. A shorter source may generate more or less efficient instructions, so readability and performance remain separate questions.

The optional evaluation fixes the required CUDA release and compiler mode, inspects generated targets and resource use, and retains the original implementation as the reference or explicitly supported fallback. Edge-shape correctness, available sanitizer coverage, compile time, binary portability, kernel metrics and complete timing define the comparison.

Application programming interface (API) and compiler support are a separate qualification lane. Trying this expression model does not implicitly update the core H100 toolchain or make CUDA Tile C++ a prerequisite for the rest of the course.

A newer abstraction can reduce indexing code but does not guarantee a better generated kernel, complete feature coverage, or compatibility with the pinned H100 environment.

Mental model

CUDA Tile C++ expresses work over tile-shaped data and cooperative execution abstractions. Its API and generated code are tied to the selected CUDA toolkit; it does not replace the need to understand memory movement, synchronization, numerical contracts, or profiler evidence.

Practical labs

Download results

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

Setup the lab environment:
Lab setup guide

Lab 01: Launch and validate a bounds-safe vector kernel

Vector addition is simple enough to expose the essential CUDA program structure without hiding it behind an algorithm. This lab allocates device buffers, transfers inputs, launches a one-dimensional kernel, and checks every output against a CPU reference.

Complete source: labs/01_vector_add.cu
#include "common.cuh"

__global__ void vector_add(const float* left, const float* right, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) output[index] = left[index] + right[index];
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 01_vector_add [--workload small|large] [--threads 128|256|512]\n"; return 0; }
  try {
    bool small = false, profile_seen = false, threads_seen = false;
    int threads = 256;
    // Read workload and kernel controls before allocating buffers.
    for (int index = 1; index < argc; ++index) {
      const std::string argument(argv[index]);
      if (argument == "--workload") small = parse_small_profile(argc, argv, index, profile_seen);
      else if (argument == "--threads" && !threads_seen && index + 1 < argc) {
        const std::string value(argv[++index]);
        if (value != "128" && value != "256" && value != "512")
          throw std::runtime_error("--threads must be 128, 256, or 512");
        threads = std::stoi(value); threads_seen = true;
      } else throw std::runtime_error("unknown, duplicate, or incomplete argument: " + argument);
    }
    const std::size_t count = small ? 1003 : (1U << 24);
    require_course_gpu();
    // Allocate host inputs and reference/output storage.
    std::vector<float> left(count), right(count), expected(count), observed(count);
    for (std::size_t index = 0; index < count; ++index) {
      left[index] = static_cast<float>(index % 97) / 97.0F;
      right[index] = static_cast<float>(index % 53) / 53.0F;
      expected[index] = left[index] + right[index];
    }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_left(count), device_right(count), device_output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_left.get(), left.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(device_right.get(), right.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    const int blocks = static_cast<int>((count + threads - 1) / threads);
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto timing = benchmark_cuda([&] {
      vector_add<<<blocks, threads>>>(device_left.get(), device_right.get(), device_output.get(), count);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(observed.data(), device_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, observed);
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("01_vector_add", timing, count);
    std::cout << "blocks=" << blocks << "\nthreads_per_block=" << threads << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/01_vector_add.sbatch --workload small

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

Lab 02: Remove an intermediate with elementwise fusion

Two simple kernels can spend more time moving intermediate values than performing arithmetic. This lab compares separate elementwise stages with a fused scale/bias/ReLU calculation using corresponding inputs.

Complete source: labs/02_fused_elementwise.cu
#include "common.cuh"

__global__ void scale_bias(const float* input, const float* bias, float* temporary, float scale, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) temporary[index] = input[index] * scale + bias[index];
}

__global__ void relu(const float* input, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) output[index] = fmaxf(input[index], 0.0F);
}

__global__ void fused_scale_bias_relu(const float* input, const float* bias, float* output, float scale, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) output[index] = fmaxf(input[index] * scale + bias[index], 0.0F);
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 02_fused_elementwise [--workload small|large]\n"; return 0; }
  try {
    const std::size_t count = problem_size(argc, argv, 4099, 1U << 25);
    require_course_gpu();
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count), bias(count), expected(count), separate_observed(count), fused_observed(count);
    for (std::size_t index = 0; index < count; ++index) {
      input[index] = static_cast<float>(static_cast<int>(index % 101) - 50) / 25.0F;
      bias[index] = static_cast<float>(index % 7) / 10.0F;
      expected[index] = std::max(input[index] * 1.25F + bias[index], 0.0F);
    }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), device_bias(count), temporary(count), separate_output(count), fused_output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(device_bias.get(), bias.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    constexpr int threads = 256;
    const int blocks = static_cast<int>((count + threads - 1) / threads);
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto separate_timing = benchmark_cuda([&] {
      scale_bias<<<blocks, threads>>>(device_input.get(), device_bias.get(), temporary.get(), 1.25F, count);
      relu<<<blocks, threads>>>(temporary.get(), separate_output.get(), count);
    });
    const auto fused_timing = benchmark_cuda([&] {
      fused_scale_bias_relu<<<blocks, threads>>>(device_input.get(), device_bias.get(), fused_output.get(), 1.25F, count);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(separate_observed.data(), separate_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(fused_observed.data(), fused_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, separate_observed);
    check_close(expected, fused_observed);
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("02_fused_elementwise", fused_timing, count);
    print_timing("separate", separate_timing);
    print_timing("fused", fused_timing);
    std::cout << "baseline_correctness=passed\ncandidate_correctness=passed\nlogical_separate_bytes=" << count * sizeof(float) * 5 << "\nlogical_fused_bytes=" << count * sizeof(float) * 3 << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/02_fused_elementwise.sbatch --workload small

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

Lab 03: Coalesce a transpose and reduce shared-memory conflicts

A transpose naturally makes either reads or writes strided when implemented directly. This lab compares naive, tiled-unpadded, and tiled-padded CUDA transposes.

Complete source: labs/03_tiled_transpose.cu
#include "common.cuh"

constexpr int tile_width = 32;

__global__ void naive_transpose(const float* input, float* output, int rows, int columns) {
  const int column = blockIdx.x * blockDim.x + threadIdx.x;
  const int row = blockIdx.y * blockDim.y + threadIdx.y;
  if (row < rows && column < columns) output[column * rows + row] = input[row * columns + column];
}

__global__ void tiled_transpose(const float* input, float* output, int rows, int columns) {
  __shared__ float tile[tile_width][tile_width + 1];
  const int input_column = blockIdx.x * tile_width + threadIdx.x;
  const int input_row = blockIdx.y * tile_width + threadIdx.y;
  if (input_row < rows && input_column < columns) tile[threadIdx.y][threadIdx.x] = input[input_row * columns + input_column];
  __syncthreads();
  const int output_column = blockIdx.y * tile_width + threadIdx.x;
  const int output_row = blockIdx.x * tile_width + threadIdx.y;
  if (output_row < columns && output_column < rows) output[output_row * rows + output_column] = tile[threadIdx.x][threadIdx.y];
}

__global__ void tiled_unpadded_transpose(const float* input, float* output, int rows, int columns) {
  __shared__ float tile[tile_width][tile_width];
  const int input_column = blockIdx.x * tile_width + threadIdx.x;
  const int input_row = blockIdx.y * tile_width + threadIdx.y;
  if (input_row < rows && input_column < columns) tile[threadIdx.y][threadIdx.x] = input[input_row * columns + input_column];
  __syncthreads();
  const int output_column = blockIdx.y * tile_width + threadIdx.x;
  const int output_row = blockIdx.x * tile_width + threadIdx.y;
  if (output_row < columns && output_column < rows) output[output_row * rows + output_column] = tile[threadIdx.x][threadIdx.y];
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 03_tiled_transpose [--workload small|large]\n"; return 0; }
  try {
    const int rows = static_cast<int>(problem_size(argc, argv, 1003, 8192));
    require_course_gpu();
    const int columns = rows + 17;
    const std::size_t count = static_cast<std::size_t>(rows) * columns;
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count), expected(count), naive_observed(count), unpadded_observed(count), padded_observed(count);
    for (std::size_t index = 0; index < count; ++index) input[index] = static_cast<float>(index % 251);
    for (int row = 0; row < rows; ++row) for (int column = 0; column < columns; ++column) expected[column * rows + row] = input[row * columns + column];
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), naive_output(count), unpadded_output(count), padded_output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    const dim3 threads(tile_width, tile_width);
    const dim3 blocks((columns + tile_width - 1) / tile_width, (rows + tile_width - 1) / tile_width);
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto naive_timing = benchmark_cuda([&] {
      naive_transpose<<<blocks, threads>>>(device_input.get(), naive_output.get(), rows, columns);
    });
    const auto unpadded_timing = benchmark_cuda([&] {
      tiled_unpadded_transpose<<<blocks, threads>>>(device_input.get(), unpadded_output.get(), rows, columns);
    });
    const auto padded_timing = benchmark_cuda([&] {
      tiled_transpose<<<blocks, threads>>>(device_input.get(), padded_output.get(), rows, columns);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(naive_observed.data(), naive_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(unpadded_observed.data(), unpadded_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(padded_observed.data(), padded_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, naive_observed);
    check_close(expected, unpadded_observed);
    check_close(expected, padded_observed);
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("03_tiled_transpose", padded_timing, count);
    print_timing("naive", naive_timing);
    print_timing("tiled_unpadded", unpadded_timing);
    print_timing("tiled_padded", padded_timing);
    std::cout << "naive_correctness=passed\nunpadded_correctness=passed\npadded_correctness=passed\nunpadded_shared_columns=32\npadded_shared_columns=33\n";
    std::cout << "rows=" << rows << "\ncolumns=" << columns << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/03_tiled_transpose.sbatch --workload small

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

Lab 04: Compare atomic, hierarchical, and CUB reductions

A reduction combines many inputs into a small output, so contention and aggregation strategy matter. This lab sums a vector using one atomic per element, warp/block aggregation followed by one atomic per block, and CUB's maintained device reduction.

Complete source: labs/04_reduction.cu
#include "common.cuh"

#include <cub/device/device_reduce.cuh>

__global__ void atomic_sum(const float* input, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) atomicAdd(output, input[index]);
}

__device__ float warp_sum(float value) {
  for (int offset = 16; offset > 0; offset >>= 1) {
    value += __shfl_down_sync(0xffffffffU, value, offset);
  }
  return value;
}

__global__ void block_atomic_sum(const float* input, float* output, std::size_t count) {
  __shared__ float warp_partials[32];
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  const int lane = threadIdx.x & 31;
  const int warp = threadIdx.x >> 5;
  float value = index < count ? input[index] : 0.0F;
  value = warp_sum(value);
  if (lane == 0) warp_partials[warp] = value;
  __syncthreads();
  if (warp == 0) {
    value = lane < (blockDim.x + 31) / 32 ? warp_partials[lane] : 0.0F;
    value = warp_sum(value);
    if (lane == 0) atomicAdd(output, value);
  }
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 04_reduction [--workload small|large]\n"; return 0; }
  try {
    const std::size_t count = problem_size(argc, argv, 1003, 1U << 24);
    require_course_gpu();
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count, 1.0F);
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), atomic_output(1), block_output(1), cub_output(1);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemset(atomic_output.get(), 0, sizeof(float)));
    constexpr int threads = 256;
    const int blocks = static_cast<int>((count + threads - 1) / threads);
    const auto atomic_timing = benchmark_cuda_with_setup(
        [&] { CUDA_CHECK(cudaMemset(atomic_output.get(), 0, sizeof(float))); },
        [&] { atomic_sum<<<blocks, threads>>>(device_input.get(), atomic_output.get(), count); });
    const auto block_timing = benchmark_cuda_with_setup(
        [&] { CUDA_CHECK(cudaMemset(block_output.get(), 0, sizeof(float))); },
        [&] { block_atomic_sum<<<blocks, threads>>>(device_input.get(), block_output.get(), count); });
    std::size_t temporary_bytes = 0;
    cub::DeviceReduce::Sum(nullptr, temporary_bytes, device_input.get(), cub_output.get(), count);
    DeviceBuffer<unsigned char> temporary(temporary_bytes);
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto cub_timing = benchmark_cuda([&] {
      CUDA_CHECK(cub::DeviceReduce::Sum(temporary.get(), temporary_bytes, device_input.get(), cub_output.get(), count));
    });
    float atomic_value = 0.0F;
    float block_value = 0.0F;
    float cub_value = 0.0F;
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(&atomic_value, atomic_output.get(), sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(&block_value, block_output.get(), sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(&cub_value, cub_output.get(), sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(
        {static_cast<float>(count), static_cast<float>(count), static_cast<float>(count)},
        {atomic_value, block_value, cub_value});
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("04_reduction", cub_timing, count);
    print_timing("per_element_atomic", atomic_timing);
    print_timing("warp_block_atomic", block_timing);
    print_timing("cub", cub_timing);
    std::cout << "per_element_atomic_operations=" << count << "\nblock_atomic_operations=" << blocks << "\ncub_temporary_bytes=" << temporary_bytes << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/04_reduction.sbatch --workload small

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

Lab 05: Reuse neighboring values with a shared-memory halo

Stencil operations compute each output from nearby input values, so adjacent threads can reuse much of the same data. This lab implements a one-dimensional three-point stencil with a shared tile and two halo values.

Complete source: labs/05_tiled_stencil.cu
#include "common.cuh"

__global__ void stencil(const float* input, float* output, std::size_t count) {
  extern __shared__ float tile[];
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  const int local = static_cast<int>(threadIdx.x) + 1;
  tile[local] = index < count ? input[index] : 0.0F;
  if (threadIdx.x == 0) tile[0] = index > 0 ? input[index - 1] : 0.0F;
  if (threadIdx.x == blockDim.x - 1) tile[blockDim.x + 1] = index + 1 < count ? input[index + 1] : 0.0F;
  __syncthreads();
  if (index < count) output[index] = 0.25F * tile[local - 1] + 0.5F * tile[local] + 0.25F * tile[local + 1];
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 05_tiled_stencil [--workload small|large]\n"; return 0; }
  try {
    const std::size_t count = problem_size(argc, argv, 1003, 1U << 24);
    require_course_gpu();
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count), expected(count), observed(count);
    for (std::size_t index = 0; index < count; ++index) input[index] = static_cast<float>(index % 101) / 101.0F;
    for (std::size_t index = 0; index < count; ++index) {
      const float left = index > 0 ? input[index - 1] : 0.0F;
      const float right = index + 1 < count ? input[index + 1] : 0.0F;
      expected[index] = 0.25F * left + 0.5F * input[index] + 0.25F * right;
    }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    constexpr int threads = 256;
    const int blocks = static_cast<int>((count + threads - 1) / threads);
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto timing = benchmark_cuda([&] {
      stencil<<<blocks, threads, (threads + 2) * sizeof(float)>>>(device_input.get(), output.get(), count);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(observed.data(), output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, observed);
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("05_tiled_stencil", timing, count);
    std::cout << "shared_bytes_per_block=" << (threads + 2) * sizeof(float) << "\nhalo_values_per_full_block=2\n";
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/05_tiled_stencil.sbatch --workload small

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

Lab 06: Group unequal work while preserving output order

Neighboring lanes that execute different amounts of work can leave some lanes inactive while others continue. This lab compares alternating long/short work with a grouped arrangement that preserves every input's assigned calculation.

Complete source: labs/06_divergence_tail.cu
#include "common.cuh"

__global__ void divergent_work(const float* input, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index >= count) return;
  float value = input[index];
  if ((index & 1U) == 0U) {
    for (int iteration = 0; iteration < 32; ++iteration) value = fmaf(value, 1.00001F, 0.00001F);
  } else {
    for (int iteration = 0; iteration < 4; ++iteration) value = fmaf(value, 1.00001F, 0.00001F);
  }
  output[index] = value;
}

__global__ void pack_grouped(const float* input, float* grouped_input, std::size_t count,
                             std::size_t long_count) {
  const std::size_t grouped_index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (grouped_index >= count) return;
  const std::size_t logical_index = grouped_index < long_count
                                        ? grouped_index * 2
                                        : (grouped_index - long_count) * 2 + 1;
  grouped_input[grouped_index] = input[logical_index];
}

__global__ void grouped_work(const float* input, float* output, std::size_t count,
                             std::size_t long_count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index >= count) return;
  const bool long_path = index < long_count;
  float value = input[index];
  const int iterations = long_path ? 32 : 4;
  for (int iteration = 0; iteration < iterations; ++iteration) value = fmaf(value, 1.00001F, 0.00001F);
  output[index] = value;
}

__global__ void scatter_grouped(const float* grouped_output, float* logical_output,
                                std::size_t count, std::size_t long_count) {
  const std::size_t grouped_index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (grouped_index >= count) return;
  const std::size_t logical_index = grouped_index < long_count
                                        ? grouped_index * 2
                                        : (grouped_index - long_count) * 2 + 1;
  logical_output[logical_index] = grouped_output[grouped_index];
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 06_divergence_tail [--workload small|large]\n"; return 0; }
  try {
    const std::size_t count = problem_size(argc, argv, 4096, 1U << 25);
    const auto properties = require_course_gpu();
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count), expected(count), divergent_observed(count), grouped_observed(count);
    auto apply_work = [](float value, int iterations) {
      for (int iteration = 0; iteration < iterations; ++iteration) value = std::fma(value, 1.00001F, 0.00001F);
      return value;
    };
    for (std::size_t index = 0; index < count; ++index) {
      input[index] = 0.25F + static_cast<float>(index % 31) * 0.01F;
      expected[index] = apply_work(input[index], (index & 1U) == 0U ? 32 : 4);
    }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), divergent_output(count), grouped_input(count),
        grouped_output(count), grouped_scattered_output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    constexpr int threads = 256;
    const int blocks = static_cast<int>((count + threads - 1) / threads);
    const std::size_t long_count = (count + 1) / 2;
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto divergent_timing = benchmark_cuda([&] {
      divergent_work<<<blocks, threads>>>(device_input.get(), divergent_output.get(), count);
    });
    pack_grouped<<<blocks, threads>>>(device_input.get(), grouped_input.get(), count, long_count);
    CUDA_CHECK(cudaDeviceSynchronize());
    const auto grouped_core_timing = benchmark_cuda([&] {
      grouped_work<<<blocks, threads>>>(grouped_input.get(), grouped_output.get(), count, long_count);
    });
    const auto grouping_overhead_timing = benchmark_cuda([&] {
      pack_grouped<<<blocks, threads>>>(device_input.get(), grouped_input.get(), count, long_count);
      scatter_grouped<<<blocks, threads>>>(grouped_output.get(), grouped_scattered_output.get(), count, long_count);
    });
    const auto grouped_end_to_end_timing = benchmark_cuda([&] {
      pack_grouped<<<blocks, threads>>>(device_input.get(), grouped_input.get(), count, long_count);
      grouped_work<<<blocks, threads>>>(grouped_input.get(), grouped_output.get(), count, long_count);
      scatter_grouped<<<blocks, threads>>>(grouped_output.get(), grouped_scattered_output.get(), count, long_count);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(divergent_observed.data(), divergent_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(grouped_observed.data(), grouped_scattered_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, divergent_observed);
    check_close(expected, grouped_observed);
    check_close(divergent_observed, grouped_observed);
    const int waves = (blocks + properties.multiProcessorCount - 1) / properties.multiProcessorCount;
    const int tail_blocks = blocks - (waves - 1) * properties.multiProcessorCount;
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("06_divergence_tail", grouped_end_to_end_timing, count);
    print_timing("divergent", divergent_timing);
    print_timing("grouped_core_only", grouped_core_timing);
    print_timing("pack_and_scatter_overhead", grouping_overhead_timing);
    print_timing("grouped_end_to_end", grouped_end_to_end_timing);
    std::cout << "long_path_items=" << long_count
              << "\nshort_path_items=" << count - long_count
              << "\ngrouping_preserves_logical_work=true"
              << "\ndivergent_correctness=passed\ngrouped_correctness=passed"
              << "\noutputs_match_each_other=passed\nblocks=" << blocks
              << "\nmodeled_waves_one_block_per_sm=" << waves
              << "\ntail_blocks_one_block_per_sm=" << tail_blocks
              << "\nprimary_grouped_timing_includes_pack_and_scatter=true"
              << "\nverify_residency_with_profiler=true\n";
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/06_divergence_tail.sbatch --workload small

# Optional profiling
sbatch slurm/06_divergence_tail.sbatch --workload small --profiler all

Lab 07: Relate block size, live state, and occupancy limits

More resident warps can help hide latency, but a kernel's registers, local storage, and block geometry constrain residency. This lab sweeps thread-block sizes and separately increases per-thread state.

Complete source: labs/07_resource_sweep.cu
#include "common.cuh"

template <int state_count>
__global__ void resource_kernel(const float* input, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index >= count) return;
  float state[state_count];
#pragma unroll
  for (int item = 0; item < state_count; ++item) {
    state[item] = input[index] + static_cast<float>(item) * 0.0001F;
  }
#pragma unroll
  for (int iteration = 0; iteration < 8; ++iteration) {
#pragma unroll
    for (int item = 0; item < state_count; ++item) {
      state[item] = fmaf(state[item], 1.00001F, static_cast<float>(item + 1) * 0.00001F);
    }
  }
  float sum = 0.0F;
#pragma unroll
  for (int item = 0; item < state_count; ++item) sum += state[item];
  output[index] = sum;
}

template <int state_count>
void report_case(const float* input, float* output, std::size_t count, int threads) {
  const int blocks = static_cast<int>((count + threads - 1) / threads);
  int active_blocks = 0;
  CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(
      &active_blocks, resource_kernel<state_count>, threads, 0));
  cudaFuncAttributes attributes{};
  CUDA_CHECK(cudaFuncGetAttributes(&attributes, resource_kernel<state_count>));
  // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
  const auto timing = benchmark_cuda([&] {
    resource_kernel<state_count><<<blocks, threads>>>(input, output, count);
  });
  float expected = 0.0F;
  for (int item = 0; item < state_count; ++item) {
    float value = 0.01F + static_cast<float>(item) * 0.0001F;
    for (int iteration = 0; iteration < 8; ++iteration) {
      value = std::fma(value, 1.00001F, static_cast<float>(item + 1) * 0.00001F);
    }
    expected += value;
  }
  // Allocate host inputs and reference/output storage.
  std::vector<float> observed(2);
  // Copy completed device output back for validation outside kernel timing.
  CUDA_CHECK(cudaMemcpy(&observed[0], output, sizeof(float), cudaMemcpyDeviceToHost));
  CUDA_CHECK(cudaMemcpy(&observed[1], output + count - 1, sizeof(float), cudaMemcpyDeviceToHost));
  // Check the GPU output against the host reference before accepting timing.
  check_close({expected, expected}, observed);
  std::cout << "case threads=" << threads
            << " state_values=" << state_count
            << " registers_per_thread=" << attributes.numRegs
            << " local_bytes_per_thread=" << attributes.localSizeBytes
            << " active_blocks_per_sm=" << active_blocks
            << " resident_warps=" << static_cast<float>(active_blocks * threads) / 32.0F
            << " median_ms=" << timing.median_ms
            << " p90_ms=" << timing.p90_ms
            << " correctness=passed\n";
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 07_resource_sweep [--workload small|large]\n"; return 0; }
  try {
    const std::size_t count = problem_size(argc, argv, 4096, 1U << 24);
    const auto properties = require_course_gpu();
    std::vector<float> input(count, 0.01F);
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    std::cout << "schema=gpu-course-result/v1\nlab_id=07_resource_sweep\n";
    for (const int threads : {64, 128, 256, 512}) {
      report_case<4>(device_input.get(), output.get(), count, threads);
    }
    report_case<16>(device_input.get(), output.get(), count, 256);
    report_case<64>(device_input.get(), output.get(), count, 256);
    std::cout << "sm_count=" << properties.multiProcessorCount << "\ninspect_compiler_resource_usage=true\n";
    std::cout << "elements=" << count << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/07_resource_sweep.sbatch --workload small

# Optional profiling
sbatch slurm/07_resource_sweep.sbatch --workload small --profiler all

Lab 08: Double-buffer global-to-shared copies

Asynchronous copies can prepare the next tile while the current tile is being processed, but correct staging and enough independent computation are essential. This lab compares a serial tiled transform with a double-buffered Cooperative Groups copy pipeline.

Complete source: labs/08_async_pipeline.cu
#include "common.cuh"

#include <cooperative_groups.h>
#include <cooperative_groups/memcpy_async.h>
#include <charconv>
#include <limits>

namespace cg = cooperative_groups;

__global__ void serial_tiled_transform(const float* input, float* output, std::size_t count, int work_iterations) {
  extern __shared__ float tile[];
  auto block = cg::this_thread_block();
  const std::size_t tile_size = blockDim.x;
  const std::size_t tiles = (count + tile_size - 1) / tile_size;
  for (std::size_t tile_index = 0; tile_index < tiles; ++tile_index) {
    const std::size_t offset = tile_index * tile_size;
    if (offset + threadIdx.x < count) tile[threadIdx.x] = input[offset + threadIdx.x];
    block.sync();
    if (offset + threadIdx.x < count) {
      float value = tile[threadIdx.x];
      for (int iteration = 0; iteration < work_iterations; ++iteration) value = fmaf(value, 1.0001F, 0.0001F);
      output[offset + threadIdx.x] = value;
    }
    block.sync();
  }
}

__global__ void pipelined_transform(const float* input, float* output, std::size_t count, int work_iterations) {
  extern __shared__ float stages[];
  auto block = cg::this_thread_block();
  const std::size_t tile_size = blockDim.x;
  const std::size_t tiles = (count + tile_size - 1) / tile_size;
  if (tiles == 0) return;
  std::size_t current = 0;
  std::size_t valid = tile_size < count ? tile_size : count;
  cg::memcpy_async(block, stages, input, valid * sizeof(float));
  cg::wait(block);
  for (std::size_t tile = 0; tile < tiles; ++tile) {
    current = tile & 1U;
    const std::size_t next = current ^ 1U;
    const std::size_t offset = tile * tile_size;
    if (tile + 1 < tiles) {
      const std::size_t next_offset = offset + tile_size;
      const std::size_t remaining = count - next_offset;
      const std::size_t next_valid = tile_size < remaining ? tile_size : remaining;
      cg::memcpy_async(block, stages + next * tile_size, input + next_offset, next_valid * sizeof(float));
    }
    if (offset + threadIdx.x < count) {
      float value = stages[current * tile_size + threadIdx.x];
      for (int iteration = 0; iteration < work_iterations; ++iteration) value = fmaf(value, 1.0001F, 0.0001F);
      output[offset + threadIdx.x] = value;
    }
    cg::wait(block);
    block.sync();
  }
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) {
    std::cout << "Usage: 08_async_pipeline [--workload small|large] [--work-iterations N]\n"
              << "Default: sweep 0,8,32,128 FMAs per element. N: integer 0..1024.\n"
              << "One block; logical intensity excludes shared traffic and loop overhead.\n";
    return 0;
  }
  try {
    bool small = false, profile_seen = false;
    bool work_seen = false;
    // Allocate host inputs and reference/output storage.
    std::vector<int> work_sweep{0, 8, 32, 128};
    // Read workload and kernel controls before allocating buffers.
    for (int index = 1; index < argc; ++index) {
      const std::string argument(argv[index]);
      if (argument == "--workload") { small = parse_small_profile(argc, argv, index, profile_seen); }
      else if (argument == "--work-iterations" && !work_seen && index + 1 < argc) {
        const std::string value(argv[++index]);
        int work = 0;
        const auto parsed = std::from_chars(value.data(), value.data() + value.size(), work);
        if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || work < 0 || work > 1024)
          throw std::runtime_error("--work-iterations must be an integer from 0 through 1024");
        work_sweep = {work};
        work_seen = true;
      } else { throw std::runtime_error("unknown, duplicate, or incomplete argument: " + argument); }
    }
    require_course_gpu();
    // Both profiles exercise a partial final tile; keep the serial single-block
    // teaching workload bounded rather than presenting it as an HBM benchmark.
    const std::size_t count = small ? 4099 : (1U << 20) + 3;
    std::vector<float> input(count), expected(count), serial_observed(count), pipelined_observed(count);
    for (std::size_t index = 0; index < count; ++index)
      input[index] = 0.25F + static_cast<float>(index % 31) * 0.01F;
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), serial_output(count), pipelined_output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    constexpr int threads = 256;
    for (const int work_iterations : work_sweep) {
      for (std::size_t index = 0; index < count; ++index) {
        float value = input[index];
        for (int iteration = 0; iteration < work_iterations; ++iteration)
          value = std::fma(value, 1.0001F, 0.0001F);
        expected[index] = value;
      }
      auto serial = [&] {
        serial_tiled_transform<<<1, threads, threads * sizeof(float)>>>(device_input.get(), serial_output.get(), count, work_iterations);
      };
      auto pipelined = [&] {
        pipelined_transform<<<1, threads, 2 * threads * sizeof(float)>>>(device_input.get(), pipelined_output.get(), count, work_iterations);
      };
      // NaN sentinels expose missing writes independently in both variants.
      std::vector<float> sentinel(count, std::numeric_limits<float>::quiet_NaN());
      CUDA_CHECK(cudaMemcpy(serial_output.get(), sentinel.data(), count * sizeof(float), cudaMemcpyHostToDevice));
      CUDA_CHECK(cudaMemcpy(pipelined_output.get(), sentinel.data(), count * sizeof(float), cudaMemcpyHostToDevice));
      serial();
      CUDA_CHECK(cudaGetLastError());
      pipelined();
      CUDA_CHECK(cudaGetLastError());
      // Copy completed device output back for validation outside kernel timing.
      CUDA_CHECK(cudaMemcpy(serial_observed.data(), serial_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
      CUDA_CHECK(cudaMemcpy(pipelined_observed.data(), pipelined_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
      // Check the GPU output against the host reference before accepting timing.
      check_close(expected, serial_observed);
      check_close(expected, pipelined_observed);
      // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
      const auto serial_timing = benchmark_cuda(serial);
      const auto pipelined_timing = benchmark_cuda(pipelined);
      std::cout << "sweep_point_begin\nwork_iterations=" << work_iterations
                << "\nlogical_flops=" << 2ULL * count * work_iterations
                << "\nlogical_global_bytes=" << 2ULL * count * sizeof(float)
                << "\nlogical_flops_per_byte=" << static_cast<double>(work_iterations) / 4.0
                << "\nserial_shared_bytes=" << threads * sizeof(float)
                << "\npipelined_shared_bytes=" << 2 * threads * sizeof(float)
                << "\nsingle_block_mechanism=true\n";
      // Emit the measured summary for the job’s CUDA result adapter.
      print_result("08_async_pipeline", pipelined_timing, count);
      print_timing("serial", serial_timing);
      print_timing("pipelined", pipelined_timing);
      std::cout << "both_cpu_references=passed\npipeline_stages=2\nprime_steady_drain=true\nsweep_point_end\n";
    }
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/08_async_pipeline.sbatch --workload small

# Optional profiling
sbatch slurm/08_async_pipeline.sbatch --workload small --profiler all

Lab 09: Compare a library GEMM with a fused epilogue

The matrix multiplication itself may already be well served by a library, while a following bias and activation add extra work. This lab compares cuBLAS plus a separate bias/ReLU kernel with a source-pinned CUTLASS epilogue path.

Complete source: labs/09_library_epilogue.cu
#include "common.cuh"

#include <cublas_v2.h>

#ifdef COURSE_ENABLE_CUTLASS
#include <cutlass/cutlass.h>
#include <cutlass/epilogue/thread/linear_combination_relu.h>
#include <cutlass/gemm/device/gemm.h>
#include <cutlass/gemm/threadblock/threadblock_swizzle.h>
#include <cutlass/layout/matrix.h>
#include <cutlass/version.h>
#endif

#define CUBLAS_CHECK(call) do { if ((call) != CUBLAS_STATUS_SUCCESS) throw std::runtime_error(std::string(#call) + ": cuBLAS failure"); } while (false)

#ifdef COURSE_ENABLE_CUTLASS
#define CUTLASS_CHECK(call) do { if ((call) != cutlass::Status::kSuccess) throw std::runtime_error(std::string(#call) + ": CUTLASS failure"); } while (false)
static_assert(CUTLASS_MAJOR == 4 && CUTLASS_MINOR == 6 && CUTLASS_PATCH == 1,
              "Lab 09 is source-pinned to CUTLASS 4.6.1; review before changing it");

using CutlassEpilogue = cutlass::epilogue::thread::LinearCombinationRelu<
    float, 1, float, float>;
using CutlassGemm = cutlass::gemm::device::Gemm<
    float, cutlass::layout::RowMajor,
    float, cutlass::layout::RowMajor,
    float, cutlass::layout::RowMajor,
    float, cutlass::arch::OpClassSimt, cutlass::arch::Sm80,
    cutlass::gemm::GemmShape<128, 128, 8>,
    cutlass::gemm::GemmShape<32, 64, 8>,
    cutlass::gemm::GemmShape<1, 1, 1>,
    CutlassEpilogue,
    cutlass::gemm::threadblock::GemmIdentityThreadblockSwizzle<>, 2>;
#endif

__global__ void bias_relu(float* matrix, const float* bias, int rows, int columns) {
  const int index = blockIdx.x * blockDim.x + threadIdx.x;
  if (index < rows * columns) matrix[index] = fmaxf(matrix[index] + bias[index % columns], 0.0F);
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 09_library_epilogue [--workload small|large]\n"; return 0; }
  try {
    validate_simple_arguments(argc, argv);
    require_course_gpu();
    const bool small = small_profile(argc, argv);
    const int rows = small ? 128 : 1024;
    const int columns = small ? 192 : 1536;
    const int depth = small ? 96 : 768;
    const std::size_t left_elements = static_cast<std::size_t>(rows) * depth;
    const std::size_t right_elements = static_cast<std::size_t>(depth) * columns;
    const std::size_t output_elements = static_cast<std::size_t>(rows) * columns;
    // Allocate host inputs and reference/output storage.
    std::vector<float> left(left_elements), right(right_elements), bias(columns),
        bias_matrix(output_elements), expected(output_elements), cublas_observed(output_elements);
    for (int row = 0; row < rows; ++row) {
      for (int inner = 0; inner < depth; ++inner) {
        left[static_cast<std::size_t>(row) * depth + inner] =
            static_cast<float>((row * 3 + inner * 5) % 17 - 8) * 0.01F;
      }
    }
    for (int inner = 0; inner < depth; ++inner) {
      for (int column = 0; column < columns; ++column) {
        right[static_cast<std::size_t>(inner) * columns + column] =
            static_cast<float>((inner * 7 + column * 11) % 19 - 9) * 0.015F;
      }
    }
    for (int column = 0; column < columns; ++column) {
      bias[column] = static_cast<float>(column % 7 - 3) * 0.05F;
    }
    std::size_t positive_elements = 0;
    std::size_t clamped_elements = 0;
    for (int row = 0; row < rows; ++row) {
      for (int column = 0; column < columns; ++column) {
        float value = bias[column];
        for (int inner = 0; inner < depth; ++inner) {
          value += left[static_cast<std::size_t>(row) * depth + inner] *
                   right[static_cast<std::size_t>(inner) * columns + column];
        }
        const std::size_t index = static_cast<std::size_t>(row) * columns + column;
        bias_matrix[index] = bias[column];
        expected[index] = std::max(value, 0.0F);
        if (expected[index] > 0.0F) ++positive_elements;
        else ++clamped_elements;
      }
    }
    if (positive_elements == 0 || clamped_elements == 0) {
      throw std::runtime_error("reference data must exercise both ReLU branches");
    }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_left(left_elements), device_right(right_elements),
        device_output(output_elements), device_bias(columns);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_left.get(), left.data(), left_elements * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(device_right.get(), right.data(), right_elements * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(device_bias.get(), bias.data(), columns * sizeof(float), cudaMemcpyHostToDevice));
    cublasHandle_t handle{};
    CUBLAS_CHECK(cublasCreate(&handle));
    CUBLAS_CHECK(cublasSetMathMode(handle, CUBLAS_PEDANTIC_MATH));
    const float alpha = 1.0F;
    const float beta = 0.0F;
    const int threads = 256;
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto timing = benchmark_cuda([&] {
      // Row-major C=A*B is column-major C^T=B^T*A^T for the cuBLAS call.
      CUBLAS_CHECK(cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N,
                              columns, rows, depth, &alpha,
                              device_right.get(), columns,
                              device_left.get(), depth, &beta,
                              device_output.get(), columns));
      bias_relu<<<(output_elements + threads - 1) / threads, threads>>>(
          device_output.get(), device_bias.get(), rows, columns);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(cublas_observed.data(), device_output.get(), output_elements * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, cublas_observed);
    CUBLAS_CHECK(cublasDestroy(handle));
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("09_library_epilogue", timing, output_elements);
    print_timing("cublas_plus_separate_bias_relu", timing);
    std::cout << "rows=" << rows << "\ncolumns=" << columns << "\ndepth=" << depth
              << "\nrelu_positive_elements=" << positive_elements
              << "\nrelu_clamped_elements=" << clamped_elements
              << "\ncublas_baseline_correctness=passed\n";
#ifdef COURSE_ENABLE_CUTLASS
    DeviceBuffer<float> device_cutlass_source(output_elements), device_cutlass_output(output_elements);
    CUDA_CHECK(cudaMemcpy(device_cutlass_source.get(), bias_matrix.data(), output_elements * sizeof(float), cudaMemcpyHostToDevice));
    CutlassGemm::Arguments arguments(
        {rows, columns, depth},
        {device_left.get(), depth},
        {device_right.get(), columns},
        {device_cutlass_source.get(), columns},
        {device_cutlass_output.get(), columns},
        {1.0F, 1.0F});
    CUTLASS_CHECK(CutlassGemm::can_implement(arguments));
    CutlassGemm cutlass_gemm;
    CUTLASS_CHECK(cutlass_gemm.initialize(arguments));
    const auto cutlass_timing = benchmark_cuda([&] { CUTLASS_CHECK(cutlass_gemm()); });
    std::vector<float> cutlass_observed(output_elements);
    CUDA_CHECK(cudaMemcpy(cutlass_observed.data(), device_cutlass_output.get(), output_elements * sizeof(float), cudaMemcpyDeviceToHost));
    check_close(expected, cutlass_observed);
    print_timing("cutlass_fused_bias_relu", cutlass_timing);
    std::cout << "cutlass_version=4.6.1\ncutlass_fused_correctness=passed\ncomparison_scope=pedagogical-fp32-simt-epilogue\n";
#else
    std::cerr << "ERROR: required CUTLASS fused epilogue was not built; configure "
                 "with COURSE_ENABLE_CUTLASS=ON and the reviewed CUTLASS_ROOT\n";
    return 3;
#endif
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/09_library_epilogue.sbatch --workload small

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

Lab 10: Qualify an optional thread-block-cluster launch

Hopper thread-block clusters introduce an additional execution grouping beyond independent blocks. This optional lab checks that the declared cluster launch can run and produce the expected block IDs. Shared setup prepares its separate SM90a build; this GPU job qualifies the optional execution path.

Complete source: labs/10_hopper_cluster.cu
#include "common.cuh"

__global__ void cluster_probe(unsigned int* observed) {
#if __CUDA_ARCH__ >= 900
  if (threadIdx.x == 0) observed[blockIdx.x] = blockIdx.x;
#endif
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 10_hopper_cluster [--workload small|large]\n"; return 0; }
  try {
    validate_simple_arguments(argc, argv);
    require_course_gpu();
    constexpr int blocks = 4;
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<unsigned int> output(blocks);
    cudaLaunchConfig_t config{};
    config.gridDim = dim3(blocks);
    config.blockDim = dim3(128);
    cudaLaunchAttribute attribute{};
    attribute.id = cudaLaunchAttributeClusterDimension;
    attribute.val.clusterDim.x = 2;
    attribute.val.clusterDim.y = 1;
    attribute.val.clusterDim.z = 1;
    config.attrs = &attribute;
    config.numAttrs = 1;
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto timing = benchmark_cuda([&] {
      CUDA_CHECK(cudaLaunchKernelEx(&config, cluster_probe, output.get()));
    });
    // Allocate host inputs and reference/output storage.
    std::vector<unsigned int> observed(blocks);
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(observed.data(), output.get(), blocks * sizeof(unsigned int), cudaMemcpyDeviceToHost));
    for (int index = 0; index < blocks; ++index) if (observed[index] != static_cast<unsigned int>(index)) throw std::runtime_error("cluster launch output mismatch");
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("10_hopper_cluster", timing, blocks);
    std::cout << "architecture=sm_90a\ncluster_blocks=2\nportable_default=false\n";
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/10_hopper_cluster.sbatch --workload small

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

Lab 11: Fuse residual addition with row-wise RMS normalization

Residual addition followed by RMSNorm is a common transformer data path with opportunities to reuse values before writing them back to memory. This lab implements a small FP32 fused row kernel and validates it against a CPU reference.

Complete source: labs/11_residual_rmsnorm.cu
#include "common.cuh"

__global__ void fused_residual_rmsnorm(const float* input, const float* residual, const float* scale, float* output, int width) {
  extern __shared__ float shared[];
  const int row = blockIdx.x;
  const int column = threadIdx.x;
  float value = 0.0F;
  float square = 0.0F;
  if (column < width) {
    value = input[row * width + column] + residual[row * width + column];
    square = value * value;
  }
  shared[column] = square;
  __syncthreads();
  for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
    if (column < stride) shared[column] += shared[column + stride];
    __syncthreads();
  }
  const float inverse_rms = rsqrtf(shared[0] / static_cast<float>(width) + 1e-5F);
  if (column < width) output[row * width + column] = value * inverse_rms * scale[column];
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 11_residual_rmsnorm [--workload small|large]\n"; return 0; }
  try {
    const int rows = static_cast<int>(problem_size(argc, argv, 17, 4096));
    require_course_gpu();
    constexpr int width = 256;
    const std::size_t count = static_cast<std::size_t>(rows) * width;
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count), residual(count), scale(width), expected(count), observed(count);
    for (std::size_t index = 0; index < count; ++index) { input[index] = static_cast<float>(index % 31) / 31.0F; residual[index] = static_cast<float>(index % 17) / 37.0F; }
    std::fill(scale.begin(), scale.end(), 1.0F);
    for (int row = 0; row < rows; ++row) {
      float sum = 0.0F;
      for (int column = 0; column < width; ++column) { const float value = input[row * width + column] + residual[row * width + column]; sum += value * value; }
      const float inverse_rms = 1.0F / std::sqrt(sum / width + 1e-5F);
      for (int column = 0; column < width; ++column) expected[row * width + column] = (input[row * width + column] + residual[row * width + column]) * inverse_rms;
    }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), device_residual(count), device_scale(width), output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(device_residual.get(), residual.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(device_scale.get(), scale.data(), width * sizeof(float), cudaMemcpyHostToDevice));
    // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
    const auto timing = benchmark_cuda([&] {
      fused_residual_rmsnorm<<<rows, width, width * sizeof(float)>>>(device_input.get(), device_residual.get(), device_scale.get(), output.get(), width);
    });
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(observed.data(), output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, observed);
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("11_residual_rmsnorm", timing, count);
    std::cout << "accumulation_dtype=float32\nepsilon=1e-5\n";
    std::cout << "rows=" << rows << "\nwidth=" << width << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}
# Normal execution
sbatch slurm/11_residual_rmsnorm.sbatch --workload small

# Optional profiling
sbatch slurm/11_residual_rmsnorm.sbatch --workload small --profiler all

Lab 12: Assemble a kernel acceptance report

A custom kernel is ready only when its correctness, memory safety, performance mechanism, and application impact are understood. This capstone provides a two-kernel affine-plus-tanh baseline and a fused candidate with matched inputs.

Complete source: labs/12_capstone.cu
#include "common.cuh"

__global__ void baseline_first(const float* input, float* temporary, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) temporary[index] = input[index] * 1.25F + 0.5F;
}

__global__ void baseline_second(const float* temporary, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) output[index] = tanhf(temporary[index]);
}

__global__ void fused_candidate(const float* input, float* output, std::size_t count) {
  const std::size_t index = static_cast<std::size_t>(blockIdx.x) * blockDim.x + threadIdx.x;
  if (index < count) output[index] = tanhf(input[index] * 1.25F + 0.5F);
}

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) { std::cout << "Usage: 12_capstone [--workload small|large] --variant-order baseline-first|candidate-first\n"; return 0; }
  try {
    bool small = false, profile_seen = false;
    std::string variant_order;
    // Read workload and kernel controls before allocating buffers.
    for (int index = 1; index < argc; ++index) {
      const std::string argument(argv[index]);
      if (argument == "--workload") small = parse_small_profile(argc, argv, index, profile_seen);
      else if (argument == "--variant-order" && index + 1 < argc) variant_order = argv[++index];
      else throw std::runtime_error("unsupported or incomplete argument: " + argument);
    }
    if (variant_order != "baseline-first" && variant_order != "candidate-first") {
      throw std::runtime_error("--variant-order is required and must be baseline-first or candidate-first");
    }
    require_course_gpu();
    const std::size_t count = small ? 4099 : 1U << 25;
    // Allocate host inputs and reference/output storage.
    std::vector<float> input(count), expected(count), baseline_observed(count), candidate_observed(count);
    for (std::size_t index = 0; index < count; ++index) { input[index] = static_cast<float>(static_cast<int>(index % 101) - 50) / 50.0F; expected[index] = std::tanh(input[index] * 1.25F + 0.5F); }
    // Allocate device buffers; their owners release them when this scope ends.
    DeviceBuffer<float> device_input(count), temporary(count), baseline_output(count), candidate_output(count);
    // Copy initialized inputs to the GPU before measuring kernels.
    CUDA_CHECK(cudaMemcpy(device_input.get(), input.data(), count * sizeof(float), cudaMemcpyHostToDevice));
    constexpr int threads = 256;
    const int blocks = static_cast<int>((count + threads - 1) / threads);
    TimingSummary baseline_timing{};
    TimingSummary candidate_timing{};
    const auto measure_baseline = [&] {
      // Warm up, then time GPU work with the shared synchronized CUDA-event helper.
      baseline_timing = benchmark_cuda([&] {
        baseline_first<<<blocks, threads>>>(device_input.get(), temporary.get(), count);
        baseline_second<<<blocks, threads>>>(temporary.get(), baseline_output.get(), count);
      });
    };
    const auto measure_candidate = [&] {
      candidate_timing = benchmark_cuda([&] {
        fused_candidate<<<blocks, threads>>>(device_input.get(), candidate_output.get(), count);
      });
    };
    if (variant_order == "baseline-first") {
      measure_baseline();
      measure_candidate();
    } else {
      measure_candidate();
      measure_baseline();
    }
    // Copy completed device output back for validation outside kernel timing.
    CUDA_CHECK(cudaMemcpy(baseline_observed.data(), baseline_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    CUDA_CHECK(cudaMemcpy(candidate_observed.data(), candidate_output.get(), count * sizeof(float), cudaMemcpyDeviceToHost));
    // Check the GPU output against the host reference before accepting timing.
    check_close(expected, baseline_observed);
    check_close(expected, candidate_observed);
    // Emit the measured summary for the job’s CUDA result adapter.
    print_result("12_capstone", candidate_timing, count);
    print_timing("baseline", baseline_timing);
    print_timing("candidate", candidate_timing);
    std::cout << "trial_kind=one-fresh-process\nvariant_order=" << variant_order
              << "\nbaseline_correctness=passed\ncandidate_correctness=passed\n"
              << "sanitizer=run-separately\nprofiler=run-separately\n"
              << "end_to_end_claim=pending-integration\n"
              << "publication_decision=pending-three-independent-run-aggregation\n";
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) { std::cerr << "ERROR: " << error.what() << '\n'; return 2; }
}

The normal command below runs one kernel comparison. For three counterbalanced fresh-process trials, replace --variant-order baseline-first with --experiment trials in the normal submission. The supplied experiment does not implement or time application integration.

# Normal execution
sbatch slurm/12_capstone.sbatch --workload small --variant-order baseline-first

# Optional profiling
sbatch slurm/12_capstone.sbatch --workload small --variant-order baseline-first --profiler all

Lab 13: Build and identify the H100 CUDA execution target

A custom kernel depends on a compiler, target architecture, runtime, and physical device that must agree. This lab establishes the required H100/SM90 execution target before any optimization experiment.

Complete source: labs/13_h100_preflight.cu
#include "common.cuh"

#include <iostream>

int main(int argc, char** argv) {
  if (wants_help(argc, argv)) {
    std::cout << "Usage: 13_h100_preflight [--workload small|large]\n";
    return 0;
  }
  try {
    // Validate controls and query the allocated GPU before accepting readiness.
    validate_simple_arguments(argc, argv);
    const auto properties = require_course_gpu();
    int runtime = 0;
    int driver = 0;
    // Read installed runtime and driver API versions; this is not a timing test.
    CUDA_CHECK(cudaRuntimeGetVersion(&runtime));
    CUDA_CHECK(cudaDriverGetVersion(&driver));
    // Emit observed properties for the job's CUDA result adapter.
    std::cout << "schema=gpu-course-result/v1\nlab_id=13_h100_preflight\n"
              << "compute_capability=" << properties.major << '.' << properties.minor << '\n'
              << "sm_count=" << properties.multiProcessorCount << "\nglobal_memory_bytes=" << properties.totalGlobalMem << '\n'
              << "runtime_version=" << runtime << "\ndriver_api_version=" << driver << '\n';
    std::cout << "course_checks=passed\n";
    return 0;
  } catch (const std::exception& error) {
    std::cerr << "ERROR: " << error.what() << '\n';
    return 2;
  }
}
# Normal execution
sbatch slurm/13_h100_preflight.sbatch --workload small

# Optional profiling
sbatch slurm/13_h100_preflight.sbatch --workload small --profiler all

Course guides

Getting started

Read the course · Estimated guided time: 36 hours.

Learn when a custom kernel is justified, then build and validate it against a library reference. Take GPU Fundamentals and GPU Performance Optimization first. Read GPU Performance Tools for profiling and PyTorch for GPU Performance Engineering when you need a tensor-reading refresher. Learner code here is CUDA C++20.

Learning route

Start with a library-first decision, a reproducible SM90 build and one correct vector kernel. Learn validation, memory, reduction and resource limits before combining mechanisms in pipelines and RMSNorm.

  • After Lesson 4, demonstrate an edge case, explain memcheck's scope and select one profiling question. Revisit racecheck/synccheck for shared-memory work.
  • After Lesson 10, distinguish limited resources from uneven work.
  • Lesson 14 completes the required single-GPU path. Lessons 15–16 are optional. Lab 10's Hopper thread-block clusters stay inside one GPU; cross-GPU work belongs to Advanced Labs.

Before the first lab

Use one full H100 and the approved CUDA runtime from the Lab Guide and Versions and environment. Preparation compiles SM90 binaries and Lab 10's separate SM90a target without a GPU; these builds are not GPU qualified. Use Lab 13 in a GPU allocation before the other kernel labs:

sbatch slurm/13_h100_preflight.sbatch --workload small

A supported H200 substitute establishes evidence only for that observed device, not H100 performance. Keep the same GPU identity across capstone trials. CUTLASS is required for Lab 09's fused bias/ReLU reference; disabling it is not acceptance evidence. The optional container build-and-test exercise is described in the Lab Guide.

Completion

Preserve independent reference checks, relevant sanitizer results, focused profiler evidence and repeated uninstrumented trials. Select memcheck, racecheck, initcheck or synccheck for the failure being investigated; sanitizer timings are diagnostic overhead. Distributed CUDA/NCCL is outside this course.

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

Reference guides

Versions and environment

Completed prepared-environment runs

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

Lab 13 records CUDA runtime and driver API version 13030 on compute capability 9.0. Those fields identify the observed runtime/API, not the compiler, CMake version or a qualified development-image digest.

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

H100 target and installation candidates

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

ComponentCourse targetEvidence status
C++ languageC++20Source contract established
CUDA toolkitManaged native CUDA 13.3.0Checksum-pinned archives; H100 activation pending
Required architectureSM90Compilation and runtime pending
Lab 10 architectureSM90aPrepared separately; activation pending
CMakeSite/toolkit-compatible current releaseConfiguration pending on Linux target
CUB and cuBLASToolkit-providedBuild/runtime pending
CUTLASS4.6.1 source contract for required Lab 09Exact source checkout, CUDA build, and H100 runtime qualification pending
GPUOne full non-MIG H100Live validation pending

Do not describe native toolkit/build identities or the CUTLASS revision as qualified until that configuration passes the relevant target checks. The optional teaching container also requires its own immutable image identity. Label untested configurations as candidates. Report compiler results, sanitizer results and speedups only from checks actually executed in the declared environment.

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: every executable lab uses one full, non-MIG GPU. Qualify the required path on H100; evidence from the supported H200 substitute applies only to that observed hardware. Lab 10's optional SM90a thread-block clusters operate inside one GPU and require their own qualification.

Use the course for lesson order. This checklist qualifies the local runtime and experiments; optional branches do not gate earlier lessons.

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.

  1. Record the prepared managed CUDA 13.3.0 toolkit and per-lab build receipts.
  2. Verify the prepared CUTLASS 4.6.1 source and native SM90 binaries. Setup compiles without submitting GPU jobs or running CTest.
  3. Submit Lab 13 and confirm one full non-MIG H100 at compute capability 9.0.
  4. Run Labs 01–09 and 11–12 through the one-node launcher.
  5. Run the matching slurm/LAB.sbatch --experiment sanitizer --sanitizer memcheck job for every required binary; submit the same launcher with racecheck, initcheck, or synccheck where the lab uses the relevant behavior.
  6. Use Nsight Systems to locate the path, then Nsight Compute on one selected kernel and metric set.
  7. Enable Lab 10 only after the CUDA 13.3 SM90a profile is qualified.
  8. Repeat accepted performance candidates across independent trials and keep live status pending for any unexecuted profile.

Build and correctness commands

Run from this course root after shared preparation. Default setup includes the dependencies for the optional container teaching exercise below. Submitting it runs CTest in a unique build/run-<build-job-id> directory. Native lab jobs use their setup-managed builds.

python3 tools/validate_course.py
bash slurm/build_and_test.sbatch --help
sbatch slurm/build_and_test.sbatch

Independently of the optional container exercise, run the device and correctness labs with their prepared runtime:

sbatch slurm/13_h100_preflight.sbatch
sbatch slurm/01_vector_add.sbatch --workload small
sbatch slurm/02_fused_elementwise.sbatch --workload small
sbatch slurm/03_tiled_transpose.sbatch --workload small
sbatch slurm/04_reduction.sbatch --workload small
sbatch slurm/05_tiled_stencil.sbatch --workload small
sbatch slurm/06_divergence_tail.sbatch --workload small
sbatch slurm/07_resource_sweep.sbatch --workload small
sbatch slurm/08_async_pipeline.sbatch --workload small
sbatch slurm/09_library_epilogue.sbatch --workload small
sbatch slurm/11_residual_rmsnorm.sbatch --workload small

Every kernel must agree with its reference for the declared shapes and tolerances, including tails and boundary cases. A completed launch is not proof of correct output. Lab 09 must run the real library/fused epilogue comparison; an unavailable CUTLASS build is a blocked gate, not a substitute.

Lab 08 now runs four work points (0, 8, 32 and 128 FMAs per element). Its smoke input has 4099 elements to exercise a partial final tile. CTest also runs zero and maximum work explicitly. Inspect both independent CPU-reference checks and the serial/pipeline distributions at each point. For focused sanitizer or profiler runs append --work-iterations 32 (or zero to exercise the no-compute case). See the pipeline walkthrough.

Sanitizer, profiler, and capstone commands

Choose a new private output prefix for each profiler run. The following uses one example kernel; repeat the applicable sanitizer for every required binary.

sbatch slurm/03_tiled_transpose.sbatch --experiment sanitizer --sanitizer memcheck --workload small
sbatch slurm/03_tiled_transpose.sbatch --experiment sanitizer --sanitizer racecheck --workload small
sbatch slurm/08_async_pipeline.sbatch --experiment sanitizer --sanitizer synccheck --workload small
sbatch slurm/08_async_pipeline.sbatch --experiment sanitizer --sanitizer memcheck --workload small
sbatch slurm/08_async_pipeline.sbatch --experiment sanitizer --sanitizer racecheck --workload small
sbatch slurm/03_tiled_transpose.sbatch --profiler nsys --workload small
sbatch slurm/03_tiled_transpose.sbatch --profiler ncu --workload small
sbatch slurm/12_capstone.sbatch --experiment trials --workload small

Require zero relevant sanitizer errors. A missing profiler or counter permission leaves that evidence uncollected. Preserve uninstrumented timing distributions separately from profiling and use at least three independent capstone runs. Optional cluster/SM90a exercises need their own qualified build and architecture statement; they are excluded from the core guided-hour total.

Optional thread-block-cluster qualification

Lab 10: Qualify an optional thread-block-cluster launch qualifies the setup-managed SM90a target. Keep its execution evidence and native toolkit identity separate from the required SM90 suite.

Lab mechanisms and evidence

Lab 08: sweep compute work while holding data movement fixed

A two-stage copy pipeline alternates between two shared-memory buffers: one holds the tile being processed while the other receives a later tile. This walkthrough extends Lesson 11 and the Lab 08 guide, which define the cooperating thread group and its ownership protocol.

Objective: learn when useful computation can hide a tile copy and when a two-stage pipeline merely adds synchronization. The async-copy lab compares a serial path that loads and processes one shared-memory tile at a time with a two-buffer Cooperative Groups copy pipeline. Both apply the same recurrence to every input and are checked independently against a CPU std::fma reference.

Derive the intensity sweep

Each element is a four-byte float read once and written once. The logical global traffic is therefore eight bytes per element. One recurrence iteration uses one fused multiply-add (FMA): multiply two values, add a third and round once at the end. Its multiplication and addition count as two FLOPs. With K iterations, logical intensity is 2K / 8 = K/4 FLOPs per byte. The default sweep uses:

FMA iterations per elementLogical FLOPs/elementLogical bytes/elementLogical FLOPs/byte
0080
81682
326488
128256832

These values exclude shared-memory traffic, loop/address instructions and transaction padding. Caches can change actual HBM traffic. This is a useful algorithm-level horizontal-axis estimate, not measured roofline intensity. The recurrence has a dependency chain per lane, so instruction latency and eligible warps also matter; this is not an independent-FMA peak-compute test.

Given four tiles, suppose load and compute require five and eight time units per tile. Serial execution needs 52 units. A perfect two-stage schedule would need one five-unit prime followed by four eight-unit compute stages: 37 units. These time units belong to an idealized model; they are not measured microseconds. Change to less than five units of compute and copy latency becomes harder to hide. Extra wait, barrier and buffer-management costs can erase either predicted benefit.

Run the bounded experiment

With the prepared Lab 08 runtime, submit:

sbatch slurm/08_async_pipeline.sbatch --workload small
sbatch slurm/08_async_pipeline.sbatch --workload small --work-iterations 32

The first command runs all four work points. The second isolates one point for profiling. --work-iterations accepts an integer from zero through 1024; invalid, duplicate or incomplete arguments fail before GPU execution. Omit --workload small for the larger bounded input. Smoke uses 4099 elements and full uses 1,048,579, so both include a partial final tile rather than testing only perfect multiples of the 256-thread block.

  1. Predict intensity for each point and record the expected limiting factor.
  2. Require independent reference correctness for both variants. NaN sentinels expose unwritten output elements. FP32 comparisons use rtol=1e-5 and atol=1e-6; neither variant is its own oracle.
  3. Read each sweep_point_begin/sweep_point_end group separately. It records work, bytes, logical intensity, shared memory, and serial/pipeline timing distributions after five warm-ups and 20 measured samples.
  4. Run Compute Sanitizer memcheck, racecheck and synccheck through the sanitizer procedure, including zero-work and partial-tile cases. Correct values alone do not prove safe synchronization.
  5. Profile a single work point to investigate waits and memory movement. Collect primary timing without profiler instrumentation. Keep only claims demonstrated on the actual H100 and pinned compiler.
Explain stage ownership

The pipeline primes stage zero and waits before consuming it. During steady state it copies the next tile into the alternate stage, computes the current tile, then waits and synchronizes before rotating. The final tile drains without issuing another copy. The serial baseline uses one 1024-byte shared tile; the pipeline uses 2048 bytes. All block participants follow the cooperative copy/wait protocol, including the partial-tile case. Alignment and transfer size determine which copy implementation is selected; never infer a particular hardware instruction just from an asynchronous API name. Consult the official asynchronous-copy guidance.

Interpretation and review

Both variants deliberately launch one block and loop through its tiles. This isolates pipeline mechanics but does not fill all H100 SMs or measure device HBM bandwidth. Extending it to a multi-block application introduces residency, tail, memory-system and end-to-end questions; do not multiply a one-block timing ratio into a whole-device speedup.

At zero work, expect to investigate pure movement and synchronization overhead, rather than assuming the pipeline will be faster. At large work, compute dependencies may dominate both variants. If timing regresses, retain that point and explain it from the evidence. Review answer: overlap requires independent useful work, safe stage reuse and affordable buffering; the default four-point sweep tests that hypothesis instead of asserting it.

Benchmark worksheet

Record the operation contract, shapes, alignment, dtype, tolerance, grid and block, compiler/toolkit/image, architecture flags, library versions, warm-up, CUDA-event samples, effective bandwidth or operation rate, registers, shared memory, spills, sanitizer result, profiler evidence, end-to-end result, portability boundary, and keep/reject decision.

Use FP32 rtol=1e-5, atol=1e-6 and FP16/BF16 rtol=1e-2, atol=1e-2 unless the operation documents a stricter criterion. Never report only the fastest sample.

Comparison worksheet

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

FieldBaselineCandidate / observation
Date and random course run ID (keep artifact location private)To recordTo record
Lab, source/commit identity, exact arguments, single changeTo recordTo record
H100 SKU, node/rank count, MIG state, topology class (no asset IDs)To recordTo record
Approved environment lock or immutable image; driver/CUDA/framework/NCCL/Slurm versionsTo recordTo record
Input shapes, layouts, dtype, seeds, batch/workload semanticsTo recordTo record
Primary metric, timer, included operations, completion condition, correctness/quality tolerancesTo recordTo record
Warm-up, measured iterations, three independent trial IDs and orderTo recordTo record
Correctness result and maximum error; missing/non-finite dataTo recordTo record
Raw timing distribution, minimum, median, p90/p95 and dispersionTo recordTo record
Baseline allocated memory, peak allocated/reserved memory, incremental peakTo recordTo record
Sanitized profiler observation, selected range/kernel, tool versionTo recordTo record
Supporting observation and disconfirming controlTo recordTo record
Decision: keep, reject, or investigate; limitation and next experimentTo recordTo record
Operation contract, boundary cases, aliasing, layouts and numerical toleranceTo recordTo record
CUDA/compiler/container/CUTLASS versions, SM90 or qualified SM90a targetTo recordTo record
Reference/library result, memcheck/racecheck/initcheck/synccheck evidenceTo recordTo record
Registers, spills, shared memory, occupancy, selected profiler evidenceTo recordTo record
Kernel and full-application latency, launch/traffic calculation and maintenance decisionTo recordTo record

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

Evidence and privacy

Keep raw build logs, original profiler reports, scheduler output, device inventory, and runtime artifacts private. Public summaries may include official component versions, H100 family, compute capability, shapes, metrics, correctness, and the scoped decision. Remove usernames, absolute paths, hostnames, scheduler identifiers, private image registries, endpoints, credentials, and customer or model data before publication.

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.

Where to Go Next

These optional directions combine recent programming tools with established advanced kernel designs. They do not replace the CUDA C++20 labs, change the pinned development environment or add completion requirements. Python-based tools below are comparative reading only; all learner kernel implementations in this course remain C++. Start with the Hopper design, then compare abstraction levels or newer hardware.

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

  • Hopper warp-specialized persistent kernels

    Warp specialization assigns different warps to tasks such as loading data and performing matrix operations. A persistent design lets resident blocks process multiple work tiles rather than finishing after one tile. Together, these ideas extend double buffering into explicit scheduling of producers, consumers and work distribution. Investigate: Which event proves a shared-memory buffer can be reused, and what happens if one stage becomes the bottleneck? Scope: Established advanced CUTLASS design relevant to H100. Exact kernel variants have architecture and toolchain requirements; Hopper and Blackwell implementations do not use identical schedules. Study CUTLASS Hopper warp specialization.

  • CUDA Tile C++ and compiler-managed tiles

    CUDA Tile expresses operations on tiles of data while the compiler manages much of their mapping to threads, memory movement and asynchronous execution. It offers a different abstraction from manually scheduling SIMT threads, not a guarantee that arbitrary code becomes fast. This is a next step from the course's optional Tile lesson into portability and control trade-offs. Investigate: Which tuning responsibilities move into the compiler, and which shape, layout and numerical choices remain yours? Scope: Recent CUDA 13.3 direction; NVIDIA documents Hopper support. It remains an optional, separately qualified toolchain path, not a required change to the C++20 baseline. Explore CUDA Tile and CUDA Tile C++ compilation.

  • CuTe DSL and explicit kernel abstractions

    CuTe DSL is a Python-based domain-specific language for expressing GPU kernels using layouts, tensor operations and architecture-aware primitives. It offers a way to study the same mapping decisions encountered in CUTLASS C++ through a different authoring interface. It is not ordinary eager Python execution on the GPU. Investigate: How much control does the author retain over layouts, asynchronous pipelines and matrix instructions compared with CUDA Tile? Scope: Evolving CUTLASS tooling. Documented coverage includes Hopper warpgroup operations and separate Blackwell primitives; consult limitations for the chosen release. Comparative reading only, not a Python lab. Read the CuTe DSL overview.

  • CompileIQ and compiler-configuration autotuning

    CompileIQ searches compiler configuration choices for a specific workload. Instead of changing the algorithm, it explores how compiler decisions such as register allocation and instruction scheduling affect generated code. A good benchmark objective must reject incorrect results and avoid choosing a configuration that only benefits one convenient input. Investigate: Does a winning configuration remain correct and useful across held-out shapes, and does its benefit repay the search cost? Scope: Recent tooling introduced with CUDA 13.3. Its search orchestration uses Python, so this is reading-only here. Compiler version, GPU, numerical checks and repeatable timing must be recorded; no speedup is assumed. Read NVIDIA's CompileIQ introduction.

  • Blackwell tensor memory and fifth-generation matrix instructions

    Blackwell SM100 introduces tensor memory (TMEM), an on-chip storage space used by its fifth-generation matrix multiply-accumulate instructions, known as tcgen05. Placing accumulators there changes the relationship between matrix operations, registers and synchronization. This is an instruction-level extension to the general architecture comparison in Fundamentals. Investigate: Which accumulator-lifetime and synchronization assumptions must change when moving from a Hopper matrix kernel to this design? Scope: Blackwell-specific study, not available on H100/SM90. Do not assume every Blackwell device supports every SM100 primitive; select the documented architecture target and treat architecture-specific binaries accordingly. Study the tcgen05 programming model.

Glossary

Aliasing
Two pointers or tensor views referring to overlapping storage; it changes safe read/write ordering.
Atomic update
An indivisible update to a memory location at the operation’s supported scope; it does not establish arbitrary ordering for other memory accesses.
Bank conflict
Serialization when lanes access different words in the same bank; supported same-word broadcasts are not bank conflicts.
Barrier
A synchronization point that coordinates participating threads and the memory visibility guaranteed by that primitive and scope.
Block
A group of CUDA threads scheduled together on one streaming multiprocessor; a block does not split across SMs.
Boundary handling
Rules for safe and correct computation where a neighborhood or tile extends beyond the input.
Bounds mask
A condition that excludes out-of-range elements from a load, store or computation, especially in a partial tile.
CCCL
CUDA Core Compute Libraries; NVIDIA’s collection including Thrust, CUB and libcu++ for CUDA C++ programming.
CMake
A build-system generator used here to configure CUDA targets and produce their build files.
Coalescing
Combining warp memory requests into efficient transactions.
Compute Sanitizer
NVIDIA’s CUDA correctness tools for detecting supported memory-access, initialization, synchronization and shared-memory hazards.
Constant memory
CUDA device memory read through a dedicated cache; uniform addresses across a warp can use broadcast, while different addresses can require separate requests.
Cooperative Groups
A CUDA C++ programming model for defining groups of threads and coordinating work within those groups.
CTest
CMake's test driver, used here to run the checks registered by the build.
CUB
CUDA C++ library of tuned parallel primitives.
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.
CUDA Tile
NVIDIA's tile-based GPU programming approach, in which the compiler maps tile operations to hardware; this course treats CUDA Tile C++ as an optional toolchain-dependent lesson.
CUTLASS
CUDA Templates for Linear Algebra Subroutines; templates for high-performance linear algebra and fused epilogues.
DCGM
NVIDIA Data Center GPU Manager; provides GPU health and telemetry facilities.
Distributed shared memory
Cluster-scoped access to the shared-memory regions of cooperating thread blocks.
Epilogue
Work applied to matrix-accumulation results before final storage.
Epsilon
Small positive stabilizer added before the RMSNorm inverse square root.
FMA
Fused multiply-add, a × b + c with one final rounding; conventionally counted as two FLOPs.
FP32
32-bit floating point; the input, accumulator and output types must be stated separately when evaluating a kernel.
Fusion
Combining operations so intermediate traffic or launch overhead is reduced.
GEMM
General matrix multiplication, commonly including alpha/beta scaling of the product and existing output.
Grid-stride loop
Indexing pattern in which each thread processes elements separated by the total grid width.
Halo
Neighboring input values outside a tile's output region needed for a stencil's boundary outputs.
HBM
High-bandwidth memory; the GPU's large off-chip device memory, distinct from registers and shared memory.
Host / device
The CPU-side program and the GPU-side execution environment; CUDA applications normally use both.
Host-facing API
The callable interface through which a consumer supplies data, shapes and an execution stream to a GPU implementation.
ILP
Instruction-level parallelism; independent instructions within one thread that can make progress without waiting on one another’s results.
Initcheck
Compute Sanitizer’s checker for reads of uninitialized device global memory.
Kernel
A device function launched as a grid of thread blocks; a library API may launch several kernels and is not itself necessarily one kernel.
Layout
The mapping from logical tensor indices to storage addresses.
Leading dimension
The physical stride used to reach the next matrix row or column under the selected layout.
Maintained library
A supported implementation such as cuBLAS, cuDNN, CUB/CCCL or CUTLASS that should be evaluated before owning a custom implementation.
Memcheck
Compute Sanitizer’s checker for memory-access errors such as out-of-bounds or misaligned accesses, with allocation/leak diagnostics.
NaN
Not a number; a floating-point value representing an undefined numerical result, such as 0/0.
Nsight Compute
A kernel profiler used for selected-kernel metrics, including roofline, traffic, instruction, scheduler, stall, and occupancy evidence.
Nsight Systems
A system profiler used to inspect the temporal relationship among CPU work, CUDA APIs, kernels, copies, synchronization, NVTX ranges, and communication.
Numerical tolerance
The allowed difference between a computed result and its correctness reference.
nvcc
NVIDIA's CUDA compiler driver, which coordinates compilation of CUDA source and host code.
NVTX
NVIDIA Tools Extension Library, an annotation API for named markers and ranges; it does not synchronize or time GPU work by itself.
Occupancy
Active resident warps divided by the SM's maximum resident-warps limit, constrained by block resources; not a speed score.
Pipeline stage
One shared-memory buffer and synchronization state used while alternating asynchronous production and computation.
PTX / SASS
Parallel Thread Execution, an intermediate GPU instruction representation / target-specific machine instructions.
PTXAS
CUDA assembler component that produces target device code and compiler resource reports.
PyTorch Profiler
The framework profiler that attributes CPU and CUDA activity, calls, shapes, memory, and stacks to PyTorch operators.
Racecheck
Compute Sanitizer’s checker for shared-memory data-access hazards; it is not a general proof of race freedom.
RAII
Resource Acquisition Is Initialization; C++ resource ownership and cleanup tied to an object’s lifetime, which must outlast asynchronous uses of that resource.
Reduction
Combining a collection of values into a smaller result, such as a sum.
Register spill
Compiler placement of thread-local values into local memory.
ReLU
Rectified linear unit; an element-wise activation that returns the larger of zero and its input.
RMSNorm
Normalization by root mean square, followed by learned scaling, without subtracting the mean.
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 threads; warp instructions operate on participating lanes with per-thread values.
SM
Streaming multiprocessor, the GPU unit that schedules warps and contains registers, shared memory, and execution resources.
SM90
Baseline compute capability 9.0 target used for H100; future-device compatibility still depends on the included PTX/cubin and the CUDA compatibility contract.
SM90a
Architecture-accelerated Hopper target with non-forward-compatible features.
Source package
Source, headers, build instructions, tests and licensing that allow a consumer to build an implementation for a documented toolchain and GPU target.
Stencil
An operation that computes each output using a local neighborhood of input values.
Synccheck
Compute Sanitizer’s checker for invalid uses of supported synchronization primitives.
Synchronization
A dependency or wait that ensures required work has completed before dependent work proceeds.
Tail wave
A final partially filled grid wave; its idle fraction depends on the remaining blocks and resource-limited capacity.
Tensor Core
Specialized matrix-multiply-accumulate hardware used only when the operation and generated kernel select a supported path.
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 smaller region of data handled cooperatively by an implementation.
TMA
Tensor Memory Accelerator, Hopper hardware that moves supported tensor regions asynchronously using a descriptor that specifies their layout and dimensions.
Warp
32 CUDA threads scheduled as an execution group on current NVIDIA GPUs covered by this course.
Warp shuffle
Direct register exchange among participating lanes in one warp, with an explicit participation mask, matching calls by named non-exited threads, and valid participating source lanes.

Official references

  1. CUDA programming model: host code and device kernels
  2. NVIDIA CUDA compiler driver: host/device compilation and libraries
  3. PyTorch custom C++ and CUDA operators: optional framework integration
  4. CUDA Programming Guide
  5. CUDA C++ Best Practices Guide
  6. NVIDIA Hopper Tuning Guide
  7. Compute Sanitizer
  8. Nsight Compute Profiling Guide
  9. Nsight Systems User Guide
  10. CUDA asynchronous copies
  11. CUDA C++ thread-block clusters
  12. CUDA Runtime cluster launch attributes
  13. CUDA Tile C++ principles
  14. NVIDIA CUB
  15. NVIDIA CUTLASS
  16. NVIDIA CUTLASS 4.6.1 release
  17. cuBLAS documentation
  18. cuDNN documentation, supported primitives and official samples
  19. CMake CUDA architectures
  20. CMake CUDA architecture initialization
  21. Slurm sbatch
  22. PTX and target-specific code generation
  23. CUDA thread-block cluster co-scheduling and distributed shared memory
  24. CUDA warp shuffle participation masks
  25. Study CUTLASS Hopper warp specialization
  26. Explore CUDA Tile
  27. CUDA Tile C++ compilation
  28. Read the CuTe DSL overview
  29. Read NVIDIA's CompileIQ introduction
  30. Study the tcgen05 programming model
  31. asynchronous-copy guidance