Count atomic serialization in a warp-level histogram
Why it matters Token counting, MoE expert load counts and top-k histograms all use atomics, and skewed distributions can make them much slower than expected.
When threads of a warp atomically add to the same histogram bin, the hardware serializes those updates. A warp needs as many rounds as the most popular bin among its 32 values.
Write histogram_rounds(vals, n_bins, warp=32). vals are integer bin ids in [0, n_bins). Split vals into consecutive warps of warp elements (the last may be smaller). For each warp, its rounds are the maximum number of times any single bin appears in that warp. Return (hist, total_rounds, worst_warp) where hist is the int histogram of length n_bins, total_rounds is the sum over warps and worst_warp is the index of the warp with the most rounds (lowest index on ties). For empty vals return (zeros, 0, -1).
def histogram_rounds(vals, n_bins, warp=32)Example
vals [1, 1, 2, 0, 3, 3, 3, 3], n_bins 4, warp 4 gives ([1, 2, 1, 4], 6, 1).
Understand the idea
Imagine 32 people dropping votes into ballot boxes at the same moment. If they all use different boxes, it takes one moment. If 10 of them want the same box, they must queue, and the whole group waits for the longest queue. GPU atomics behave the same way inside a warp. Worked example: warp size 4. Warp 0 has [1, 1, 2, 0]: bin 1 appears twice, so 2 rounds. Warp 1 has [3, 3, 3, 3]: 4 rounds. Total 6, and warp 1 is the worst. Rule: rounds(warp) = max over bins of count in that warp. Kernels avoid this by giving each warp or block its own private copy of the histogram in shared memory and merging at the end, which spreads the conflicts out.