PaperLeet

FlashAttention-2 Delayed Normalization and Query Blocks

FlashAttention-2 · ICLR 2024 · Hard · 40 minutes

Stream K/V for each query block, maintaining unnormalized outputs and returning logsumexp.

A CPU specification of single-head square attention, including causal masks, tail blocks, numerical stability and autograd; no GPU warp timing.

Functions to implement

FlashAttention-2 Delayed Normalization and Query Blocks

1. Problem

Stream K/V for each query block, maintaining unnormalized outputs and returning logsumexp.

A CPU specification of single-head square attention, including causal masks, tail blocks, numerical stability and autograd; no GPU warp timing.

Source: FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning · Section 3.1.1, Algorithm 1; Section 3.3, query-row work partitioning.

2. Core equations

$$ m\leftarrow\max(m,\max_j S_j),\quad \ell\leftarrow e^{m_{old}-m}\ell+\sum_j e^{S_j-m},\quad U\leftarrow e^{m_{old}-m}U+e^{S-m}V,\quad O=U/\ell,\quad L=m+\log\ell. $$

3. From equations to code

  • flash2_forward(q: Tensor, k: Tensor, v: Tensor, query_block: int, key_block: int, causal: bool = False) -> tuple[Tensor, Tensor] — Attention output and per-row logsumexp.

Query-row blocks independently own their outputs. Each K/V tile updates a stable maximum, denominator and unnormalized numerator. Rescale both old accumulators when the maximum changes, then normalize once at the end.

4. Conventions

q,k:(N,D), v:(N,V), returning O:(N,V) and L:(N,). Scores include 1/sqrt(D). query_block and key_block are positive integers. Causal visibility is key_index<=query_index; each row sees itself. Normalize U by l only after streaming. Both outputs retain gradients.

5. Experiment view

Sweep five uneven block sizes on 13 deterministic tokens, four query/key features and three value features, for causal and full attention; compare outputs and LSE with dense execution.

The chart is generated by the actual submitted kernel during T3 and by the reference during export. Values are synthetic teaching measurements, not GPU throughput or full-model quality claims.

6. Run your implementation

Complete the functions in the Python editor on the right, then click Run tests. Inspect each failed check, update your implementation, and run again. Passing every required check marks the problem as solved and unlocks the notes.

7. Further study

Read the cited section and explain which dimensions or scheduling constraints the kernel preserves. Then extend the experiment beyond the stated fixture while retaining the existing contract. Larger models, real devices, and communication costs require separate measurement.

Read paper · arXiv:2307.08691

Related exercises