# Prefix sum

In computer science, the prefix sum, cumulative sum, inclusive scan, or simply scan of a sequence of numbers x$_0$, x$_1$, x$_2$, ... is a second sequence of numbers y$_0$, y$_1$, y$_2$, ..., the sums of prefixes (running totals) of the input sequence:
    y$_0$ = x$_0$
    y$_1$ = x$_0$ + x$_1$
    y$_2$ = x$_0$ + x$_1$+ x$_2$
For instance, the prefix sums of the natural numbers are the triangular numbers:
    input numbers  1 2 3 4 5 6... prefix sums  1 3 6101521...
Prefix sums are trivial to compute in sequential models of computation, by using the formula y$_i$ = y$_{i−1}$ + x$_i$ to compute each output value in sequence order. However, despite their ease of computation, prefix sums are a useful primitive in certain algorithms such as counting sort, and they form the basis of the scan higher-order function in functional programming languages. Prefix sums have also been much studied in parallel algorithms, both as a test problem to be solved and as a useful primitive to be used as a subroutine in other parallel algorithms.
Abstractly, a prefix sum requires only a binary associative operator ⊕, making it useful for many applications from calculating well-separated pair decompositions of points to string processing.
Mathematically, the operation of taking prefix sums can be generalized from finite to infinite sequences; in that context, a prefix sum is known as a partial sum of a series. Prefix summation or partial summation form linear operators on the vector spaces of finite or infinite sequences; their inverses are finite difference operators.

## Scan higher order function

In functional programming terms, the prefix sum may be generalized to any binary operation (not just the addition operation); the higher order function resulting from this generalization is called a scan, and it is closely related to the fold operation. Both the scan and the fold operations apply the given binary operation to the same sequence of values, but differ in that the scan returns the whole sequence of results from the binary operation, whereas the fold returns only the final result. For instance, the sequence of factorial numbers may be generated by a scan of the natural numbers using multiplication instead of addition:
    input numbers 123456... prefix products 12624120720...

### Inclusive and exclusive scans

    input numbers 123456... inclusive 136101521... exclusive 01361015...
Programming language and library implementations of scan may be either inclusive or exclusive. An inclusive scan includes input x$_i$ when computing output y$_i$ (i.e., y$_i$=⨁$_{j=0}$$^i$x$_j${\textstyle y_{i}=\bigoplus _{j=0}^{i}x_{j}}) while an exclusive scan does not (i.e., y$_i$=⨁$_{j=0}$$^{i−1}$x$_j${\textstyle y_{i}=\bigoplus _{j=0}^{i-1}x_{j}}). In the latter case, implementations either leave y$_0$ undefined or accept a separate "x$_{−1}$" value with which to seed the scan. Either type of scan can be transformed into the other: an inclusive scan can be transformed into an exclusive scan by shifting the array produced by the scan right by one element and inserting the identity value at the left of the array. Conversely, an exclusive scan be transformed into an inclusive scan by shifting the array produced by the scan left and inserting the sum of the last element of the scan and the last element of the input array at the right of the array.
The following table lists examples of the inclusive and exclusive scan functions provided by a few programming languages and libraries:
| Language/library | Inclusive scan | Exclusive scan |
| APL | +\ | |
| C++ | std::inclusive_scan | std::exclusive_scan |
| Clojure | reductions without init | reductions with init |
| CUDA | thrust::inclusive_scan cub::DeviceScan::InclusiveScan | thrust::exclusive_scan cub::DeviceScan::ExclusiveScan |
| F# | | scan |
| Haskell | scanl1 | scanl |
| HPF | sum_prefix | sum_prefix(..., exclusive=.true.) |
| Java | Arrays.parallelPrefix | |
| Kotlin | | scan |
| MPI | MPI_Scan | MPI_Exscan |
| Python | itertools.accumulate when initial is None | itertools.accumulate when initial is not None |
| Rust | scan | |
| Scala | | scan |
The directive-based OpenMP parallel programming model supports both inclusive and exclusive scan support beginning with Version 5.0.

## Parallel algorithms

There are two key algorithms for computing a prefix sum in parallel. The first offers a shorter span and more parallelism but is not work-efficient. The second is work-efficient but requires double the span and offers less parallelism. These are presented in turn below.

### Algorithm 1: Shorter span, more parallel

Hillis and Steele present the following parallel prefix sum algorithm:
In the above, the notation $x_{j}^{i}$ means the value of the jth element of array x in timestep i.
With a single processor this algorithm would run in O(n log n) time. However if the machine has at least n processors to perform the inner loop in parallel, the algorithm as a whole runs in O(log n) time, the number of iterations of the outer loop.

### Algorithm 2: Work-efficient

A work-efficient parallel prefix sum can be computed by the following steps.
* Compute the sums of consecutive pairs of items in which the first item of the pair has an even index: z$_0$ = x$_0$ + x$_1$, z$_1$ = x$_2$ + x$_3$, etc.
* Recursively compute the prefix sum w$_0$, w$_1$, w$_2$, ... of the sequence z$_0$, z$_1$, z$_2$, ...
* Express each term of the final sequence y$_0$, y$_1$, y$_2$, ... as the sum of up to two terms of these intermediate sequences: y$_0$ = x$_0$, y$_1$ = z$_0$, y$_2$ = z$_0$ + x$_2$, y$_3$ = w$_1$, etc. After the first value, each successive number y$_i$ is either copied from a position half as far through the w sequence, or is the previous value added to one value in the x sequence.
If the input sequence has n steps, then the recursion continues to a depth of O(log n), which is also the bound on the parallel running time of this algorithm. The number of steps of the algorithm is O(n), and it can be implemented on a parallel random access machine with O(n/log n) processors without any asymptotic slowdown by assigning multiple indices to each processor in rounds of the algorithm for which there are more elements than processors.

### Discussion

Each of the preceding algorithms runs in O(log n) time. However, the former takes exactly log$_2$ n steps, while the latter requires 2 log$_2$ n − 2 steps. For the 16-input examples illustrated, Algorithm 1 is 12-way parallel (49 units of work divided by a span of 4) while Algorithm 2 is only 4-way parallel (26 units of work divided by a span of 6). However, Algorithm 2 is work-efficient—it performs only a constant factor (2) of the amount of work required by the sequential algorithm—while Algorithm 1 is work-inefficient—it performs asymptotically more work (a logarithmic factor) than is required sequentially. Consequently, Algorithm 1 is likely to perform better when abundant parallelism is available, but Algorithm 2 is likely to perform better when parallelism is more limited.
Parallel algorithms for prefix sums can often be generalized to other scan operations on associative binary operations, and they can also be computed efficiently on modern parallel hardware such as a GPU. The idea of building in hardware a functional unit dedicated to computing multi-parameter prefix-sum was patented by Uzi Vishkin.
Many parallel implementations follow a two pass procedure where partial prefix sums are calculated in the first pass on each processing unit; the prefix sum of these partial sums is then calculated and broadcast back to the processing units for a second pass using the now known prefix as the initial value. Asymptotically this method takes approximately two read operations and one write operation per item.

### Concrete implementations of prefix sum algorithms

An implementation of a parallel prefix sum algorithm, like other parallel algorithms, has to take the parallelization architecture of the platform into account. More specifically, multiple algorithms exist which are adapted for platforms working on shared memory as well as algorithms which are well suited for platforms using distributed memory, relying on message passing as the only form of interprocess communication.

#### Shared memory: Two-level algorithm

The following algorithm assumes a shared memory machine model; all processing elements (PEs) have access to the same memory. A version of this algorithm is implemented in the Multi-Core Standard Template Library (MCSTL), a parallel implementation of the C++ standard template library which provides adapted versions for parallel computing of various algorithms.
In order to concurrently calculate the prefix sum over n data elements with p processing elements, the data is divided into $p+1$ blocks, each containing ${\frac {n}{p+1}}$ elements (for simplicity we assume that $p+1$ divides n). Note, that although the algorithm divides the data into $p+1$ blocks, only p processing elements run in parallel at a time.
In a first sweep, each PE calculates a local prefix sum for its block. The last block does not need to be calculated, since these prefix sums are only calculated as offsets to the prefix sums of succeeding blocks and the last block is by definition not succeeded.
The p offsets which are stored in the last position of each block are accumulated in a prefix sum of their own and stored in their succeeding positions. For p being a small number, it is faster to do this sequentially, for a large p, this step could be done in parallel as well.
A second sweep is performed. This time the first block does not have to be processed, since it does not need to account for the offset of a preceding block. However, in this sweep the last block is included instead and the prefix sums for each block are calculated taking the prefix sum block offsets calculated in the previous sweep into account.
Improvement: In case that the number of blocks are too much that makes the serial step time-consuming by deploying a single processor, the Hillis and Steele algorithm can be used to accelerate the second phase.

#### Distributed memory: Hypercube algorithm

The Hypercube Prefix Sum Algorithm is well adapted for distributed memory platforms and works with the exchange of messages between the processing elements. It assumes to have $p=2^{d}$ processor elements (PEs) participating in the algorithm equal to the number of corners in a d-dimensional hypercube.
Throughout the algorithm, each PE is seen as a corner in a hypothetical hyper cube with knowledge of the total prefix sum $\sigma$ as well as the prefix sum x of all elements up to itself (according to the ordered indices among the PEs), both in its own hypercube.
* The algorithm starts by assuming every PE is the single corner of a zero dimensional hyper cube and therefore $\sigma$ and x are equal to the local prefix sum of its own elements.
* The algorithm goes on by unifying hypercubes which are adjacent along one dimension. During each unification, $\sigma$ is exchanged and aggregated between the two hyper cubes which keeps the invariant that all PEs at corners of this new hyper cube store the total prefix sum of this newly unified hyper cube in their variable $\sigma$. However, only the hyper cube containing the PEs with higher index also adds this $\sigma$ to their local variable x, keeping the invariant that x only stores the value of the prefix sum of all elements at PEs with indices smaller or equal to their own index.
In a d-dimensional hyper cube with $2^{d}$ PEs at the corners, the algorithm has to be repeated d times to have the $2^{d}$zero-dimensional hyper cubes be unified into one d-dimensional hyper cube. Assuming a duplex communication model where the $\sigma$ of two adjacent PEs in different hyper cubes can be exchanged in both directions in one communication step, this means $d=\log _{2}p$ communication startups.

#### Large message sizes: pipelined binary tree

The Pipelined Binary Tree Algorithm is another algorithm for distributed memory platforms which is specifically well suited for large message sizes.
Like the hypercube algorithm, it assumes a special communication structure. The processing elements (PEs) are hypothetically arranged in a binary tree (e.g. a Fibonacci Tree) with infix numeration according to their index within the PEs. Communication on such a tree always occurs between parent and child nodes.
The infix numeration ensures that for any given PE$_j$, the indices of all nodes reachable by its left subtree $\color {Blue}{[l\dots j-1]}$ are less than j and the indices $\color {Blue}{[j+1\dots r]}$ of all nodes in the right subtree are greater than j. The parent's index is greater than any of the indices in PE$_j$'s subtree if PE$_j$ is a left child and smaller if PE$_j$ is a right child. This allows for the following reasoning:
* The local prefix sum $\color {Blue}{\oplus [l\dots j-1]}$ of the left subtree has to be aggregated to calculate PE$_j$'s local prefix sum $\color {Blue}{\oplus [l\dots j]}$.
* The local prefix sum $\color {Blue}{\oplus [j+1\dots r]}$ of the right subtree has to be aggregated to calculate the local prefix sum of higher level PE$_h$ which are reached on a path containing a left children connection (which means $h>j$).
* The total prefix sum $\color {Red}{\oplus [0\dots j]}$ of PE$_j$ is necessary to calculate the total prefix sums in the right subtree (e.g. $\color {Red}{\oplus [0\dots j\dots r]}$ for the highest index node in the subtree).
* PE$_j$ needs to include the total prefix sum $\color {Red}{\oplus [0\dots l-1]}$ of the first higher order node which is reached via an upward path including a right children connection to calculate its total prefix sum.
Note the distinction between subtree-local and total prefix sums. The points two, three and four can lead to believe they would form a circular dependency, but this is not the case. Lower level PEs might require the total prefix sum of higher level PEs to calculate their total prefix sum, but higher level PEs only require subtree local prefix sums to calculate their total prefix sum. The root node as highest level node only requires the local prefix sum of its left subtree to calculate its own prefix sum. Each PE on the path from PE$_0$ to the root PE only requires the local prefix sum of its left subtree to calculate its own prefix sum, whereas every node on the path from PE$_{p-1}$ (last PE) to the PE$_{root}$ requires the total prefix sum of its parent to calculate its own total prefix sum.
This leads to a two-phase algorithm:

##### Upward Phase

    Propagate the subtree local prefix sum $\color {Blue}{\oplus [l\dots j\dots r]}$ to its parent for each PE$_j$.

##### Downward phase

    Propagate the exclusive (exclusive PE$_j$ as well as the PEs in its left subtree) total prefix sum $\color {Red}{\oplus [0\dots l-1]}$ of all lower index PEs which are not included in the addressed subtree of PE$_j$ to lower level PEs in the left child subtree of PE$_j$. Propagate the inclusive prefix sum $\color {Red}{\oplus [0\dots j]}$ to the right child subtree of PE$_j$.
Note that the algorithm is run in parallel at each PE and the PEs will block upon receive until their children/parents provide them with packets.

##### Pipelining

If the message m of length n can be divided into k packets and the operator ⨁ can be used on each of the corresponding message packets separately, pipelining is possible.
If the algorithm is used without pipelining, there are always only two levels (the sending PEs and the receiving PEs) of the binary tree at work while all other PEs are waiting. If there are p processing elements and a balanced binary tree is used, the tree has $\log _{2}p$ levels, the length of the path from $PE_{0}$ to $PE_{\mathrm {root} }$ is therefore $\log _{2}p-1$ which represents the maximum number of non parallel communication operations during the upward phase, likewise, the communication on the downward path is also limited to $\log _{2}p-1$ startups. Assuming a communication startup time of $T_{\mathrm {start} }$ and a bytewise transmission time of $T_{\mathrm {byte} }$, upward and downward phase are limited to $(2\log _{2}p-2)(T_{\mathrm {start} }+n\cdot T_{\mathrm {byte} })$ in a non pipelined scenario.
Upon division into k packets, each of size ${\tfrac {n}{k}}$ and sending them separately, the first packet still needs $(\log _{2}p-1)\left(T_{\mathrm {start} }+{\frac {n}{k}}\cdot T_{\mathrm {byte} }\right)$ to be propagated to $PE_{\mathrm {root} }$ as part of a local prefix sum and this will occur again for the last packet if $k>\log _{2}p$. However, in between, all the PEs along the path can work in parallel and each third communication operation (receive left, receive right, send to parent) sends a packet to the next level, so that one phase can be completed in $2\log _{2}p-1+3(k-1)$ communication operations and both phases together need $(4\cdot \log _{2}p-2+6(k-1))\left(T_{\mathrm {start} }+{\frac {n}{k}}\cdot T_{\mathrm {byte} }\right)$ which is favourable for large message sizes n.
The algorithm can further be optimised by making use of full-duplex or telephone model communication and overlapping the upward and the downward phase.

## Data structures

When a data set may be updated dynamically, it may be stored in a Fenwick tree data structure. This structure allows both the lookup of any individual prefix sum value and the modification of any array value in logarithmic time per operation. However, an earlier 1982 paper presents a data structure called Partial Sums Tree (see Section 5.1) that appears to overlap Fenwick trees; in 1982 the term prefix-sum was not yet as common as it is today.
For higher-dimensional arrays, the summed area table provides a data structure based on prefix sums for computing sums of arbitrary rectangular subarrays. This can be a helpful primitive in image convolution operations.

## Applications

Counting sort is an integer sorting algorithm that uses the prefix sum of a histogram of key frequencies to calculate the position of each key in the sorted output array. It runs in linear time for integer keys that are smaller than the number of items, and is frequently used as part of radix sort, a fast algorithm for sorting integers that are less restricted in magnitude.
List ranking, the problem of transforming a linked list into an array that represents the same sequence of items, can be viewed as computing a prefix sum on the sequence 1, 1, 1, ... and then mapping each item to the array position given by its prefix sum value; by combining list ranking, prefix sums, and Euler tours, many important problems on trees may be solved by efficient parallel algorithms.
An early application of parallel prefix sum algorithms was in the design of binary adders, Boolean circuits that can add two n-bit binary numbers. In this application, the sequence of carry bits of the addition can be represented as a scan operation on the sequence of pairs of input bits, using the majority function to combine the previous carry with these two bits. Each bit of the output number can then be found as the exclusive or of two input bits with the corresponding carry bit. By using a circuit that performs the operations of the parallel prefix sum algorithm, it is possible to design an adder that uses O(n) logic gates and O(log n) time steps.
In the parallel random access machine model of computing, prefix sums can be used to simulate parallel algorithms that assume the ability for multiple processors to access the same memory cell at the same time, on parallel machines that forbid simultaneous access. By means of a sorting network, a set of parallel memory access requests can be ordered into a sequence such that accesses to the same cell are contiguous within the sequence; scan operations can then be used to determine which of the accesses succeed in writing to their requested cells, and to distribute the results of memory read operations to multiple processors that request the same result.
In Guy Blelloch's Ph.D. thesis, parallel prefix operations form part of the formalization of the data parallelism model provided by machines such as the Connection Machine. The Connection Machine CM-1 and CM-2 provided a hypercubic network on which the Algorithm 1 above could be implemented, whereas the CM-5 provided a dedicated network to implement Algorithm 2.
In the construction of Gray codes, sequences of binary values with the property that consecutive sequence values differ from each other in a single bit position, a number n can be converted into the Gray code value at position n of the sequence simply by taking the exclusive or of n and n/2 (the number formed by shifting n right by a single bit position). The reverse operation, decoding a Gray-coded value x into a binary number, is more complicated, but can be expressed as the prefix sum of the bits of x, where each summation operation within the prefix sum is performed modulo two. A prefix sum of this type may be performed efficiently using the bitwise Boolean operations available on modern computers, by computing the exclusive or of x with each of the numbers formed by shifting x to the left by a number of bits that is a power of two.
Parallel prefix (using multiplication as the underlying associative operation) can also be used to build fast algorithms for parallel polynomial interpolation. In particular, it can be used to compute the divided difference coefficients of the Newton form of the interpolation polynomial. This prefix based approach can also be used to obtain the generalized divided differences for (confluent) Hermite interpolation as well as for parallel algorithms for Vandermonde systems.
Parallel prefix algorithms can also be used for temporal parallelization of Recursive Bayesian estimation methods, including Bayesian filters, Kalman filters, as well as the corresponding smoothers. The core idea is that, for example, the solutions to the Bayesian/Kalman filtering problems are written in terms of a suitably defined associative filtering operator such that the prefix "sums" of the filtering operator gives the filtering solution. This allows parallel prefix algorithms to be applied to compute the filtering and smoothing solutions. A similar idea also works for the parallelization of a class of probabilistic differential equation solvers in the context of Probabilistic numerics.
In the context of Optimal control, parallel prefix algorithms can be used for parallelization of Bellman equation and Hamilton–Jacobi–Bellman equations (HJB equations), including their Linear–quadratic regulator special cases. Here, the idea is that we can define an associative operator for a combination of conditional value functions (conditioned on the end-point), and the prefix sums of this operator give solutions to the Bellman equations or HJB equations.
Prefix sum is used for load balancing as a low-cost algorithm to distribute the work between multiple processors, where the overriding goal is achieving an equal amount of work on each processor. The algorithms uses an array of weights representing the amount of work required for each item. After the prefix sum is calculated, the work item i is sent for processing to the processor unit with the number [ ⁠prefixSumValue$_i$/ totalWork / numberOfProcessors⁠ ]. Graphically this corresponds to an operation where the amount of work in each item is represented by the length of a linear segment, all segments are sequentially placed onto a line and the result cut into number of pieces, corresponding to the number of the processors.
Below is a lookup table of quarter squares with the remainder discarded for the digits 0 through 18; this allows for the multiplication of numbers up to 9×9.
| n | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
| ⌊n$^2$/4⌋ | 0 | 0 | 1 | 2 | 4 | 6 | 9 | 12 | 16 | 20 | 25 | 30 | 36 | 42 | 49 | 56 | 64 | 72 | 81 |
If, for example, you wanted to multiply 9 by 3, you observe that the sum and difference are 12 and 6 respectively. Looking both those values up on the table yields 36 and 9, the difference of which is 27, which is the product of 9 and 3.