Picture this: you've just secured a cluster of 64 H100 GPUs. You're ready to fine-tune a 70-billion parameter model on sequences long enough to swallow entire codebases. You launch training, watch the loss curve start its satisfying downward glide… and then you notice something ugly in your GPU telemetry. Your tensor cores—the silicon you're paying roughly $30,000 per card for—are sitting at under 30% utilization. Meanwhile, your HBM bandwidth counters are pegged at 100%, screaming like a jet engine at takeoff.
You didn't buy a memory bus. You bought a compute monster. But the attention mechanism inside your transformer just turned your $2 million cluster into the world's most expensive memory-copying machine.
This is the story of FlashAttention—not a new model, not a new architecture, but one of the most consequential systems papers of the modern AI era. It's a tale about the unglamorous truth of deep learning at scale: the bottleneck was never FLOPs. It was data movement. And the fix required rethinking attention from the memory hierarchy up, with a little help from a numerical trick that sounds like it shouldn't work but absolutely does.
Let's dig in.
The Setup: Why Attention Is a Memory Crime Scene
Start with the math everyone knows. Scaled dot-product attention, for a sequence of length ( N ) with head dimension ( d ):
[ \text{Attention}(Q, K, V) = \text{softmax}!\left(\frac{QK^\top}{\sqrt{d}}\right)V ]
Clean, elegant, three matrix multiplications. Here's the part that gets glossed over in every tutorial: the intermediate matrix ( S = QK^\top ) is ( N \times N ).
Forget the FLOPs for a second. Think about the memory.
- ( Q, K, V ) each live in HBM (high-bandwidth memory) and are ( N \times d ). At ( N = 8192 ) and ( d = 128 ) in fp16, that's 2 MB each—fine.
- But ( S ) is ( 8192 \times 8192 ) fp16 = 128 MB per attention head, per layer.
- Then softmax reads all 128 MB back, writes another 128 MB.
- Then the ( \times V ) matmul reads it again.
- Then you need ( S ) for the backward pass in training, so you either checkpoint it (recompute) or materialize even more.
A standard GPT-style model has dozens of layers and multiple heads. The naive implementation of attention, as written in the original Transformer paper and every textbook implementation since, materializes ( S ) and the softmax output ( P ) to HBM over and over. At long sequence lengths, the memory traffic dwarfs the actual arithmetic.
And here's the kicker: on modern GPUs, HBM bandwidth is the scarce resource, not compute.
The Arithmetic Intensity Problem
Every GPU has a "roofline." On an A100:
- FP16 tensor core throughput: ~312 TFLOPS
- HBM bandwidth: ~2 TB/s (1.5–2.0 depending on SKU)
- On-chip SRAM (shared memory): ~19 MB total, ~108 KB per SM
The ratio of FLOPs to bytes—arithmetic intensity—tells you whether you're compute-bound or memory-bound. For naive attention at long ( N ), the elementwise operations over the ( N \times N ) matrix (softmax, scaling, masking, dropout) have terrible arithmetic intensity. You touch each element of ( S ) multiple times, moving it to and from HBM, doing only a handful of FLOPs per byte.
The result: the attention kernel is memory-bandwidth-bound, and your tensor cores sit idle waiting for data. This is the "memory wall," and attention slams into it face-first at exactly the sequence lengths where models get interesting.
The Core Insight: Don't Materialize the Matrix
FlashAttention's central thesis, stated plainly: the ( N \times N ) attention matrix never needs to exist in HBM at all.
The trick is to compute attention in tiles that fit in on-chip SRAM, and to fuse all the operations (the matmul, the scaling, the masking, the softmax, the second matmul) into a single kernel so data flows through the chip once—not three times.
If you've written CUDA, you know why this is hard. The softmax is the villain. Softmax is a global reduction: to compute the denominator, you need the maximum over the entire row (for numerical stability) and the sum of exponentials over the entire row. But if you're processing ( S ) in tiles, you don't have the whole row yet. You'd normally need two passes: one to find the row max and sum, one to normalize.
Two passes over HBM = back to square one. So how do you softmax a matrix you're only allowed to see one tile at a time?
Enter the Hero: Online Softmax (and Its Unsung Authors)
Here's where the story gets interesting, because FlashAttention didn't invent its most important ingredient. It weaponized an existing numerical technique and married it to aggressive hardware-aware kernel engineering.
The technique is online softmax (also called streaming softmax or incremental softmax), formalized in a 2018 paper by Milakov and Gimelshein at NVIDIA, with earlier roots in streaming normalization work. The idea:
You can compute the softmax incrementally, one tile at a time, by maintaining running statistics and rescaling your accumulated output whenever a new maximum appears.
Concretely: as you stream through tiles of a row, you keep a running max ( m ) and running sum ( \ell ). When a new tile contains a larger max ( m' ), you don't restart—you rescale your running sum and your running output accumulator by ( e^{m - m'} ), then fold in the new tile.
Let's make that concrete. For a block of scores, with running state:
# Streaming (online) softmax over tiles of a single attention row
m_running = -inf # running row max
l_running = 0.0 # running sum of exp(s - m_running)
acc = 0.0 # running (unnormalized) output accumulator
for tile in tiles_of_row:
m_tile = max(tile) # local max of this tile
m_new = max(m_running, m_tile) # updated global max
# rescale previous accumulator to the new max
correction = exp(m_running - m_new)
l_running = l_running * correction + sum(exp(tile - m_new))
acc = acc * correction + exp(tile - m_new) @ V_tile
m_running = m_new
output = acc / l_running # final normalization
That correction factor is the whole ballgame. It lets you merge partial softmax results without ever seeing the full row, and—crucially—without precision loss, because every exponent is taken relative to a max you're actively tracking. No overflow. No underflow. No hidden numerical landmines.
The FlashAttention authors (Tri Dao and colleagues, 2022) realized: if you can compute softmax incrementally, then you can fuse the entire attention operation into a single pass over the data, keeping the ( N \times N ) score tile in registers/shared memory, applying the online softmax update, multiplying by the corresponding ( V ) tile, and never writing the score matrix to HBM. Not once. Not even for the backward pass (more on the recomputation trick below).
The Kernel: A Guided Tour of What's Actually Happening on the Chip
Let's walk through the forward pass the way the GPU sees it. This is the part where systems people get misty-eyed, because it's a genuinely beautiful piece of scheduling.
The Tiling Strategy
The kernel launches a grid of thread blocks. Each block owns a row-block of ( Q ) (say, 128 rows) and iterates over column-blocks of ( K ) and ( V ). Everything that needs to be reused lives in SRAM:
- ( Q ) tile: loaded once into registers/shared memory, reused across all ( K/V ) blocks.
- ( K ) tile and ( V ) tile: loaded per iteration into shared memory.
- Accumulators: ( O ) (the output, size ( B_r \times d )) and the softmax statistics ( m, \ell ) (size ( B_r )) live in registers.
The block loops over ( K/V ) tiles. For each:
- Compute ( S_{ij} = Q_i K_j^\top ) using tensor cores — tile stays on-chip.
- Apply scaling, masking, and (optionally) dropout in registers.
- Update running max ( m ), rescale the accumulator ( O ) by the correction factor, update running sum ( \ell ).
- Compute ( P_{ij} = \exp(S_{ij} - m) ) and immediately multiply by ( V_j ), accumulating into ( O ).
Notice what's missing: HBM traffic. The ( S ) tile is born in SRAM, lives in registers, and dies there. The only HBM reads are the input ( Q, K, V ) (each read a small, tiled number of times) and the final output ( O ) (written once). The intermediate ( N \times N ) monster never touches global memory.
The memory savings are staggering. Naive attention's HBM footprint scales as ( O(N^2) ). FlashAttention's scales as ( O(N) ) — you only ever hold ( Q ), ( K ), ( V ), and ( O ), each linear in sequence length. The ( N^2 ) work still happens (you can't avoid the quadratic FLOPs of attention), but it happens on-chip, at SRAM speeds, without polluting your HBM bandwidth.
The Backward Pass: Recompute, Don't Store
Training needs gradients. Naive attention stores the ( N \times N ) probability matrix ( P ) (and often ( S )) from the forward pass to reuse in the backward pass—another ( O(N^2) ) memory explosion, this time persistent.
FlashAttention takes a page from gradient checkpointing: it doesn't store ( P ) or ( S ) at all. In the backward pass, it recomputes the attention tiles on the fly from ( Q, K, V ) and the tiny per-row statistics ( m ) and ( \ell ) (which are all it saved—( O(N) ) memory). The recomputation costs extra FLOPs, but the kernel is memory-bound anyway, so those extra FLOPs are free—they're absorbed into the idle tensor-core cycles that were previously wasted waiting on HBM. In many regimes FlashAttention is wall-clock faster in the backward pass despite doing more arithmetic, because it slashed the memory traffic.
That's the counterintuitive magic: doing more math makes it faster, because the math was never the bottleneck.
The IO Complexity Result
The paper's formal contribution is an IO-complexity analysis. It proves FlashAttention's HBM reads/writes scale as:
[ O!\left(\frac{N^2 d^2}{M}\right) ]
where ( M ) is SRAM size—versus ( \Theta(N^2 + Nd) ) or worse for standard attention. The full attention matrix is never round-tripped through HBM. At realistic SRAM sizes, that's a multi-fold reduction in memory traffic, which is exactly what the roofline model says you need to escape the bandwidth wall.
The Numbers: From Curiosity to Default
When the paper dropped in 2022, the benchmarks read like marketing copy—except they were reproducible:
- Up to 3× faster wall-clock attention than the best existing (already-fused) implementations, like Megatron's and PyTorch's.
- 5–20× reduction in memory footprint for the attention step, enabling sequence lengths that previously OOM'd.
- Enabling 2–4× longer context on the same hardware—the difference between a model that can read a function and one that can read a repo.
- Crucially: exact results. Not an approximation. Same outputs up to floating-point rounding, because online softmax is numerically equivalent to standard softmax.
And it didn't stay an academic artifact. FlashAttention became part of the standard stack: integrated into PyTorch (scaled_dot_product_attention), Hugging Face, vLLM, TensorRT-LLM, and essentially every serious training and inference framework. FlashAttention-2 (2023) refined the work partitioning and parallelism across the sequence dimension, pushing utilization higher; FlashAttention-3 (2024) targeted Hopper's async capabilities (TMA, warp specialization, FP8) and pushed toward the hardware's realistic roofline. This wasn't a paper that sat on a shelf—it became the attention kernel.
Here's the context for why the hype was justified: 2022–2023 was the moment the industry discovered that context length was the new scaling axis. Everyone wanted models that could ingest entire books, codebases, and conversation histories. Every one of those ambitions ran straight into the quadratic memory wall of attention. FlashAttention wasn't a marginal optimization—it was the thing that made long context economically possible. That's why it became lore.
Why This Is a Systems Story, Not Just a Math Story
The deepest lesson of FlashAttention has almost nothing to do with attention specifically. It's a systems manifesto:
- Know your memory hierarchy. Registers > shared memory > L2 > HBM, each roughly an order of magnitude apart in latency and bandwidth. The kernel was co-designed with this hierarchy, not against it.
- Fuse aggressively. Every kernel boundary is an HBM round-trip waiting to happen. Fusing matmul + softmax + matmul into one kernel eliminated the round-trips entirely.
- Recompute beats store when you're bandwidth-bound and compute-rich. The backward pass trades cheap FLOPs for expensive bytes—and wins.
- The roofline is a design tool, not an observation. FlashAttention started from "what does the roofline say is optimal?" and built a kernel to hit it.
If you squint, this is the same philosophy that powers high-performance databases (columnar layouts, vectorized execution, cache-conscious joins) and CDNs (edge caching to avoid origin round-trips). AI infrastructure just arrived late to the party. FlashAttention is, at heart, a cache-oblivious-style algorithm for the GPU memory hierarchy—except it's cache-aware, hand-tuned to the exact SRAM sizes and warp schedules of real silicon.
A Peek at the Modern Kernel
The Hopper-era kernels (FA-3) are gnarly in the best way. They exploit:
- TMA (Tensor Memory Accelerator): asynchronous bulk copies from HBM to shared memory that free the SMs to compute while data is in flight.
- Warp specialization: dedicating warps to producer (memory) vs. consumer (compute) roles, overlapping the two.
- FP8 with careful scaling, doubling tensor-core throughput while preserving accuracy via the same online-softmax rescaling discipline.
- 2-stage pipelining across the ( K/V ) loop so the next tile is loading while the current one computes.
The pseudo-structure of the inner loop looks roughly like:
for each K/V tile j:
async_load(K_j, V_j) # TMA, overlaps with compute
S_ij = Q_i @ K_j^T # tensor cores, on-chip
m_new = max(m_running, rowmax(S_ij))
P_ij = exp(S_ij - m_new) # on-chip, in registers
corr = exp(m_running - m_new)
l_running = l_running * corr + rowsum(P_ij)
O_i = O_i * corr + P_ij @ V_j # tensor cores, accumulate on-chip
m_running = m_new
O_i = O_i / l_running # final normalize, write once to HBM
Elegant. Every line is deliberate about where the data lives. The ( N \times N ) never sees daylight.
The Honest Caveats (Because Premium Engineering Means Candor)
No kernel is a silver bullet, and a seasoned infra reader deserves the fine print:
- Quadratic compute remains. FlashAttention kills the memory quadratic, not the FLOPs quadratic. Attention is still ( O(N^2) ) arithmetic. For genuinely extreme contexts, you need algorithmic cousins (linear attention, state-space models, sparse attention, sliding windows) on top of good kernels. FlashAttention makes attention affordable; it doesn't change its asymptotic compute.
- It's hardware-specific. The optimal tile sizes, pipeline depths, and instruction mix depend heavily on the GPU generation. An FA kernel tuned for A100 is not magically optimal on H100 or on non-NVIDIA accelerators. Portability across hardware is an ongoing effort (AMD's ROCm, for instance, has its own variants).
- Head-dimension and dtype sensitivity. Performance and numerics vary with head dimension, block sizes, and low-precision formats. FP8 is spectacular but demands care with scaling.
- It's a kernel, not a model fix. It won't rescue a poorly designed architecture—but it will make a well-designed one dramatically cheaper to run.
Being clear-eyed about these is what separates a real engineering account from a hype piece. FlashAttention is transformative within its lane.
The Takeaway
The next time someone tells you AI progress is "just more GPUs and more data," point them at FlashAttention. The model architecture didn't change. The math didn't change. The hardware didn't change. What changed was how bytes move through silicon—and that alone unlocked a step-function in what's practical to train and serve.
The saga's real lesson is a systems one: the gap between the FLOPs you can theoretically issue and the FLOPs you can actually feed is where modern performance lives. FlashAttention closed that gap for the single most expensive operation in the most important workload of our decade, and in doing so, it quietly rewrote the default kernel for a generation of models.
So when your H100 cluster finally shows tensor-core utilization in the 70s and your HBM counters stop howling—remember the online-softmax rescaling trick, the tile that never left SRAM, and the recomputed backward pass. That's not just clever numerics. That's engineering the memory wall into submission, one fused kernel at a time.
