Unit 7 of 11 · about 3 hours · implement

Stream compaction from predicate, scan and scatter

Compaction is the first complete irregular primitive: data-dependent output positions with no races and no oversized buffers.

You'll be able to

  • Build predicate, exclusive-scan and scatter stages into one compaction.
  • Handle all-false, all-true and empty inputs with exact outputs.
  • Explain why scan, not atomics, assigns the write positions.

Covers

Predicate, scan and scatter for stream compaction
1

Read

In this order, only the parts listed

0 of 3 done

  1. Compaction from scan and scatterMIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7

    Lecture 7, Pattern #4: Stream Compaction (slides 32 to 38): predicate array, exclusive scan as scatter addresses, and the return to compaction after the scan pattern

  2. Split and load-balance searchMIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7

    Lecture 9, Pattern #4.5: Split (slides 5 to 8) for stable partitioning by scan, and Load-balance Search (slides 9 to 15) for count, scan and scatter expansion

  3. Run-length compressionMIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 6, 7 and 9 and Lab 7

    Lab 7, Part 2 (rle_compress.cu, launch_rle_compress): run starts as an implicit predicate plus scan for positions over a 16-million-byte bitmap (rle_raw.bmp)

    Build for your own GPU with nvcc -arch=native and retarget the 1.6 ms course goal to your hardware. Part 3 decompression is extra credit; skip it here.

2

Focus on

  • Compaction is three steps: predicate in 0/1, exclusive scan giving write address as the count of kept elements before , then order-preserving scatter. The kept total is .
  • Positions come from the scan, so no two threads claim one slot and no atomic counter serializes. That is the whole point of the construction.
  • LeetGPU 72 keeps rejected slots as 0.0 in a full-size output while RLE packs values plus lengths tightly. Both are correct compactions with different contracts, so read the expected layout first.
Common mistakes · 3
  • Using an inclusive scan for addresses shifts every write by one slot: slot 0 stays unwritten and the last kept element lands one past the kept total.
  • Treating 0.0 as kept. The contract selects strictly positive inputs, so zeros stay out.
  • Sizing the output to the kept count before computing it. Read back the total first, or overallocate to the input length and slice.
3

Try it yourself

Closed-book, before checking anything

On [-1, 2, 0, 4] produce predicate [0, 1, 0, 1], exclusive scan [0, 0, 1, 1] and output [2, 4, 0, 0] under the Challenge 72 contract. Then implement scan-plus-scatter that matches it on all-positive, all-negative and length-255 non-power-of-two inputs.
4

Quiz yourself

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

0 got · 0 missed

  1. 1.Compact [-1, 2, 0, 4] under the Challenge 72 contract. What are the predicate, the exclusive scan, the output and K?Answer

    Predicate [0, 1, 0, 1], scan [0, 0, 1, 1], output [2, 4, 0, 0], . Zeros are rejected and survivors keep order.

  2. 2.What do an all-negative input and an empty input produce?Answer

    An all-zero output with , and an empty output with . The kernel must still launch and synchronize cleanly.

  3. 3.Why not assign positions with one atomic counter?Answer

    Every kept element would serialize on one address. The scan assigns all positions in parallel with no contention.

  4. 4.How do the Challenge 72 and RLE output layouts differ?Answer

    Challenge 72 pads rejected slots with 0.0 to the full input length; RLE packs kept values plus run lengths tightly. The checker decides which is correct.

5

Practice

  • MIT Lab 7 Part 2: run-length compression

    Part 2 launch_rle_compress in rle_compress.cu: scan-built positions for run starts, reusing your Part 1 scan

    Build with nvcc -arch=native, run in your own harness, and recompute the timing goal for your GPU; the course runner needs an MIT token.

  • LeetGPU challenge 72: Stream Compaction

    Challenge 72: solve(A, N, out) keeping strictly positive values in order, with the rest of out left at 0.0, checked exactly, with functional cases for length 1 present and absent plus non-powers of two, and a performance case of

    Attempt only after challenges 3, 4, 5, 13 and 16 pass. Run it on LeetGPU or locally with the harness from the transpose unit.

You're done when

Your compactor matches the Challenge 72 contract on edge sizes, and you derive every scatter address from the exclusive scan by hand on the 4-element example.

Only when you can do this without notes.

Leads to

Notes

Resources · 1 for this unit, 10 more in the section

Also in this 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.

  • 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.

  • 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.

  • 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.

  • 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.