The Loop Had an Order and the Sum Never Needed It
A loop over an array becomes one function of an index when no trip needs another trip's result. Two questions decide whether a given loop qualifies.
What the loop was doing for you
Here is a loop that adds two arrays, element by element, into a third. It is about the plainest useful loop there is.
void addLoop(float* A, float* B, float* C, int n) {
for (int i = 0; i < n; i++) {
C[i] = A[i] + B[i];
}
}Look at what one trip touches. It reads cell i of A and cell i of B, and it writes cell i of C. It reads nothing that any other trip writes, and it writes nothing that any other trip reads or writes. Trip 7 would come out the same if it ran first, last, or at the same moment as trip 300,000.
So the order was never part of the computation. It was a habit of the machine the loop was written for, which had one place to do arithmetic and had to take the trips one after another. A GPU, as Why a GPU Is Built This Way set out, has a great many slower places instead. To use them, the order has to go.
The body, with the loop removed
Take the loop away and keep the middle line. What is left is a function of the index: given i, add those two cells and store the result.
__global__ void vecAdd(float* A, float* B, float* C, int vectorLength) {
int workIndex = threadIdx.x + blockIdx.x*blockDim.x;
if (workIndex < vectorLength) {
C[workIndex] = A[workIndex] + B[workIndex];
}
}The vendor calls such a function a kernel, and calls each run of it a thread. This course will say function and worker. The program that launches the function asks for as many workers as there are elements, and the guide says plainly that this is often millions. Every worker runs the same few lines. The only thing that differs between them is the index.
The function returns nothing, and that is not an accident of the dialect. A million workers cannot hand back a million return values to one caller. The result of a run is the cell it wrote.
To see that the order really is free, run four workers in a shuffled order over two small arrays, A holding 1, 2, 3, 4 and B holding 10, 20, 30, 40.
| step | run | index | reads | C after the run | what happened |
|---|---|---|---|---|---|
| 1 | 1 | 2 | 3 and 30 | _, _, 33, _ | The worker with index 2 happens to go first. It needs nothing from anyone. |
| 2 | 2 | 0 | 1 and 10 | 11, _, 33, _ | Index 0 goes second. It fills its own cell and disturbs no other. |
| 3 | 3 | 3 | 4 and 40 | 11, _, 33, 44 | Index 3. Still no run has read a cell that another run wrote. |
| 4 | 4 | 1 | 2 and 20 | 11, 22, 33, 44 | The last cell fills. The output is exactly what the loop would have produced. |
If w workers can run at the same moment, n elements take n divided by w rounds, rounded up. With an illustrative 4,096 workers running at once, 1,048,576 elements take 256 rounds where the loop took 1,048,576 trips.
What stops a loop being written this way
Now change the loop slightly. Instead of adding two arrays, keep a running total: each cell of the output is the sum of every input cell up to that point. The body is one line, the output cell i equals output cell i minus 1 plus input cell i.
It looks just as simple, and it cannot be written as the function above. Trip i reads a cell that trip i minus 1 writes. Trip i minus 1 needs trip i minus
- The trips form a chain as long as the array, and a chain has to be walked one link at a time. For 1,048,576 elements that is 1,048,575 links, and 4,096 idle workers do not shorten it by one.
That is the first of two questions to ask of any loop. The second concerns writing. Suppose the loop adds every element into a single total. No trip reads another trip's output cell, but all of them write the same cell. Run two of them together and the cell keeps whichever write landed last.
| a trip reads a cell another writes | two trips write one cell | one function of the index | |
|---|---|---|---|
| adding two arrays | 0 | 0 | 1 |
| scaling every element | 0 | 0 | 1 |
| averaging neighbours into a new array | 0 | 0 | 1 |
| a running total | 1 | 0 | 0 |
| summing into one total | 0 | 1 | 0 |
| counting values into bins | 0 | 1 | 0 |
The third row deserves a second look, because it is the commonest mistake in the other direction. Reading other cells is harmless. What matters is whether anyone writes them during the run. Averaging neighbours from an input array into a separate output array passes. Averaging in place, overwriting the same array, fails the first question.
What becomes of the failures
Neither failure is the end of the matter. A carried value can often be rearranged so that the chain becomes a tree, and a tree of 1,048,576 leaves is only 20 levels deep. Two writers on one cell can be made safe with an update that cannot be interrupted. Those are the subjects of Sharing Within a Block and Two Workers, One Cell later in this course.
| Loop | Reads a cell another trip writes | Two trips write one cell | Fate |
|---|---|---|---|
| Adding two arrays | no | no | one function, as written |
| A running total | yes | no | must be rearranged first |
| Summing into one total | no | yes | staged, later in this course |
| Counting into bins | no | yes | needs a protected update |
The habit to form is to ask the two questions before writing anything. If both answers are no, delete the loop, keep the body, and let the index come from the worker. If either is yes, the loop as written holds an order that the computation depends on, and the rewrite has to deal with that order rather than discard it.
Recap
- A loop whose trips each read their own inputs and write their own output can be written as one function of the index, and the runs of that function may then happen in any order or all at once.
- A loop cannot be written that way when one trip reads a cell that another trip writes, because the chain of results forces an order that no number of workers can shorten.
- A loop also fails when two trips write the same cell, because the result then depends on which run arrived last, and nothing in the device promises an order.
This is the reading half
Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.
The contents