Loading editor...

Kernel visualization: online softmax

Softmax needs the maximum of a vector before it can compute any element of it:

Subtracting from each value makes the calculation stable (no overflows) without altering the output.

A naive implementation of a softmax kernel involves three passes across the HBM:

  1. Read the entire sequence to calculate .
  2. Read the entire sequence to calculate the denominator .
  3. Finally, calculate the output values.

Online softmax

Online softmax fuses steps 1 and 2 (shown in the overview), thus requiring only two passes across the HBM. It uses the following formula:

with and . Both and are updated on every element, so a single read of the sequence produces the final and .

Define as the denominator over the first elements, normalized against the maximum known so far:

Split off the last term and rewrite the rest against instead of :

The second line is the only step that does any work, and it is just . The factor does not depend on , so it comes out of the sum, and what is left is exactly .

When the maximum does not move, and the factor is , so the update reduces to an ordinary running sum.

The hardware reads the sequence one tile (a contiguous chunk of numbers) at a time, so each update takes in a whole tile at once instead of a single element.

The tiled version of the same formula is:

Whenever the running maximum moves, every term already accumulated in was computed against the old maximum. Multiplying by fixes all of them at once, because . That single multiply is what removes the need for a separate pass to find first.

Step 3 cannot be fused: no output value can be written until is final, and is not final until the last element has been read.


The naive version: three passes

Each of the three loops is a full trip over . Pass 2 cannot start early, because every exponential it computes needs the final .

  • Pass 1: calculate the max
    • , ,
    • , .
  • Pass 2: calculate the denominator
    • , ,
    • , .
  • Pass 3:
    • , , ,
    • , ,


Online softmax: two passes

  • Pass 1:
    • , .
    • ,
  • Pass 2:
    • ,
    • ,