MLCrack

    LLMS & TRANSFORMERS · INTERVIEW QUESTION

    Explain FlashAttention. How does it achieve sub-quadratic memory while maintaining exact attention?

    ⚫ expert · Transformer Architecture

    Hint: Think about tiling, SRAM vs HBM, and the online softmax trick.

    Answer

    FlashAttention is an IO-aware exact attention algorithm. Standard attention materializes the N×N attention matrix in GPU HBM (slow). FlashAttention:

    1. Tiles Q, K, V into blocks that fit in SRAM (fast on-chip memory)
    2. Computes attention block-by-block using the online softmax trick (maintains running max and sum)
    3. Never materializes the full N×N matrix.

    Result: O(N2d)O(N²d) FLOPs (same as standard) but O(N)O(N) memory instead of O(N2)O(N²), and 2-4x faster due to reduced HBM reads/writes. FlashAttention-2 further optimizes parallelism and work partitioning. This enabled training with much longer context windows (e.g., 128k tokens).