From a Matrix Multiply to a Forward Pass
A Run of Small Operations Joined Into One Pass Pays for One Start and One Trip Through Memory
Last timeEverything That Is Not a Multiply
Five element by element operations in a row read and write the table five times and start five times. Joined into one, they do both once, and the saving is exact.
The last lesson ended on the only repair available: start fewer operations. This lesson does it, and finds that the same move saves memory traffic as well.
One worker, one number, every step
Take five element by element operations in a row on a table of numbers: add a constant, multiply by a scale, replace negatives with zero, and so on. Run apart, each is a function of its own. It reads the whole table from main memory, changes every number and writes a whole table back. The next one reads that table straight back in.
Nothing in any of the five needs a number's neighbours. So one worker can fetch one number, apply all five steps while holding it, and write it once. Compilers for these frameworks call this fusion.
apart, five functions started one after another:
a = x + bias
b = a * scale
c = larger of b and 0
d = c - mean
y = d * gain
joined, one function, each worker doing this for its own i:
v = x[i]
v = v + bias
v = v * scale
v = larger of v and 0
v = v - mean
y[i] = v * gainThe documentation of one such compiler, XLA, works a smaller case: a sum over . Run apart it starts three functions, one for the multiplication, one for the addition and one for the sum. Joined, it starts one, and the documentation points out that the two in-between results are never written to memory at all.
The lesson stops here
5 more paragraphs to go
You have read the opening. The rest of the argument, the problems that check whether it landed, and the lines worth keeping at the end all come with a plan.
The first lesson of every course in the library reads the whole way through, free, so you can see exactly what the rest of them are.
See the planThe contentsThis 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