Unit 1 of 11 · about 4 hours · implement

Elementwise maps, vectorized access and thread coarsening

Every later primitive reuses this loop. If the map is wrong on tails or wastes transactions, the reduction, scan and softmax built on it inherit both defects.

You'll be able to

  • Write a grid-stride elementwise kernel that covers any length, including zero and nonmultiple sizes, with one bounds check.
  • Convert scalar loads to alignment-guarded vectorized loads and predict the per-warp transaction change.
  • Apply thread coarsening and state where its extra registers and lost parallelism stop paying off.

Covers

Elementwise maps and grid-stride coverageAlignment-safe vectorized loads and storesThread coarsening, instruction work and memory reuse
1

Read

In this order, only the parts listed

0 of 4 done

  1. Thread coarseningProgramming Massively Parallel Processors, 4th edition - Chapters 6 and 9 to 12

    Chapter 6, Section 6.3 (printed p. 138): assigning several elements to each thread; Chapter 10, Section 10.8 (printed p. 228): coarsening against parallelization overhead

  2. Map pattern and coarsening notesMIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7

    Lecture 7, Pattern #1: Map (slide 9); Pattern #3: Reduce (slides 18 to 31), including the thread-coarsening note

  3. Coalesced access and transaction widthCUDA C++ Programming Guide (v13.4.2)

    Section 2.3.4.1: 32-byte transactions, the 4-byte word example with four transactions at full utilization, and the 12.5 percent worst case

    Read for the transaction model only. The section's transpose example belongs to the next unit.

  4. Grid-stride loop patternOptimizing Parallel Reduction in CUDA

    Reduction #7, slides 31 to 33: the grid-stride accumulation loop that adds as many elements as necessary

    Use only for the loop pattern. The reduction sequence belongs to the reduction units.

2

Focus on

  • A grid-stride loop decouples launch configuration from length: each thread visits i, i + gridDim.x * blockDim.x, and so on, so every index is covered exactly once for any length including 0.
  • One 16-byte vectorized load moves 4 floats per thread and needs 16-byte alignment. Guard with an alignment and divisibility test and keep a scalar tail.
  • Coarsening trades fewer blocks and amortized index math for more registers per thread and less parallel slack. PMPP frames it as paying less for parallelism.
  • Coalescing is about the warp, not the thread: consecutive threads should touch consecutive words so one 128-byte request fills four 32-byte transactions.
Common mistakes · 3
  • Trusting base-pointer alignment after arithmetic. cudaMalloc returns aligned bases, but p + offset may not be 16-byte aligned, so check the accessed address at runtime.
  • Testing only round sizes. A vectorized loop without a scalar tail silently drops the last elements, so test 1000003, not just 1048576.
  • Assuming more coarsening is faster. Past the point where blocks still fill the SMs, extra work per thread only adds register pressure and loses latency hiding.
3

Try it yourself

Closed-book, before checking anything

From a blank file, write scalar, vectorized (float4) and 4-way coarsened saxpy kernels with a grid-stride loop, and predict each variant's per-warp transaction count before running. On 1000003 random floats all three match a CPU reference computed with fmaf bit-exactly. nvcc contracts a * x[i] + y[i] into one fused multiply-add by default, so a CPU reference that multiplies and then adds differs in the last bit: on an RTX 3050 6 GB with CUDA 13.4 it disagreed at 282,894 of the 1,000,003 elements; your count will differ, so check the mismatch pattern on your own GPU rather than the exact count.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.With 256 blocks of 256 threads and length 1000003, which indices does thread 0 visit?Answer

    Stride 65536: 0, 65536, up to 983040, which is 16 visits. The next, 1048576, exceeds the length.

  2. 2.A float pointer sits at a byte address with remainder 8 modulo 16. Is a float4 load through it safe?Answer

    No. Vector loads need 16-byte alignment. Peel a scalar head, take a scalar path, or realign the allocation.

  3. 3.One warp loads one consecutive float per thread. How many 32-byte transactions, and at what utilization?Answer

    128 bytes in four transactions at full utilization. Every fetched byte is used.

  4. 4.Why can 8-way coarsening run slower than 4-way on a short vector?Answer

    Too few blocks remain to fill the SMs, and each thread holds more live state. Parallel slack is lost after the memory saving is exhausted.

You're done when

All three saxpy variants match an fmaf reference exactly on an odd size, and you predict each variant's per-warp transaction count before profiling.

Only when you can do this without notes.

Leads to

Notes

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

    Read thread coarsening in Chapter 6, then Chapters 9 (histogram), 10 (reduction), 11 (prefix sum) and 12 (merge, optional). Work the exercises that test work, depth, contention and boundary handling.

  • Optimizing Parallel Reduction in CUDANVIDIA · required

    Implement the optimization sequence from interleaved addressing through sequential addressing, first-add-during-load, unrolling and warp-level completion. Correct outdated assumptions and retain the stage where each optimization stops helping.

  • MIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7MIT · support

    Use Lecture 6 for host-device copies and streams, and Lectures 7 and 9 for map, stencil, reduce, compaction, scan, segmented scan, histogram and merge. Do Lab 7 (Run-Length Compression, with its scan and shuffle warm-ups) built for your own GPU.

  • CUDA C++ Programming Guide (v13.4.2)NVIDIA · reference

    Use Section 2.3.4 for coalesced access, the transpose example and bank-conflict padding; Section 2.5 for streams, events, synchronization and the stream-capture intro; and Section 4.2 for graph creation, update and capture constraints. This is the API reference beside the book chapters.

Also in this section

  • AI Systems Performance Engineering - Chapters 11 and 12Chris Fregly (O'Reilly) · required

    Read Chapter 11 on streams, events, inter-kernel pipelining and stream-ordered allocation, and Chapter 12 on CUDA graphs and dynamic scheduling. Skip device-initiated launch beyond the vocabulary.

  • Efficient Matrix Transpose in CUDA C/C++NVIDIA · required

    Rebuild copy, naive transpose, coalesced transpose and padded shared-memory variants. Update deprecated details for the installed toolkit and compare requested transactions, bank behavior and achieved bandwidth on odd as well as friendly shapes.

  • Single-pass Parallel Prefix Scan with Decoupled Look-backNVIDIA Research · depth

    Read after two-pass scans pass. Derive the state and progress argument, then implement or inspect a bounded version only if the available hardware and time support meaningful comparison.

  • Online Normalizer Calculation for SoftmaxOnline Softmax Authors · required

    Derive the running maximum and normalizer recurrence, test extreme and all-masked rows, and compare materialized, two-pass and online implementations before using the recurrence inside attention.

  • LeetGPU - CUDA Primitive ChallengesAlphaGPU · required

    Solve challenge 3 Matrix Transpose, 4 Reduction, 5 Softmax, 13 Histogramming and 16 Prefix Sum in CUDA. Add 70 Segmented Prefix Sum or 72 Stream Compaction only after the required set. Keep local source, hidden-shape assumptions, hardware, raw timings and correctness evidence outside the leaderboard.

  • GPU MODE - Reductions and ScansGPU MODE · support

    Use Lectures 9, 20, 21 and 24 after the PMPP implementations. Reproduce one faster scan or reduction idea and show the exact shape and device regime where it changes the bottleneck.

  • GPU Microbenchmark and Kernel Suite - CUDA CoreRoadmap-Final · support

    Complete the CUDA vector map, reduction, transpose and stable softmax requirements plus seeded access, synchronization, mask, stream and numerical failures. Preserve library and framework baselines.