Back to journal Where did the attention matrix go?

Where did the attention matrix go?

How FlashAttention computes a weighted average one block at a time.

A tile of query and key scores updates a running maximum, weight sum and weighted value sum for each query.

Give one attention head 4,096 tokens. A diagram of self-attention now has 4,096 rows and 4,096 columns. At two bytes per entry, a single square array of those scores occupies 32 MiB. Yet the next part of the model asks for one vector per token. Who needs the other 16 million numbers, and for how long?

Pick one query position and follow its row. Suppose you have read half the keys and a much better match arrives in the second half. Every earlier attention weight has to shrink. It seems you must have kept those weights somewhere to correct them. The way out is to ask what all the corrections have in common. Finding that common factor explains how a GPU can compute dense attention in tiles and discard the individual scores almost as soon as it creates them.

What one row owes the next layer

For a single query, let each key have a score s, its dot product with the query divided by the square root of the key width. A larger score gives the corresponding value vector more influence. To compute the output component for one feature, multiply each value’s feature by the exponential of its score, sum the products, then divide by the sum of the exponentials. The denominator is the same for every feature of that row. This is the scaled dot-product attention in the original Transformer, written out one component at a time. [1]

weight of key j = exp(sⱼ) / Σₖ exp(sₖ)
output          = Σⱼ exp(sⱼ) vⱼ / Σₖ exp(sₖ)

Notice where the division sits in the second line. You can postpone it until every key has contributed. Carry a weighted sum of the values and a scalar sum of the weights. Once a value has contributed to both, you can discard its score. The next key needs only the two sums. Rabe and Staats develop this observation as a way to compute attention with limited working memory. There is one practical catch if you translate those two sums directly into code. The exponential of a large score can overflow even when the final weighted average is small. [2]

How to change a maximum halfway through

Imagine two equally good keys, each with score 1,000. Their weights are exactly one half apiece. A program that first tries to represent the exponential of 1,000 in an ordinary 64-bit float has already lost the calculation. Subtract 1,000 from both scores first and the problem vanishes. The two exponentials are now both one. The answer survives the subtraction because it multiplies every term in the numerator and denominator by the same constant.

You can use the largest score in the row as the number to subtract. That keeps each shifted exponential at most one. But the largest score in the whole row is precisely the information you lack halfway through it. Milakov and Gimelshein give an online update for the softmax denominator. Keep the largest score seen so far, and measure the sum relative to that maximum. When a later score raises the maximum from m to M, multiply the old sum by exp(m − M). Every old term is now expressed relative to M. The same multiplication works component by component on the weighted value sum. [3] [2]

Choose numbers that make the adjustment visible. Two keys have score zero and carry scalar values two and six. Their running maximum is zero, their denominator is two, and their weighted sum is eight. The answer so far is four. A third key arrives with score ln(2) and value ten. In the original scale its exponential weight is two, so you can already predict the answer by hand. It is (2 + 6 + 2 × 10) / (1 + 1 + 2), which is seven.

Now do it without going back to either old key. The new maximum is ln(2). The old sums both get multiplied by exp(0 − ln(2)), or one half. That turns the old denominator into one and the old weighted sum into four. The new key, measured against its own score, contributes one to the denominator and ten to the weighted sum. Divide fourteen by two. You get seven again. The earlier keys collectively have half the influence in the completed answer, and the algorithm has adjusted them without knowing how they split that influence between themselves.

What goes wrong if you average the tiles

There is a tempting shortcut when splitting keys across workers. Ask each worker for its local attention output, then average those outputs. The example above makes a surprisingly bad test for this bug. Its two local answers are four and ten. Their ordinary average is seven. A broken implementation passes because the two groups happen to have the same total exponential weight.

Change just the third score from ln(2) to zero. Both local answers stay exactly the same. This time all three keys have equal weight, so the full answer is (2 + 6 + 10) / 3, or six. Any merger that only receives four and ten must return the same answer in both experiments. It has thrown away information that the global result depends on. That is a stronger diagnosis than observing that the numbers differ on a random input. It identifies two inputs the proposed algorithm cannot distinguish.

A worker can instead return three things for its block of visible keys. These are its maximum, its sum of shifted exponentials, and its weighted value sum in that same scale. The merge below handles two nonempty blocks and one scalar value feature. For a full head, the last sum becomes a vector. In exact arithmetic, merging any partition of the same visible keys produces the same final quotient. Different floating-point addition orders can round differently.

from math import exp, isclose, log

def merge(left, right):
    m1, mass1, total1 = left
    m2, mass2, total2 = right
    maximum = max(m1, m2)
    a, b = exp(m1 - maximum), exp(m2 - maximum)
    return maximum, a * mass1 + b * mass2, a * total1 + b * total2

first_pair = (0, 2, 8)
for score, expected in [(log(2), 7), (0, 6)]:
    last_key = (score, 1, 10)
    _, mass, total = merge(first_pair, last_key)
    assert isclose(total / mass, expected)

What the GPU gets to forget

Now give a GPU a tile of queries and a tile of keys and values. It can form a small rectangle of scores, update the summary for each query row, and retire the rectangle once its contribution has been counted. A later tile may raise the running maximum for one row and leave the next row’s maximum alone. Each query therefore needs its own normalization state. If one query has unusually large scores, using its maximum for every row could push all the shifted exponentials of another row toward zero in finite precision. [4]

The original FlashAttention paper arranges this work around two kinds of GPU memory. High-bandwidth memory holds the large input and output arrays. Smaller, on-chip memory holds the tiles being processed. A straightforward sequence of separate matrix multiplication, softmax and matrix multiplication operations can write a full score or probability array to device memory and read it back. In a fused attention kernel the short-lived rectangles can be consumed on chip. This saves transfers even though every permitted query–key pair still contributes to dense attention. For a square causal head the permitted triangle contains T(T + 1)/2 pairs. Doubling sequence length still roughly quadruples the number of pairs. [4]

The distinction also matters during training. Gradients require information from the forward computation. Keeping every attention probability until the backward pass would bring back the square array. The original algorithm retains the output and row normalization statistics and uses the queries and keys to reconstruct probabilities for tiles during the backward pass. Extra arithmetic buys a reduction in what has to be stored and read. How much time that saves on a particular workload depends on the hardware and implementation. The 32 MiB at the start was a size calculation for one array. It cannot predict a runtime. [4]

Return to the question of who needs the grid. If a visualization asks for every attention weight, the grid itself becomes a requested output and has 16,777,216 entries in our example. If the next layer asks only for the context vectors, the grid is one possible intermediate. The most revealing line in the calculation is the division you can move outside the sum. Once you do that, a square in an architecture diagram stops dictating what must occupy memory.

Sources

  1. Vaswani et al. (2017), §3.2.1, the definition of scaled dot-product attention. Attention Is All You Need.
  2. Markus N. Rabe and Charles Staats (2021 preprint, revised 2022), §§2–4, accumulating contributions for a single query and summarizing chunks. Self-attention Does Not Need O(n²) Memory.
  3. Maxim Milakov and Natalia Gimelshein (2018), Algorithm 3 and §3.1, updating and merging the softmax normalizer. Online Normalizer Calculation for Softmax.
  4. Tri Dao et al. (2022), §3.1, Algorithm 1 and Appendix B, tiling, memory traffic and recomputation during backpropagation. FlashAttention.

Claims to verify

  • Multiply 4,096² by two bytes and divide by 2²⁰. The 32 MiB figure covers one dense array for one head and one sequence.
  • Run both cases in the example. Changing only the last score leaves both local averages unchanged and changes the correct global result from seven to six.
  • Expand exp(s − m) × exp(m − M) to verify the rescaling identity. The argument assumes finite scores and at least one visible key in each summarized block.
  • Compare the stored quantities and the reconstructed tiles with §3.1 and Appendix B of Dao et al. The memory claim concerns the full intermediate attention matrix. The dense computation still evaluates quadratically many permitted pairs.