What is Prefix sum?
Computing the running totals of an array from the start, also called a scan. It can be computed in parallel and is used to find write positions when compacting output.
Japanese name: プレフィックスサム
Computing the running totals of an array from the start, also called a scan. It can be computed in parallel and is used to find write positions when compacting output.
Japanese name: プレフィックスサム
A prefix sum computes, for each position in an array, the total from the start up to that position. An inclusive prefix sum includes the element itself; an exclusive one adds only the elements before it. For the input 3, 1, 7, 0, 4, the inclusive result is 3, 4, 11, 11, 15. The exclusive result is 0, 3, 4, 11, 11, which is the inclusive result shifted one place to the right. Whereas a reduction outputs a single total, a prefix sum outputs every running total.
Written as a running sum, each value seems to need the previous result first. But addition is associative, so partial sums over sections can be prepared in advance. A representative method first builds partial sums upward in a tree. It then passes partial sums back down the tree to obtain the value at each position. The number of stages is proportional to log2 n. Methods are known that keep the total number of additions roughly proportional to n.
When only the elements that meet a condition are written out packed together, a thread does not know its write position in advance. Each element is therefore flagged 1 if it will be output and 0 if not, and an exclusive prefix sum of the flags is computed. For the flags 1, 0, 1, 1, 0, 1 the result is 0, 1, 1, 2, 3, 3. An element whose flag is 1 uses this value as its write address. The elements at positions 0, 2, 3 and 5 line up at addresses 0, 1, 2 and 3. The same building block is used in radix sort and elsewhere.
Answer: B. A prefix sum (scan, the running total from the start)
Representing whether each thread outputs as 0 or 1 and computing the running total from the start (an exclusive prefix sum) gives each thread "the number of outputting threads before me", which is exactly its write address. A scan can be computed in parallel with a tree structure, like a reduction. It is the basic tool for compacting variable per-element output in parallel.
The exclusive form is used to find write addresses, because each value is then the number of elements output before that position. Shifting the inclusive result one place to the right and putting 0 at the front gives the exclusive result.
Yes. Any associative operation, such as maximum, can be computed the same way. An operation that is not associative, such as subtraction, cannot be used as it is.
As an Amazon Associate I earn from qualifying purchases.
This page was drafted with AI and fact-checked by a separate AI review before publication. Our Editorial policy explains how we write and check content. If you spot an error, please tell us on our Contact page.