Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Attention Mechanism: Computation & Memory Patterns

Introduction

Welcome to the next lesson in our module on parallelizing machine learning workloads. In our previous lesson, we examined how convolution operations are transformed into matrix multiplications (GEMM) via the im2col technique. The key insight was that by reformulating a complex operation into a primitive that is highly optimized on the hardware, we can achieve significant performance gains. A central theme was the idea of implicit transformation—performing the computation as if a large, unrolled matrix existed, without ever materializing it in memory, thus saving memory and bandwidth.

Today, we will apply this same system-level thinking to another cornerstone of modern AI: the attention mechanism. Our learning outcome is to analyze the computational and memory access patterns of the attention mechanism in Transformers.

You will dissect the standard attention algorithm, identify its quadratic scaling properties that create a significant performance bottleneck, and understand why it is fundamentally limited by memory bandwidth. We will then explore how an I/O-aware algorithm, FlashAttention, restructures the computation to overcome this bottleneck, drawing a direct parallel to the "implicit" philosophy we saw with im2col. This analysis is crucial for designing systems capable of handling the long sequence lengths required by today's state-of-the-art models.

1. The Standard Attention Algorithm: A Computational Breakdown

The self-attention mechanism allows a model to weigh the importance of different tokens in an input sequence when computing the representation of each token. The standard formulation, scaled dot-product attention, is defined as:

Where:

  • , , and are the Query, Key, and Value matrices, each with shape , where is the sequence length and is the head dimension.
  • is the dimension of the keys, used for scaling.

The computation proceeds in three main steps:

  1. Score Calculation: . This is a matrix multiplication of a matrix with a matrix, resulting in an attention score matrix, .
  2. Normalization: . The scores are scaled, and a softmax function is applied row-wise to produce the attention probabilities, . This matrix is also .
  3. Output Calculation: . The attention probabilities are used to compute a weighted average of the value vectors. This is another matrix multiplication, between an matrix and an matrix, producing the final output of shape .

To begin, let's watch a brief overview of this process and the primary challenge it introduces.

FlashAttention - Tri Dao | Stanford MLSys #67

The following clip from a Stanford MLSys seminar by Tri Dao, the author of FlashAttention, clearly defines the standard attention computation and highlights the core problem associated with its intermediate matrices.

Watch the segment from 10:07 to 13:16. Focus on how the input matrices (Q, K, V) lead to the creation of a large, intermediate N x N attention matrix and why this matrix's quadratic scaling with sequence length (N) is the central issue.

This next video provides a helpful animated visualization of the data flow in this "naive" implementation, showing how data moves between the GPU's main memory and its compute cores.

How FlashAttention Accelerates Generative AI Revolution

This animation illustrates the data movement required by the standard attention algorithm.

Watch from 0:56 to 3:01. Pay attention to the repeated transfers of large matrices (S and A) back and forth between High-Bandwidth Memory (HBM) and the GPU cores. This visualization will be key to understanding the memory bottleneck.

2. The Computational and Memory Bottleneck

As the videos highlighted, the standard attention mechanism has two critical performance characteristics rooted in its dependence on the sequence length .

Computational Complexity

The computation is dominated by the two matrix multiplications:

  • : floating-point operations (FLOPs).
  • : FLOPs.

The total computational cost is . This quadratic scaling means that doubling the sequence length quadruples the amount of computation required.

Memory Complexity and Access Pattern

The more severe problem lies in the memory footprint and access pattern.

  • The inputs and output are of size .
  • However, the intermediate matrices and are of size .

For a sequence length of 64k, a single matrix of 16-bit floats requires GB of memory. This is a massive amount just for one attention head in one layer of a model, and it must be written to and read from the GPU's slow High-Bandwidth Memory (HBM).

This leads to a classic systems bottleneck. Modern GPUs have immense computational power (TFLOP/s), but their memory bandwidth—the speed at which they can read from HBM—is far more limited. When an algorithm requires moving vast amounts of data, the compute units sit idle waiting for data to arrive. This makes the algorithm memory-bandwidth bound.

The Roofline model provides a formal way to analyze this.

Roofline Model with Sub-Optimal Resource Utilization
A Roofline model plots an algorithm's performance (Throughput) against its arithmetic intensity (FLOPs per byte of data moved). An algorithm is memory-bound if its arithmetic intensity is too low to saturate the hardware's peak compute, leaving its performance constrained by the memory bandwidth slope.

Let's examine a quantitative analysis that applies this model to naive attention.

Kernel-Level GPU Optimization for Transformer Attention

This technical article provides an excellent Roofline analysis of the attention mechanism. It mathematically demonstrates why the naive implementation is fundamentally memory-bound.

Read the section titled '2.2 The Memory Bandwidth Bottleneck'. The key things to understand are: The calculation of arithmetic intensity for attention. The comparison of this intensity to the H100 GPU's 'compute-bound threshold'. The conclusion that materializing the N² attention matrix keeps the operation far below this threshold, making it memory-bound.

The analysis is clear: the need to read and write the matrix to HBM torpedoes the arithmetic intensity, ensuring that performance is dictated by memory bandwidth, not compute power.

3. Solving the Bottleneck: IO-Aware Kernel Fusion

To overcome this, we need an algorithm that avoids materializing the full matrix. This is the core innovation of FlashAttention. It is an IO-aware algorithm, meaning it is explicitly designed around the memory hierarchy of the GPU, aiming to minimize data movement between slow HBM and fast on-chip SRAM.

The approach is conceptually similar to the implicit GEMM from our last lesson. It fuses the multiple steps of attention (score calculation, softmax, output calculation) into a single GPU kernel. This kernel computes the final output by loading small blocks (tiles) of the input matrices into the fast SRAM, performing the attention calculation for that block, and updating the output, without ever forming the full or matrices in HBM.

This is made possible by two classical techniques applied to attention:

  1. Tiling: The computation is broken down into blocks. The kernel iterates through tiles of the Key and Value matrices, computing a portion of the output for a given tile of the Query matrix.
  2. Online Softmax: A clever mathematical trick allows the softmax to be computed correctly without having the full row of the matrix at once. As each new tile is processed, it updates a running maximum and a running sum, allowing it to correctly scale the previous partial results and incorporate the new ones.

Let's delve into these concepts.

[PDF] 20: LLM-4 (flash attention, deepseek-v3 review, ending words)

These scribe notes from a graduate course provide a clear, mathematical derivation of the 'online softmax' trick that enables FlashAttention's tiled approach.

Read sections '3.5 Optimizing Softmax: Fusing the First Two For Loops' and '3.6 Deriving Flash Attention via Further Fusing'. You don't need to memorize the formulas, but follow the logic of how the accumulator d' and the output o' can be defined recursively, allowing them to be computed 'online' as you process the sequence piece by piece.

Now, let's see how these ideas—tiling and online softmax—are combined to create an efficient, IO-aware algorithm.

FlashAttention - Tri Dao | Stanford MLSys #67

The following segments from the Stanford seminar and the animated explainer will walk you through the full FlashAttention algorithm.

First, watch from 13:16 to 28:32 in the 'FlashAttention - Tri Dao' video. This section explains the GPU memory hierarchy, frames the goal as exploiting this asymmetry, and details the tiling technique powered by the online softmax math.

How FlashAttention Accelerates Generative AI Revolution

This animation provides a visual walkthrough of the tiled computation we just heard about, which can help solidify the concept.

Watch from 8:19 to 11:28. The animation shows how tiles of Q, K, and V are loaded into SRAM, a partial result is computed, and the final output is updated iteratively. Notice how the full N x N matrix is never created.

4. Analyzing the Optimized Pattern

FlashAttention fundamentally changes the memory access pattern of the attention mechanism.

  • Computational Pattern: The total number of FLOPs is actually slightly higher than the naive approach. This is because during the backward pass (for training), the attention scores, which were never saved, must be recomputed. This is a classic speed-memory trade-off: we perform more (cheap) computation to save on (expensive) memory access.
  • Memory Access Pattern: This is where the major optimization occurs.
    • The intermediate matrices are never written to or read from HBM. They exist only ephemerally as small tiles within the fast on-chip SRAM.
    • The memory complexity of the operation is effectively reduced from to , as the main memory accesses are just for the Q, K, V, and O matrices.
    • This dramatic reduction in HBM traffic significantly increases the arithmetic intensity, moving the operation from the memory-bound portion of the Roofline model much closer to the compute-bound peak. This allows the GPU's powerful compute units to be utilized much more effectively.

This final clip explains the recomputation strategy.

FlashAttention - Tri Dao | Stanford MLSys #67

To complete our analysis, let's look at the backward pass. This clip explains the recomputation strategy, which is the final piece of the puzzle.

Watch from 28:32 to 30:15. The key takeaway is that by recomputing attention blocks on-the-fly in SRAM during the backward pass, we avoid the HBM read/write that would have been necessary to save the matrix from the forward pass. This increases FLOPs but reduces HBM access, leading to a net speedup.

Conclusion

In this lesson, we dissected the computational and memory access patterns of the Transformer's attention mechanism. We saw how a seemingly straightforward algorithm can lead to severe performance bottlenecks when mapped naively to parallel hardware.

Key Takeaways:

  • Standard attention has a computational complexity of and, more critically, a memory complexity of due to the need to materialize a large intermediate attention matrix.
  • This memory requirement makes the operation memory-bandwidth bound, leading to low GPU utilization as compute units wait for data to be transferred from slow HBM.
  • IO-aware algorithms like FlashAttention resolve this by fusing the computational steps into a single kernel that uses tiling to keep working data in fast on-chip SRAM.
  • This is enabled by an online softmax formulation, which allows the correct result to be computed without access to the full attention score matrix at once.
  • The optimized pattern trades a small increase in computation (via recomputation in the backward pass) for a massive reduction in HBM traffic, resulting in significant speedups and enabling much longer sequence lengths.

Preview of the Next Lesson:

Understanding the performance of a single operation is the first step. To build an efficient system, we must also consider how to execute many computations in parallel. In the next lesson, we will describe how batching strategies affect GPU utilization and throughput in both training and inference, moving from optimizing a single kernel to optimizing the throughput of the entire system.

Can't find a good explanation? Sign up and we'll make it for you

Sign up