Unit 6 of 10 · about 3 hours · derive, implement

Divergence, predication, grid-stride loops and bounds

Bounds checks are part of correctness, not an optional performance cost. A grid-stride loop decouples coverage from launch size while preserving adjacent-lane addressing within each iteration.

You'll be able to

  • Predict divergent paths and useful active lanes for a warp, including a partial tail.
  • Implement a bounds-safe grid-stride map with zero-size handling and overflow-aware indexing.
  • Use generated code to distinguish branches from predicated instructions rather than guessing from source syntax.

Covers

Control divergence, predication and reconvergenceGrid-stride loops, tails, zero sizes and bounds safety
1

Read

In this order, only the parts listed

0 of 3 done

  1. PMPP, 4th edition: control divergenceProgramming Massively Parallel Processors, 4th edition - Chapters 2 to 6

    Section 4.5

  2. CUDA C++ Best Practices Guide 13.4: branches and predicationCUDA C++ Best Practices Guide

    Sections 13.1 and 13.2

  3. NVIDIA: flexible kernels with grid-stride loopsNVIDIA CUDA Pro Tips: grid-stride loops and vectorized memory access

    Monolithic SAXPY kernel, grid-stride SAXPY kernel, Scalability and thread reuse, and Debugging

2

Focus on

  • Divergence is within a warp. Different uniform paths in different warps need not serialize each other as divergent paths of one warp do.
  • A source if may become a branch, a select or predicated instructions. Inspect the final code before describing the machine's control flow.
  • A grid-stride loop starts at the global thread index and increments by the total grid thread count. Each element belongs to one residue class, so coverage is complete without overlapping writes.
  • Handle an empty input on the host rather than launching a zero-block grid. Promote operands before index multiplication and define a size limit that also prevents loop-increment overflow.
Common mistakes · 3
  • Using block size alone as the loop stride in a multi-block grid. Blocks then overlap work.
  • Removing the tail guard to avoid divergence. Invalid memory access cannot be traded for speed.
  • Assuming a serial GPU launch reproduces all CPU floating-point arithmetic bit for bit. Contraction, precision and operation order can still differ.
3

Try it yourself

Closed-book, before checking anything

Convert the vector-add baseline to a grid-stride loop. For 1003 elements and a one-block, 128-thread launch, thread 0 handles indices 0, 128, 256, 384, 512, 640, 768 and 896; thread 127 handles seven indices ending at 895. Validate every result against the host reference, then repeat with a one-thread launch and lengths 0, 1, 31, 32 and 33. Use the exact integer-valued single-precision inputs from the programming-model unit, so equality is exact here, not a general floating-point promise.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Does threadIdx.x < 32 diverge a block with 128 threads?Answer

    It gives different paths to different warps, but each warp's predicate is uniform. It is not within-warp divergence for this one-dimensional launch.

  2. 2.Why is a grid-stride map complete even when the grid is smaller than the input?Answer

    Every valid index has a unique remainder modulo the total grid thread count. That thread reaches the index after a finite number of loop increments.

  3. 3.Is converting the completed index product to a wide type sufficient to avoid overflow?Answer

    No. The multiplication can overflow before conversion. Promote an operand before multiplication and also check the maximum supported size and increment.

You're done when

Your grid-stride map passes the stated lengths with both launch sizes, and you predict lane activity for a new predicate before checking its generated control flow.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 8 more in the section
  • Programming Massively Parallel Processors, 4th edition - Chapters 2 to 6Wen-mei Hwu, David Kirk and Izzat El Hajj · primary

    Read Chapters 2 to 6: data-parallel kernels, multidimensional grids, compute architecture and scheduling, memory architecture and data locality, and performance considerations. Work the chapter exercises on warps, occupancy, memory and coalescing, and predict three altered launch or address patterns before running them.

  • CUDA C++ Best Practices GuideNVIDIA · required

    Study Assess, Parallelize, Optimize, Deploy; Getting the Right Answer; memory optimization; execution configuration; instruction optimization; and deployment compatibility. Convert recommendations into hypotheses, not universal rules.

  • NVIDIA CUDA Pro Tips: grid-stride loops and vectorized memory accessNVIDIA · required

    Read the grid-stride SAXPY loop and its scalability and debugging discussion (April 22, 2013), plus the scalar-copy SASS and vector-type alignment discussion in Increase Performance with Vectorized Memory Access (August 4, 2025). Skip the latter article's full vector-copy kernels: their tail-thread condition can omit remainders. These fill the pool's grid-stride and vector-width coverage gaps.

Also in this section

  • MIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 2 to 5 and Labs 2 and 3MIT · required

    Use Lecture 2 (Throughput Processors), Lectures 3 and 4 (Memory, Parts 1 and 2) and Lecture 5 with its continuation (scratchpads, bank conflicts, register shuffles, overlap) for why the hardware looks as it does. Do Lab 2 (Massively-Parallel Mandelbrot, with its FMA-latency and warp-scheduler probes) and Lab 3 (Wave Simulation, with its coalesced-load and memory-latency probes) from the public lab repositories, built with nvcc for your own GPU instead of the course service. The labs were written for an RTX 4000 Ada, so recompute any SM count or bandwidth the questions assume.

  • CUDA Programming GuideNVIDIA · required

    Read the Basics and Programming Model chapters plus the sections on memory, synchronization, hardware implementation and compute capabilities used by your kernels. Record the toolkit documentation version alongside every claim.

  • Parallel Thread Execution ISANVIDIA · reference

    Read the PTX purpose, machine model, state spaces, memory consistency and target directives. Compile two tiny kernels, map source to PTX and SASS, and explain what PTX does and does not guarantee across devices.

  • GPU MODE Foundations LecturesGPU MODE · support

    Use Lectures 2, 3, 4, 5, 8, 37 and 41 for PMPP review, CUDA setup, architecture, optimization checklists, SASS and documentation reading. Reproduce only the examples that test a prediction from this stage.

  • TensorTonic Language Modeling from Scratch - GPU analysis problemsTensorTonic · support

    Solve GPU Occupancy Calculator, Shared-Memory Bank Conflict Analyzer and Global-Memory Coalescing Counter after the matching units, and check each answer against your own derivation.

  • AI Performance Engineering - GPU FundamentalsWafer · reference

    A curated index. Use Section 1 only to find a CUDA, PTX or architecture source the other entries lack.

  • CUDA Binary Utilities 13.4NVIDIA · reference

    Sections 1.1 to 1.2, 2.1.1 to 2.1.3, 3.1.1 and 3.1.4 for cubin extraction, resource reports and line-correlated SASS. The existing compiler and PTX references lack a worked binary-tool workflow.

  • PyTorch custom C++/CUDA operators and CUDA semanticsPyTorch · required

    Custom C++ and CUDA Operators: build system, backend registration, Testing an operator and mutable schema; CUDA semantics 2.14: CUDA streams. These fill the native tensor-boundary gap in the CUDA-only pool. Stop before fake-kernel and autograd implementation; harden the tutorial's CUDA example for empty inputs, same-device checks, device guards, indexing width and launch errors.