LogoCookLLM Docs
LogoCookLLM Docs
HomeCookLLM

Principles

Tokenization
Tokenization BasicsBPE AlgorithmGPT TokenizersBPE Training Engineering
Model Architecture
Transformer LM
From token ids to logitsEmbedding and LM Head
Attention Mechanisms
From Self-Attention to GQAAttention Sink
Position Encoding
Position Encoding BasicsRoPE Math DerivationRoPE ImplementationLength Extrapolation
GPU Programming Basics
GPU Architecture BasicsTensor LayoutTriton Basics: Vector Add
FlashAttention
Flash Attention PrinciplesFrom Naive Implementation to Auto-TuningBlock Pointers and Multi-Dim SupportCausal Masking OptimizationGrouped Query AttentionBackward Pass Implementation
Distributed Training
Data ParallelismZeRO OptimizerFully Sharded Data ParallelTensor ParallelismPipeline ParallelismMulti-Dimensional Hybrid Parallelism

Hands-on Training

Overview
Pretraining
Pretraining DataTokenizer TrainingModel ArchitectureData PipelineTraining LoopMonitoring and Validation
X (Twitter)
SystemsFlashAttention

Flash Attention Principles

Premium

Through interactive visualizations, gain a deep understanding of Flash Attention's core techniques: the memory bottleneck, Online Softmax, and tiled matrix multiplication.

The Memory Bottleneck in Standard Attention

Before we dive into the code implementation of Flash Attention, we must first answer a foundational question: why is the standard attention formula Softmax(QKT)VSoftmax(QK^T)VSoftmax(QKT)V still not fast enough on modern GPUs?

GPU Memory Hierarchy: SRAM and HBM

First, we need to establish an extremely important concept: in the GPU architecture, all computation (such as matrix addition and multiplication) must happen in the SRAM (Shared Memory) that sits close to the cores.

This means that even if your VRAM (HBM) is as large as 80GB, the data must first be "moved" into the SRAM, which is only tens of MB in size, before it can be processed by the compute cores.

The Logical Trap in the Standard Implementation

In the "naive" implementations of deep learning frameworks such as PyTorch, the Attention computation is split into multiple independent operators (Ops). This leads to a serious efficiency problem:

  1. Step 1 (QKTQK^TQKT): the GPU moves QQQ and KKK from HBM to SRAM and computes the score matrix SSS.
  2. The intermediate result is too large: since the shape of SSS is (N,N)(N, N)(N,N), for long sequences this matrix is so large that SRAM simply cannot hold it.
  3. Forced write-back: the GPU has no choice but to "evict" this giant matrix SSS from SRAM and write it back to the slow HBM.
  4. Repeated back-and-forth: when it comes to the next step of computing Softmax(S)Softmax(S)Softmax(S), the GPU has to go back to HBM and move the SSS it just stored back into SRAM again.
# The IO nightmare of the standard Attention implementation
def standard_attention(Q, K, V):
    # 1. HBM -> SRAM (compute) -> HBM (store S)
    S = Q @ K.T

    # 2. HBM (read S) -> SRAM (compute) -> HBM (store P)
    P = softmax(S)

    # 3. HBM (read P) -> SRAM (compute) -> HBM (store O)
    O = P @ V
    return O

This repeated I/O round trip of "move in -> compute -> evict -> move back" is the biggest performance killer.

The Bandwidth Gap Between SRAM and HBM

You might ask: how much impact can storing back to HBM and reading it back again really have?

Comparison of Speed Differences

Storage typeCapacity example (A100)BandwidthSpeed metaphor
SRAM (shared memory)~20 MB~19 TB/sF1 race car 🏎️
HBM (VRAM)40~80 GB~1.5 TB/sordinary sedan 🚗

SRAM's bandwidth is typically more than about 10 times higher than HBM's.

The Essence of the Bottleneck: IO-bound

Because of this speed gulf, if the algorithm keeps moving intermediate data back and forth between HBM and SRAM, an awkward situation arises:

The GPU's powerful compute cores spend most of their time "idling," waiting in agony for data to be delivered from the slow HBM.

This state is called IO-bound, meaning that the compute capability is held back by the memory transfer speed.

To get a quantitative feel for it: in standard Attention, the time spent reading and writing the N×NN \times NN×N intermediate matrices SSS and PPP far exceeds the time spent actually performing the matrix multiplication computation.

The Capacity Limit of SRAM

Since SRAM is so fast, why not just put the entire Attention matrix in SRAM, finish computing, and be done? This is where rigid physical and economic constraints come into play:

Physical Constraints and Cost

SRAM has an extremely low storage density, which makes its cost extremely high. According to relevant materials (such as the background cited in the FlashAttention paper):

  • Cost: manufacturing an 80GB capacity SRAM memory could cost as much as $13,000 (an order-of-magnitude estimate).
  • Comparison: an HBM of the same capacity costs only about $2,000.

The Capacity Limit

In real hardware, an A100's HBM can reach 80GB, but SRAM is usually only 192 KB / SM (per streaming multiprocessor). Because of this capacity limit, you cannot cram the entire N×NN \times NN×N attention matrix into SRAM all at once. As the sequence length NNN grows, the size of the intermediate matrix explodes at O(N2)O(N^2)O(N2).

The Core Idea: Optimizing IO Complexity

The core logic of Flash Attention lies right here: since SRAM is expensive and small but fast, while HBM is large and cheap but slow, we must abandon the fantasy of "reading and writing everything at once."

We need to introduce two core ideas:

  1. Tiling: split the data into "small blocks" that can fit into SRAM.
  2. Kernel Fusion: inside SRAM, complete the QKTQK^TQKT, Softmax, and multiplication by VVV in one go, writing only the final result OOO back to HBM in the last step.

Avoiding Spilling the Intermediate Matrix to Memory

In this way, we never even generate (nor write to HBM) that huge N×NN \times NN×N intermediate matrix.

MethodHBM read/write volumeComplexity
Standard AttentionO(N2)O(N^2)O(N2)as the sequence gets longer, IO explodes
Flash AttentionO(N)O(N)O(N)linear growth, hugely saving bandwidth

Log in to continue reading

This is premium content. Please log in to access the full article.

Flash Attention

Deeply understand Flash Attention principles and Triton implementation

From Naive Implementation to Auto-Tuning

Write your first Flash Attention kernel and use Auto-Tune for performance optimization.

Table of Contents

The Memory Bottleneck in Standard Attention
GPU Memory Hierarchy: SRAM and HBM
The Logical Trap in the Standard Implementation
The Bandwidth Gap Between SRAM and HBM
Comparison of Speed Differences
The Essence of the Bottleneck: IO-bound
The Capacity Limit of SRAM
Physical Constraints and Cost
The Capacity Limit
The Core Idea: Optimizing IO Complexity
Avoiding Spilling the Intermediate Matrix to Memory
The Principle of Online Softmax
The Limitations of Offline Algorithms
Online Algorithms and Dynamic Correction
Deriving the Correction Formula
Numerical Demonstration: Using the Sequence [3, 2, 5, 1] as an Example
A Summary of the Mathematical Principle Behind Flash Attention
Tiled Matrix Multiplication (Tiling)
Why Do We Need to "Tile"?
Visual Demonstration: The Tiled Computation Flow
Key Things to Observe
Combining Tiling with Attention
Comparing Loop Strategies: V1 vs V2
Interactive Guide to the Diagram
Softmax Correction in Tiled Attention
The Naive Implementation: The Limitations of Local Softmax
The Solution: Online Rescaling
Initialization
Inner Loop: Traversing the K-Blocks
Final Step: Normalization
Complete Algorithm Pseudocode
The Full Picture of the Algorithm
Summary