FlashAttention: the same answer with less memory traffic
Trace stable online softmax, merge tile statistics, and distinguish temporary memory savings from sparse attention or cache compression.
Preparation: Softmax and weighted averages; attention; basic memory concepts.
Plan 25–40 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.
FULL LOCAL NARRATION
Follow the complete explanation.
Narration includes worked solutions. Pause at each practice prompt before continuing. Formula notation has a spoken explanation; all teaching text remains readable.
High-school path. Trace stable online softmax, merge tile statistics, and distinguish temporary memory savings from sparse attention or cache compression. Preparation: Softmax and weighted averages; attention; basic memory concepts. Move between Signal Room, Workbench and Field Notes without losing your section. Pause before each worked solution.
Attention computes scores, converts them to probabilities, and mixes values. A straightforward implementation may write a large score or probability table to device memory and read it again later. That movement can be costly even when arithmetic is fast. FlashAttention reorganizes computation into tiles that use a faster, smaller memory level and carry compact running statistics. Its central dense form preserves the intended attention operation rather than discarding token interactions. Think of finishing parts of a calculation at a small worktable instead of carrying every intermediate sheet to a distant cabinet.
Worked example. A score table with 4,096 rows and 4,096 columns contains 16,777,216 numbers. At two bytes per entry, one such table occupies 32 mebibytes for one head and one sequence. Avoiding that materialized table matters even though every allowed score still contributes to the result.
Less intermediate storage does not imply fewer allowed attention pairs
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. Does avoiding storage of the full score table mean allowed scores were ignored?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. Scores can be computed in blocks, used and discarded while sufficient statistics are retained. Dense attention still accounts for every allowed interaction.
Section 02 / 07
Stabilize softmax before splitting it
Softmax turns scores into weights by exponentiating and normalizing them. Large scores can make raw exponentials overflow. Subtracting the largest score before exponentiation leaves normalized weights unchanged, because every exponential is multiplied by the same factor. This is a numerical rearrangement, not a change in the desired distribution. It gives useful statistics to carry between tiles: the maximum, a sum of shifted exponentials, and a weighted-value numerator. Keep these quantities distinct from the final normalized output; each has a different role in the calculation.
Worked example. Use scores zero and the natural logarithm of three, with values two and ten. Weights are one quarter and three quarters, so output is eight. Subtracting the larger score gives exponentials one third and one, denominator four thirds, and numerator thirty-two thirds. Dividing still gives eight.
m=max(x); l=Σ exp(x−m); u=Σ exp(x−m)v; output=u/l
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. If the same constant is added to every score, should exact softmax output change?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. The common exponential factor cancels. Stable implementations exploit this invariance; finite precision may introduce small differences.
Section 03 / 07
Why averaging tile answers is wrong
Suppose two tiles each compute their own weighted average. Those averages do not tell you how much total probability mass each tile should receive. Combining them equally generally gives the wrong answer. You need normalization information as well as the local output. A tile with much larger scores may deserve much more final weight. Running maxima and denominators allow contributions to be compared on a common scale without constructing a full probability table. This is why a careful reduction can replace the table, while a casual average cannot.
Worked example. Put score zero and value two in the first tile. Put score natural-logarithm-of-three and value ten in the second. Each single-entry tile outputs its value: two or ten. Their ordinary average is six, but global attention outputs eight because the second receives three times the unnormalized weight.
Average(local outputs) generally differs from global softmax output
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. What is missing if you keep only each tile’s final average?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
Relative normalization mass is missing. Retain a compatible maximum and exponential sum, along with the weighted numerator, so contributions can be merged correctly.
Section 04 / 07
Rescale old and new statistics before merging
To merge tiles, select the larger of their maxima. Express both tiles’ sums relative to that common maximum. A tile with a smaller maximum has its denominator and numerator multiplied by the exponential of the maximum difference. Add the rescaled denominators and numerators. Divide after the required tiles have been processed. This prevents earlier contributions from staying at a different numerical scale when a later tile contains a larger score. The running state is compact, but it must preserve exactly the information needed for the final normalization.
Worked example. For the two single-entry tiles above, the common maximum is log three. The first tile scales by one third and the second by one. The denominator becomes one third plus one; the numerator becomes two thirds plus ten. Their ratio is eight. Keeping the old numerator unscaled would be a bug.
m=max(m_A,m_B); l=e^(m_A−m)l_A+e^(m_B−m)l_B; u likewise
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. When a new maximum increases, should only the old denominator be rescaled?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. Both the old denominator and weighted numerator must use the new scale. Rescaling only one changes the resulting average.
Section 05 / 07
Walk through an eight-entry attention row
Workbench uses eight scores, zero through seven, and values ten through eighty. You can multiply scores by a common factor, choose how many positions are causally visible, and vary tile width. It computes the visible row directly and then merges tile statistics. Inspect intermediate maxima, denominators and numerators. Tile width changes how work is grouped, while the reference operation stays the same for fixed scores and visibility. A shorter last tile is valid; no padding value should accidentally enter the intended attention calculation.
Worked example. With multiplier zero, visible scores are equal. If all eight positions are visible, output is the mean of ten, twenty, through eighty: forty-five. With three positions visible it is twenty. Splitting either row into tiles of one, two, three or four entries should preserve output within rounding tolerance.
Fixed scores + fixed mask → tile-independent output, within tolerance
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. If changing tile width substantially changes output while scores and mask stay fixed, what should you suspect?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
Suspect an implementation error, such as incorrect rescaling, a missing entry or inconsistent masking. Tiling should reorganize the same numerical operation.
Section 06 / 07
Understand what the optimization does not remove
FlashAttention does not remove dense attention interactions. For long prefill sequences, dense arithmetic still grows quadratically with sequence length, even though temporary memory and memory traffic improve. It does not automatically shrink the persistent key-value cache used during decoding. Grouped-query attention, latent storage and cache quantization address different aspects of that state. Techniques can interact, but account for their benefits separately. A diagram showing fewer memory transfers is not a diagram proving fewer mathematical dependencies or a different language model.
Worked example. Doubling sequence length from 4,096 to 8,192 quadruples a square score table’s entries. A tiled algorithm can avoid storing that table, but still computes the relevant dense pairs. A simple per-token KV cache doubles under a fixed head layout. These are three different scaling statements.
Dense prefill arithmetic: O(N²d); persistent KV payload: typically O(Nd)
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. Does smaller temporary attention allocation prove a model can store four times as much KV cache?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
No. Temporary workspace and persistent cache are different allocations. Capacity depends on combined peaks, model weights and other runtime memory.
Section 07 / 07
Measure the workload that matters
Correctness comes before speed claims. Compare a clear reference under the same mask, precision and inputs. Then measure the intended workload: training, prefill and one-token decoding stress different resources. Warm up the implementation, synchronize timing where required, report dimensions and include memory peaks. A browser example cannot tell you which GPU kernel is fastest. Its purpose is to make the numerical invariant visible so you know what a correct optimized implementation preserves. Save the result together with the assumptions that made the comparison meaningful.
Worked example. Set multiplier zero and visibility eight, and predict forty-five. Try tile width three: the last tile has two entries, but output should still match. Increase the multiplier and watch later values gain weight. Save direct result, merged result and error in Field Notes without treating browser runtime as a GPU benchmark.
Numerical equivalence first; workload-specific performance second
The displayed notation records the process described in the example. Keep its assumptions and units attached to the result.
Try it yourself. What would establish a speed improvement beyond this experiment?
Pause the narration and explain your reasoning before continuing to the worked solution.
Reveal worked solution
A controlled measurement on target hardware and workload, with matching correctness and configuration. The online-softmax identity alone does not establish latency.
Final checkpoint. Why can we not simply average tile outputs? Option 1: The tiles need their relative normalization mass. Option 2: The values must all be equal. Option 3: Tiling removes every other token.
Pause and choose an answer before continuing.
Reveal worked solution
Option 1 is correct. Local normalized averages lose the relative mass required for a correct global merge.
WORKBENCH / PREDICT → TEST → EXPLAIN
Inspect exact numerical data
These are computed teaching fixtures. No remote AI model or GPU is called by the experiment.
Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.