Phase 04/Faster kernels and memory/FlashAttention
PHASE 04 · Faster kernels and memory

FlashAttention

0%
8 h5 subtopics2 lessons · 1 required
In plain English

Attention compares every word with every other word, which produces a giant table of scores. The naive way writes that whole table to the GPU's main memory, reads it back to normalize it, writes it again, and reads it once more to combine the values. FlashAttention never writes the table. It is like doing a long sum on a notepad at your desk instead of walking to a filing cabinet after every line: you process a small tile of the table in the GPU's fast on-chip memory, keep a running total and a running maximum, and only write the final answer. The arithmetic is the same, the result is the same, but the walking back and forth, which was the slow part, is gone. Memory use drops from quadratic to linear in sequence length.

Why it matters

Attention is the one transformer block whose cost grows with the square of the context length, so FlashAttention is what makes long prompts feasible. Every serving engine depends on a FlashAttention-style kernel for prefill, and understanding the online softmax trick is required to read vLLM, SGLang or any custom attention kernel later.

Hiring signal

Skills this topic builds, with the number of the 46 analysed job postings that ask for each. Companies asking: Anthropic, Anyscale, Baseten, Cerebras, Cohere, CoreWeave, Crusoe, Databricks, ElevenLabs, Fireworks, Hugging Face, Liquid AI, Modal, nvidia, OpenAI, Perplexity, Thinking Machines, Together AI, xAI.See all skills →

Learning objectives

  • Count the bytes moved by naive attention and by tiled attention for given sequence length and head dimension.
  • Implement online softmax and tiled attention in numpy and show it matches the reference exactly.
  • Explain the difference between FlashAttention v1, v2 and FlashDecoding in terms of parallelism.
  • Measure the speed and memory of PyTorch SDPA backends on a GPU across sequence lengths.

Key concepts

IO-aware algorithm
An algorithm designed around bytes moved between HBM and SRAM rather than FLOPs.
Tiling
Splitting Q, K and V into blocks that fit in shared memory and processing one pair of blocks at a time.
Online softmax
Computing softmax over a stream of blocks by tracking a running max and running sum and rescaling earlier partial results.
Recomputation
In the backward pass, recomputing attention scores from Q and K instead of storing them.
Arithmetic intensity
FLOPs per byte moved; tiling raises it so the kernel becomes compute-bound.
FlashAttention-2
Rewrites the loop order to parallelize over sequence length and reduce non-matmul work, roughly 2x over v1.
FlashDecoding
Splits the KV sequence across thread blocks for decode, where there is only one query and parallelism is otherwise scarce.
scaled_dot_product_attention
The PyTorch entry point that dispatches to flash, memory-efficient or math backends.

Subtopics

  1. 1. Memory traffic of naive attention

    Materializing the N x N score matrix costs O(N^2) HBM reads and writes per head; derive the byte count for N=4096, d=128.

  2. 2. Online softmax

    Maintain m (running max) and l (running denominator) per row; rescale previous partial output by exp(m_old - m_new) when the max changes.

  3. 3. Tiled forward pass

    Outer loop over K/V blocks, inner loop over Q blocks (v1) or the reverse (v2); everything stays in SRAM until the final write.

  4. 4. Backward pass and recomputation

    Store only the output and the logsumexp; recompute scores in the backward pass to avoid the N^2 memory.

  5. 5. Variants for inference

    FlashAttention-2 and 3, FlashDecoding and split-KV for single-query decode, and how paged KV layouts plug in.

Resources

Hands-on lessons

L1

Tiled attention with online softmax in numpy

CPU · your Macnotebook120 minrequired

Goal · Implement block-tiled attention that never materializes the full score matrix, prove it matches the reference, and count the bytes each version touches.

  1. 1Write reference_attention(Q, K, V) in numpy that forms the full N x N softmax matrix; use N=1024, d=64, float32.
  2. 2Write online_softmax(row_blocks) that processes a row in chunks keeping running max m and running sum l; verify against np.softmax on random rows.
  3. 3Write flash_attention(Q, K, V, block_q, block_k) with an outer loop over K/V blocks and an inner loop over Q blocks, rescaling the partial output when the max changes.
  4. 4Assert np.allclose(flash, reference, atol=1e-5) for several block sizes including ones that do not divide N evenly.
  5. 5Instrument both versions with a byte counter that adds the size of every array read or written to the "HBM" (anything outside the current tile) and print the totals.
  6. 6Plot bytes moved versus N for N in [256, 512, 1024, 2048] for both versions on a log scale.
Deliverable
A notebook with both implementations, the allclose assertion and the bytes-versus-N plot.
Check
allclose passes for all block sizes; naive bytes grow as N^2 while tiled bytes grow linearly in N.
L2

Benchmark SDPA backends on a T4

Colab T4 · freeexperiment60 minoptional

Goal · Measure time and peak memory of the math, memory-efficient and flash SDPA backends across sequence lengths and find where each stops working.

  1. 1In Colab, create random q, k, v of shape (1, 16, N, 64) in float16 for N in [512, 1024, 2048, 4096, 8192].
  2. 2Use torch.nn.attention.sdpa_kernel to force each backend in turn; wrap each call in torch.cuda.Event timing with warmup.
  3. 3Record torch.cuda.max_memory_allocated after each run and reset between runs.
  4. 4Note which backends raise errors on T4 (flash requires sm80 and newer; mem-efficient should work) and record the error text.
  5. 5Plot time and memory versus N per backend.
Deliverable
A table and plot of time and peak memory per backend per N, plus the error messages for unsupported backends.
Check
The math backend's memory grows quadratically and runs out first; the memory-efficient backend stays near-linear in N.
Fallback
Run the math and CPU-friendly comparison with torch on CPU for N up to 2048 and compare only peak memory via tracemalloc.

Build your own

Build your own FlashAttention in Triton

TritonColab T4 · free~10 h

A tiled, online-softmax attention kernel for a T4, grown from a numpy prototype to a causal, autotuned Triton kernel with a split-KV decode variant.

The real thing: github.com/Dao-AILab/flash-attention ↗

How you know a stage passes

Write tests/test_flash.py first. Every stage compares your kernel's output with torch.nn.functional.scaled_dot_product_attention computed in fp32 (math backend) on seeded fp16 inputs, with atol and rtol of 1e-2, over sequence lengths 128 to 4096 and head_dim 64. bench.py reports TFLOP/s and peak memory next to the math, memory-efficient and flash SDPA backends. On Colab run `!pytest -q`; on your Mac set TRITON_INTERPRET=1 to run the same tests on CPU for correctness only. A stage is done when its test passes and all earlier tests still pass.

Stages, in order. Each one leaves you with something that runs.0/6
  1. 01online softmax in numpy for one query row
    A function walks K and V in tiles, keeping a running max, running sum and running output, and never materialises the full score row.
    test · For 50 random seeds and tile sizes 16, 32 and 64 the result matches softmax(q K^T / sqrt(d)) V to 1e-6; the peak intermediate array has tile_size elements, not N.
  2. 02a Triton kernel for one Q tile
    One program handles one (batch, head, Q-tile) and loops over K/V tiles with fp32 accumulators, non-causal, fp16 in and out.
    test · allclose against the SDPA reference for N in 128, 512, 1024 and the kernel compiles for BLOCK_M and BLOCK_N of 64; a deliberately wrong scale (sqrt(d) omitted) fails the test, proving the test has teeth.
  3. 03causal masking with tile skipping
    Tiles entirely above the diagonal are skipped by the loop bounds and the diagonal tile is masked with -inf before the online update.
    test · Output matches SDPA with is_causal=True; a tile counter written to a side buffer shows the kernel visited within 10 percent of N_tiles * (N_tiles + 1) / 2 tiles rather than N_tiles squared.
  4. 04autotune and measure against SDPA
    triton.autotune over BLOCK_M, BLOCK_N, num_warps and num_stages picks the configuration for the T4, and bench.py produces the comparison table.
    test · At N 4096, 16 heads, head_dim 64, batch 1, your kernel reaches at least 40 percent of the throughput of the fastest SDPA backend on the T4; your peak memory at N 4096 is within 5 percent of N 1024 while the math backend's grows about 16x.
  5. 05flash-decoding for a single query over a long KV cache
    A seq_q = 1 kernel splits the KV length across programs, each producing a partial (max, sum, output), with a second tiny kernel that combines them.
    test · Matches the reference for KV lengths 512 to 8192 at batch 1; at length 8192 it is at least 1.5x faster than the stage-3 kernel called with a single query row.
  6. 06Stage 6 (optional), the backward pass
    dQ, dK and dV kernels recompute the scores from the saved logsumexp instead of storing the N x N probabilities.
    test · Gradients match torch autograd on the fp32 reference with max abs error below 1e-2 on fp16 inputs for N 512; no tensor of shape (N, N) is allocated, checked with torch.cuda.max_memory_allocated.

No GPU? Run all correctness stages on your Mac with TRITON_INTERPRET=1 (numpy interpreter) and skip the throughput and memory assertions in stages 4 and 5, recording them as not measured.

Knowledge check

QWhy is FlashAttention faster even though it does the same or slightly more FLOPs than naive attention?

Naive attention is memory-bound on reading and writing the N x N score matrix to HBM; FlashAttention keeps tiles in SRAM and removes most of that traffic.

QWhat two running statistics does online softmax keep per row, and what happens when a new block has a larger max?

The running max m and the running denominator l; the previous partial output and l are multiplied by exp(m_old - m_new) before adding the new block.

QWhat does FlashAttention store for the backward pass instead of the attention matrix?

Only the output O and the per-row logsumexp; scores are recomputed from Q and K during the backward pass.

QWhy does decode need a different kernel (FlashDecoding) than prefill?

Decode has a single query row per sequence, so parallelizing over queries gives too few thread blocks; FlashDecoding splits the KV sequence instead and reduces the partial results.

Completion

  • All 5 subtopics marked done
  • All 1 required lessons done
  • All subtopics marked completed.
  • Lesson l1 passes allclose for multiple block sizes and the bytes plot is saved.
  • Can derive the online softmax rescaling formula on a whiteboard.
Topic progress is derived; it reaches 100% when both checks above pass.Next recommended topic →