Dashboard
0%
1
Curious builder0 XP earned · 300 to level 2
0 daysFinish a lesson to begin
Badge collection0 of 6 unlocked
51 small wins to finish your pathNext question →

Q19IntermediateConcept

Why is attention O(n²)? What are FlashAttention and other long-context techniques?

30-second answerSay your answer out loud first, then reveal.

Cost of standard attention

  • Compute: O(n² · d) per layer.
  • Memory for scores: O(n²) per head. At n = 128K, 128K² ≈ 16 billion entries per head per layer, which is impossible to store naively.

FlashAttention (Dao et al. 2022; v2, v3)

  • Key insight: attention is memory-bandwidth bound. The bottleneck is moving data between HBM (large, slow) and SRAM (small, fast).
  • Tiles Q, K and V into blocks, computes the softmax incrementally (online softmax), and never writes the full score matrix to HBM.
  • Exact attention, not an approximation. Memory is linear in n, and it's several times faster.
  • Standard in modern training and inference stacks.

Other long-context techniques

TechniqueIdeaTrade-off
Sliding-window attentionEach token attends to the last W tokensLoses direct long-range links (stacking layers extends reach)
Sparse / block-sparse attentionAttend to selected positionsPattern design; may miss information
Linear attention / SSMs (Mamba) / hybridsO(n) recurrent-style mixingRecall over long contexts can be weaker; hybrids help
Ring attention / context parallelismSplit long sequences across GPUsCommunication overhead
RoPE scaling (YaRN etc.)Extend positional range (Q40)Needs some fine-tuning

This is what real progress feels like.