Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 1

Tracing Tiled QKV Data Movement in FlashAttention’s Memory Hierarchy

Recommended resources

Hello! Welcome to your lesson on FlashAttention. Given your extensive background in machine learning engineering and infrastructure, you're likely well aware that the performance of large models is often dictated by memory bandwidth, not just raw computational power. This lesson delves into one of the most significant architectural optimizations in modern transformers that addresses this very issue.

Our goal is to trace the memory-efficient dataflow of the FlashAttention algorithm. By the end of this lesson, you will be able to use a diagram to explain how blocks of the query, key, and value matrices are moved between the slower, large High Bandwidth Memory (HBM) and the faster, smaller on-chip SRAM during a forward pass. This will provide a hardware-aware perspective on a critical component of today's LLMs.

1. The Memory Bottleneck in Standard Attention

Before we dive into the solution, let's briefly establish the problem FlashAttention was designed to solve. The standard self-attention mechanism, while powerful, is notoriously memory-intensive. For a sequence of length , it requires the explicit computation and storage of an attention matrix. As grows, this matrix becomes a major bottleneck, not because of the computations themselves, but because of the repeated reads and writes to and from the GPU's main memory.

On a GPU, there are two key types of memory to consider:

  • High Bandwidth Memory (HBM): This is the large (e.g., 40-80 GB) memory we typically think of as "GPU memory." It has high bandwidth, but access is significantly slower compared to on-chip memory.
  • Static Random-Access Memory (SRAM): This is a much smaller (e.g., ~20 MB) but extremely fast memory located directly on the GPU's streaming multiprocessors (the compute units).

The core issue with standard attention is the need to shuttle the large intermediate attention matrix back and forth between the compute units and HBM. FlashAttention's central insight is to minimize these slow HBM accesses by maximizing the work done in the fast SRAM.

To get a first-hand account of this problem and the high-level solution, let's watch a short segment from a talk by Tri Dao, one of the creators of FlashAttention.

MedAI #54: FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness | Tri Dao

In this video, "MedAI #54: FlashAttention," Tri Dao introduces the concept of IO-awareness and explains why data movement, not computation, is the primary bottleneck in standard attention implementations.

Please watch from the introduction where he introduces IO-aware tiling. Then, jump to the section from the bottleneck, where he details how memory reads and writes in the standard attention mechanism limit performance and sets up the objective for FlashAttention: reducing reads and writes to HBM by exploiting the faster SRAM.


2. Tiling and Online Softmax: The Solution

To avoid materializing the full attention matrix in HBM, FlashAttention employs a technique called tiling. The large Query (Q), Key (K), and Value (V) matrices are partitioned into smaller blocks, or "tiles," that are small enough to be loaded into the fast SRAM.

However, simply processing blocks independently is not straightforward because of the softmax operation. The softmax of a vector depends on all elements in that vector for normalization. You cannot compute the correct softmax for the first half of a vector without seeing the second half.

FlashAttention overcomes this with a clever mathematical trick often called the "online softmax." It restructures the computation to allow for the incremental calculation of attention. In essence, it processes one block at a time, computes a partial result, and maintains running statistics (the maximum value seen so far and the cumulative sum for the denominator). When the next block is processed, it uses these statistics to update the partial result correctly.

This combination of tiling and online softmax allows all the intermediate steps of the attention calculation—the dot product, scaling, and softmax—to be "fused" into a single GPU kernel that operates on tiles within SRAM. This drastically reduces the data traffic to and from HBM.

Designing Hardware-Aware Algorithms: FlashAttention

This article from DigitalOcean provides a concise explanation of the core techniques. It explains how tiling and a restructured softmax computation work together.

Please read the sections titled "Tiling" and "Making Softmax Associative". Focus on how these two concepts enable the attention computation to be performed block-by-block without writing the large intermediate matrices to HBM.


3. Tracing the Dataflow of a Forward Pass

Now, let's trace the movement of data using a diagram that illustrates the FlashAttention forward pass. This diagram shows which data resides in the large, slow HBM and which computations are performed on-the-fly in the fast on-chip SRAM.

This diagram illustrates the memory-efficient dataflow of FlashAttention. Matrices in blue boxes are stored in HBM, while intermediate results in orange dashed boxes are computed in SRAM and are not written to HBM. The process involves loading blocks of Q, K, and V into SRAM, performing local computations, and updating the final output O in HBM.

Let's break down the process step-by-step, following the data:

  1. Initialization: The complete Q, K, and V matrices start in HBM. The output matrix O is also initialized to zeros in HBM.

  2. Outer Loop - Load K and V blocks: The algorithm iterates through the K and V matrices in blocks. In the diagram, it first loads the block and its corresponding value block from HBM into SRAM.

  3. Inner Loop - Load Q block: The algorithm then begins an inner loop over the blocks of the Q matrix. It loads a block of Q (labeled simply as in this simplified diagram, but think of it as one tile ) from HBM into SRAM.

  4. On-Chip Computation (in SRAM): With blocks of Q, K, and V now in fast SRAM, a flurry of computation happens without any HBM access:

    • The score matrix block is computed: . Notice this is in an orange dashed box, meaning it's an intermediate result that is not written back to HBM.
    • The unnormalized attention weights are calculated: . This, too, remains in SRAM.
    • A running statistic for the softmax denominator, , is computed by summing the elements of .
    • A partial output is computed by multiplying the locally normalized attention weights () by the value block . This partial output is written back to HBM.
  5. Iteration and Online Update: The algorithm now moves to the next block of K and V, loading and into SRAM. The same block of Q is used.

    • New scores and weights are computed in SRAM.
    • The crucial "online" step happens here. A new denominator statistic, , is calculated, which incorporates information from both the first and second blocks.
    • The final output for this Q block, , is computed. Notice how it's not a simple sum. The previous output is rescaled by to account for the new, correct normalization factor. The contribution from the current block, , is then added.
    • This updated output block is written back to HBM, overwriting the previous partial result.

This process continues for all blocks of K and V. Once that is done, the inner loop moves to the next block of Q, and the entire process repeats. The key is that the large and matrices are never fully formed in HBM.

To see this process animated, the following video provides a clear visualization that maps directly to the steps we just discussed.

How FlashAttention Accelerates Generative AI Revolution

This video, "How FlashAttention Accelerates Generative AI Revolution," offers an excellent visualization of the tiling and data movement process.

Watch the segment from "visualize these steps". It dynamically shows the partitioning of Q, K, and V, the loading of tiles into SRAM, the computation of partial results, and the update process, reinforcing the trace we just performed on the static diagram.

Finally, to connect this visual understanding to the formal algorithm, you can look at the pseudocode from the original paper.

6803_flashattention_fast_and_memory.pdf

This is the pseudocode from the original FlashAttention paper. It formalizes the loops and operations we've discussed.

In "Algorithm 1 FLASHATTENTION," focus on lines 5-13. Line 5 (for 1 <= j <= T_c do): This is the outer loop over blocks of K and V. Line 6 (Load K_j, V_j from HBM): This is the data movement from HBM to SRAM. Line 7 (for 1 <= i <= T_r do): This is the inner loop over blocks of Q. Line 8 (Load Q_i, O_i, ... from HBM): Loading the Q block and the current state of the output/statistics. Lines 9-11: These are all the on-chip SRAM computations. Line 12 (Write O_i ... to HBM): Writing the updated output block back to HBM. You don't need to implement this, but seeing the code can help solidify the flow of control and data. The variables \ell and m in the algorithm correspond to the running statistics for the online softmax.


Conclusion

In this lesson, we have dissected the IO-aware dataflow of FlashAttention. By tracing the movement of data tiles between HBM and SRAM, you can now see precisely how this algorithm achieves its remarkable efficiency gains.

The key takeaways are:

  • Problem: Standard attention is bottlenecked by memory I/O, specifically reading and writing the large attention matrix to and from slow HBM.
  • Solution: FlashAttention uses tiling to break matrices into blocks that fit in fast SRAM and an online softmax algorithm to process these blocks incrementally.
  • Dataflow: Blocks of K and V are loaded into SRAM in an outer loop, and blocks of Q are processed in an inner loop. All intermediate calculations happen on-chip, and only the final, updated output block is written back to HBM at each step.

This principle of designing algorithms to be "IO-aware"—conscious of the memory hierarchy—is a cornerstone of high-performance computing and is what makes training and inference with very long sequence lengths feasible in modern LLMs. The same principles are applied to create an optimized backward pass, which uses recomputation to avoid storing the attention matrix, further enhancing memory savings.

End of Module,Exit lesson