Unit 4 of 11 · about 5 hours · implement
Warp shuffles, block reductions, multi-pass completion and tails
No single block sees the whole vector. This unit turns a block-local tree into a correct whole-array reduction, the completion pattern behind every multi-pass primitive.
You'll be able to
- Write a warp shuffle reduction with a correct mask and tail handling.
- Complete a grid reduction with block partials and a second pass, covering lengths 0, 1, odd and huge.
- Measure coarsening-factor trade-offs and keep the factor where gains stop.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Divergence, memory and hierarchical reductionProgramming Massively Parallel Processors, 4th edition - Chapters 6 and 9 to 12
Chapter 10, Sections 10.4 to 10.7: minimizing control divergence, memory divergence and global accesses, plus hierarchical reduction for arbitrary input length
- Shuffle prelabMIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7
Lab 7, Part 0 (
shuffle.cu):__shfl_up_sync(0xffffffff, threadIdx.x, 1)semantics, no wrap-around, and the two 32-integer cumulative-sum kernels with and without shared memoryBuild for your own GPU with
nvcc -arch=nativeand recompute any SM count the questions assume. Use only Part 0 here; the scan parts belong to later units. - Warp completion and cascadingOptimizing Parallel Reduction in CUDA
Slides 21 and 22 (unrolling the last warp with
warpReduce) and slides 31 to 33 (multiple adds per thread with a grid-stride loop)The deck predates Volta. Its
warpReduceassumes lockstep warps, so rewrite it with__shfl_down_syncbefore you reuse it. - Coarsened reduction codeGPU MODE - Reductions and Scans
Lecture 9 code in
lecture_009/reduce_coarsening.cu: per-thread accumulation withCOARSE_FACTORbefore the block tree
Focus on
__shfl_down_sync(0xffffffff, v, offset)requires every lane named in the mask to make the same call, and a lane reading from an inactive lane gets an undefined value. Keep all 32 lanes in the reduction and give out-of-range lanes the identity (0 for a sum).- Blocks cannot synchronize globally, so write one partial per block and finish with a second kernel launch. The second pass needs its own tail handling for odd partial counts.
- First-add-during-load halves the launched blocks: each thread adds two elements as it loads them, so the first tree level runs during the load. Global reads stay at . Cascading extends the idea until occupancy or registers stop the gain.
Common mistakes · 3
- Calling
__syncthreads()inside a divergent branch. The guide calls it invalid or undefined behavior: the block may hang, or on current GPUs run on with a silent race. Keep barriers on uniform control flow. - Finishing with one global atomic per element instead of one per block. Atomics belong at block granularity; per-element atomics turn completion into contention.
- Testing only multiples of 1024. Tail bugs hide there, so test 1, 31, 32, 33, 1023 and 1000003.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why complete a grid reduction in two passes instead of one global barrier?Answer
No grid-wide barrier exists for independently scheduled blocks. One partial per block plus a second launch is the portable completion; single-pass schemes risk deadlock.
2.A tail warp has 20 lanes with data and reduces with a full
0xffffffffmask. When does this go wrong, and what is the fix?AnswerIf the other 12 lanes skip the shuffle inside a branch, the call is invalid and may hang. If they have exited, the call is allowed but shuffles that read from them return undefined values. Keep all 32 lanes in the reduction with identity values for the missing elements.
3.A 1,000,003-element reduction uses 256-thread blocks. How many blocks does it launch at coarsening 4 and at coarsening 64, and why can the second be slower on your GPU?Answer
977 blocks at 4 and 62 at 64. As the worked example, compute capability 8.6 holds up to six 256-thread blocks per SM, 108 on 18 SMs, so 62 blocks leave SMs partly idle with too few warps to hide memory latency; redo the block-to-SM arithmetic for your own GPU.
4.What exactly does first-add-during-load halve?Answer
The launched blocks and the threads that sit in the shared-memory tree: each thread sums two elements on load. Every element is still read once from global memory.
You're done when
Your two-pass reduction matches float64 within 1e-6 relative error on adversarial sizes, and you can state the coarsening factor where your GPU stops gaining.
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.
- 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.
- 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.
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 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.
- 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.