Macalinao StudioLearnAll enriched lessons ↗
College path · 7 sectionsSwitch to high school ↗

College / LONGER LESSON flash

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.

Section 01 / 07

The cost of moving intermediate results

College 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.

The distinction is input-output traffic between memory levels, not file input-output. GPU high-bandwidth memory is larger but more costly to access than on-chip storage. Kernels use parallel matrix operations and carefully chosen layouts. Our browser experiment demonstrates the numerical reduction for one row; it is not a GPU kernel or speed benchmark.

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.

For scores x_i and scalar values v_i, choose m=max x_i, define l=sum exp(x_i-m), and u=sum exp(x_i-m) v_i. The output is u/l. For vector values, u is a vector with the same scalar denominator. Masked entries contribute zero; an entirely masked row needs an explicit policy rather than unguarded zero division.

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.

Each tile can be summarized by a triple: local maximum m, shifted exponential sum l, and shifted weighted numerator u. This triple is sufficient for the softmax-weighted sum over that tile. A normalized output u/l alone discards information required for a correct merge. Tiles must describe disjoint portions of the intended row, without duplicated entries.

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.

For triples A and B, let m=max(m_A,m_B), alpha=exp(m_A-m), beta=exp(m_B-m). Set l=alpha l_A+beta l_B and u=alpha u_A+beta u_B. In exact arithmetic, this gives the statistics of their union. Floating-point rounding can depend on merge order, so implementation equality is assessed with tolerances.

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.

The score multiplier is a teaching control, not a learned model parameter or complete sampling-temperature setting. Causal visibility retains a prefix of eight entries. This is one attention row at a chosen query position; full sequence attention repeats the operation with each query’s scores and mask. Apply masking before computing softmax statistics.

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.

Training can recompute intermediates during backward propagation instead of storing the full attention matrix. FlashAttention-2 improves work partitioning and reduces non-matrix-multiplication overhead. Support and performance depend on hardware, dimensions, dtype, masks and kernel version. Exact attention means the same mathematical operator, not guaranteed bit-for-bit equality across floating-point execution orders.

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.

Test awkward tile boundaries, causal prefixes, extreme logits and supported data types. Gradient checks and dropout-state handling matter for training kernels but are outside this forward-only fixture. Distinguish kernel latency from application throughput, which includes other layers and scheduling. Record implementation versions and configurations for reproducibility.

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. If a new maximum is larger, what must be rescaled? Option 1: Only the denominator. Option 2: Both the old denominator and weighted numerator. Option 3: Neither.

Pause and choose an answer before continuing.

Reveal worked solution

Option 2 is correct. Both statistics must use the same common maximum before contributions are added.

Continue the learning path

Sources and scope

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.

Reset this college path?

This removes only this path’s notes, progress and experiments from this browser.