8 The Histogram pattern
In parallel GPU code, the chapter frames histogramming as a classic write-conflict problem: many threads may try to update the same counter at the same time, and a simple read-modify-write like ++ can silently lose updates. The fix is to make the update indivisible with atomics, so operations such as atomicAdd, atomicMax, atomicMin, and atomicCAS serialize access to a shared location and preserve correctness. The chapter also shows how compare-and-swap can be used to build more specialized atomics, such as a floating-point max operation.
Building on that foundation, the text develops histogram construction from a naive, fully global version into a faster privatized design. A straightforward parallel histogram uses one global bin array and an atomic increment for every input element, which is correct but can become very slow when many threads contend for the same bin. To reduce contention, each CUDA block first initializes its own 256-bin histogram in shared memory, tallies into that private copy using shared-memory atomics, and then merges the local bins back into the global histogram with far fewer global atomic updates. This preserves correctness while shifting most of the hot updates into fast on-chip memory.
The chapter finishes by showing how to scale the pattern when there are more input elements than threads, using grid-stride loops so each thread processes multiple items. It also warns about common mistakes, especially forgetting atomics on shared counters and placing __syncthreads() inside divergent branches, which can cause deadlock. The broader takeaway is that histogram performance is shaped less by algorithmic work than by contention: atomics make shared updates safe, privatization makes them cheaper, and the best implementation balances both while keeping the barriers and initialization in the right places.
The race condition (Scenario A, top) and the correct sequential execution (Scenario B, bottom). When T0 and T1 run concurrently (A), both threads read count=5 and both write 6, so one increment is lost: the final count is 6. When T0 completes before T1 starts (B), the final count is correctly 7.
The histogram pattern on a CPU. A single thread T0 reads each element of the data array (length n) one at a time and writes to the corresponding bin in the 256-element hist array. With only one writer, there are no conflicts.
The histogram pattern in parallel, without atomics. n threads (T0 through Tn−1) read their data elements simultaneously and all write into hist at the same time. When multiple threads target the same bin, their writes race and updates are lost: the same race condition as in figure 8.1, scaled up across all bins.
The three-step shared memory histogram pipeline, with time flowing top to bottom. Step 1 (setup): each of the m blocks zeros its own 256-bin localHist in shared memory in parallel. Step 2 (compute): each block i reads its k-element slice of the input from global memory and atomically increments the matching bins of its own localHist. Step 3 (merge): each block adds the values in its localHist into the single global hist array. Only Step 2 reads global input and only Step 3 writes global output; the heavy traffic between them, the tallying, stays in fast shared memory.
Step 1 (setup) inside a single block. Block i has k threads, T0 through Tk−1. Thread Tj writes 0 into localHist entries at offset j and at every j + k, j + 2k, ... up to index 255, the stride-k pattern that guarantees all 256 bins are zeroed regardless of block size. Every block from 0 through m−1 does this independently in parallel.
Step 2 (compute) inside a single block. Block i is responsible for the slice data[i*k … i*k+k−1] of the global input array. Thread T0 reads data[i*k], T1 reads data[i*k+1], and so on through Tk−1 reading data[i*k+k−1]. Each thread then atomically increments the localHist bin matching its element. The arrows converge because different threads in the block may target the same bin, but the atomicAdd targets fast shared memory rather than global memory.
Step 3 (merge) inside a single block. Block i’s k threads divide up its localHist using the same stride-k pattern as Step 1: thread Tj reads localHist[j], localHist[j+k], localHist[j+2k], ... and adds each value into the corresponding entry of the global hist with atomicAdd. All m blocks merge into the same hist concurrently, so the atomic is still required, but only m blocks contend per bin, instead of the n input elements that would have contended in the naive version.
Summary
- Atomic operations make read-modify-write indivisible, eliminating race conditions. atomicAdd, atomicSub, atomicMax, atomicMin, atomicExch, and atomicCAS make up your atomic toolkit. atomicCAS is the general one: it writes your value only if the current value is still what you expected, so it belongs inside a retry loop. That loop is also how you build the atomics CUDA lacks, such as a float atomicMax.
- atomicAdd takes an address, not a value: pass count when the variable is already a pointer, as it is in countPositive, and &hist[bin] when the target is an array element. Zero the counter or the histogram on the device before you launch, or the count starts from whatever was already sitting in GPU memory.
- Atomics are safe, but they come with a cost. They serialize the threads that target the same address, so the cost depends on contention: values spread evenly across bins run at full speed, while one hot bin drops throughput to nearly sequential.
- The histogram pattern counts how often each value appears. On a GPU the fast version is privatized: each block accumulates into a private shared memory copy, then merges it into the global histogram with atomics.
- The privatized kernel runs in three steps, with a __syncthreads() after each of the first two: zero localHist in shared memory, tally into it with shared memory atomics, then merge it into the global histogram. Both barriers must sit where every thread reaches them.
- Instead of one global atomic per input element, each block issues at most one per bin, carrying that block’s accumulated count. The reduction factor is the block size: a bin that could see up to n global atomics now sees at most one per block, and n divided by the number of blocks is the block size. It equals 256 in our example only by coincidence with the 256 bins.
- “Reduce locally, combine globally” is privatization, the same shape as the per-block partial sums in chapter 5, and it answers contention outside CUDA too: OpenMP gives each CPU thread its own bins and sums them at the end.
- The histogram is the pattern where contention rather than depth sets performance. Its ideal depth is O(1), one independent element per thread, but atomics on a popular bin serialize threads and lengthen it in practice.
- A grid-stride loop handles more elements than threads: each thread steps by blockDim.x * gridDim.x. Combined with privatization, fewer blocks each doing more work, it is a common design for production histogram kernels.
- In PyTorch, torch.bincount() and torch.histc() compute histograms; on a CUDA tensor they use optimized kernels built on the same ideas, privatization and atomics.
FAQ
What is the histogram pattern in GPU programming?
The histogram pattern counts how many input values fall into each bin of an output array. On a GPU, many threads often contribute to the same bins, so the pattern is mainly about handling write conflicts correctly and efficiently.
Why do naive parallel histograms produce wrong results?
Because multiple threads can increment the same bin at the same time. A plain increment is a read-modify-write sequence, so one thread can overwrite another’s update and lose counts.
How do atomic operations fix histogram race conditions?
Atomic operations make the update indivisible, so no other thread can slip in between reading, adding, and writing back. For histograms, atomicAdd(&hist[bin], 1) prevents lost updates.
What is the difference between hist[bin]++ and atomicAdd(&hist[bin], 1)?
hist[bin]++ is unsafe in parallel because it can race. atomicAdd(&hist[bin], 1) performs the increment safely in one serialized atomic step.
Why can atomics be safe but still slow?
Atomics serialize when many threads target the same address. They prevent incorrect results, but threads must take turns, so heavy contention can make the kernel much slower.
What is shared memory privatization in a histogram kernel?
Privatization means giving each block its own private histogram in shared memory, letting blocks tally locally first, then merging those partial histograms into the global result. This reduces contention on global memory.
Why is a shared-memory histogram usually faster than a global-atomic histogram?
Because most updates happen in fast shared memory instead of global memory, and only the merge phase uses global atomics. That reduces the number of expensive global-contention points per bin.
Why are __syncthreads() calls necessary in the shared-memory histogram?
They ensure every thread in the block finishes the current phase before any thread starts the next one. Without the barriers, some threads could start using or merging the histogram before others finish initializing or tallying it.
What is a grid-stride loop and why is it useful for histograms?
A grid-stride loop lets each thread process multiple elements by jumping ahead by the total number of threads in the grid. It is useful when there are more data elements than threads, and it can be combined with the shared-memory histogram to handle large inputs efficiently.
What common mistakes should you watch for in histogram kernels?
The two biggest mistakes are forgetting atomics on shared updates and placing __syncthreads() inside a conditional so only some threads reach it. The first causes wrong counts; the second can deadlock the kernel.
Grokking GPU Programming ebook for free