FlashAttention is an IO-aware, exact attention algorithm that recomputes parts of the attention operation on-the-fly to avoid reading and writing the large intermediate attention matrix to high-bandwidth memory (HBM). This technique, known as tiling and recomputation, dramatically reduces memory bandwidth usage and footprint, speeding up both training and inference while enabling longer context windows within fixed GPU memory constraints.
Glossary
FlashAttention

What is FlashAttention?
FlashAttention is a foundational algorithm that redefined the efficiency of transformer models by optimizing memory access patterns during the attention computation.
By fusing the attention computation into a single, optimized GPU kernel, FlashAttention minimizes expensive HBM accesses, directly addressing the memory-bound regime of transformer inference. Its design principles underpin modern KV cache management in systems like vLLM and are essential for techniques such as PagedAttention, enabling efficient continuous batching and high-throughput serving of large language models.
Key Features and Benefits
FlashAttention is an IO-aware, exact attention algorithm that recomputes parts of the attention operation on-the-fly to avoid reading and writing the large intermediate attention matrix to high-bandwidth memory (HBM). This section details its core architectural innovations and resulting performance gains.
IO-Aware Algorithm Design
FlashAttention is explicitly designed around the memory hierarchy of modern GPUs. It treats high-bandwidth memory (HBM) as a slow, large storage and SRAM as a fast, small cache. The algorithm tiles the large attention matrix into blocks, performing the entire softmax operation for a block within SRAM. This minimizes the number of expensive reads/writes to HBM, making the computation memory-bandwidth optimal. The core insight is that recomputation (a compute cost) is cheaper than frequent HBM I/O (a memory cost) for attention operations.
Dramatic Memory Footprint Reduction
Standard attention algorithms must materialize the intermediate S = QK^T matrix, which scales quadratically (O(N²)) with sequence length (N). For a 64K sequence, this matrix requires ~16GB of memory in FP16. FlashAttention never stores this full matrix to HBM. By fusing the attention scoring, softmax, and weighted sum operations, it only writes the final output. This reduces memory usage from quadratic to linear in sequence length, enabling the training and inference of models with extremely long contexts (e.g., 64K, 128K tokens) on the same hardware.
Significant Speedup for Training & Inference
By minimizing HBM I/O, FlashAttention provides substantial wall-clock speed improvements. Benchmarks show:
- Up to 3x faster training for GPT-style models.
- Up to 10-20x faster inference for long-sequence generation. The speedup is most pronounced for long context lengths where standard attention becomes severely memory-bound. This directly translates to lower cloud compute costs and faster iteration cycles for research and production deployment. The algorithm is exact, so these speedups come with no loss in model accuracy.
Enabler for Longer Context Models
FlashAttention's memory efficiency directly enabled a new generation of long-context LLMs. Before its development, training models on sequences longer than 2K tokens was prohibitively expensive. By eliminating the quadratic memory bottleneck, FlashAttention made it feasible to train models on 8K, 32K, and even 128K token sequences. This capability is critical for applications requiring deep document analysis, long-form content generation, and extended multi-turn conversations, forming the technical backbone for models like GPT-4 and Claude.
Foundation for Advanced Variants
The core tiling and recomputation principles of FlashAttention have been extended to create more specialized, high-performance variants:
- FlashAttention-2: A more optimized implementation with better work partitioning, achieving near-peak GPU utilization.
- FlashAttention-3: Leverages new hardware features like NVIDIA's FP8 Tensor Cores and asynchronous copy instructions for H100 GPUs.
- FlashDecoding: Optimizes the decode-phase attention for batch size 1, crucial for low-latency inference.
- FlashDecoding++: Further enhances decode-phase performance for very long sequences. These variants ensure the algorithm family continues to push hardware limits.
Integration with KV Cache Management
While FlashAttention optimizes the prefill phase, its principles are complementary to KV cache optimizations for the decode phase. Efficient attention computation reduces the initial cost of populating the KV cache. Furthermore, techniques like PagedAttention (used in vLLM) manage the storage of the KV cache in GPU memory, while FlashAttention optimizes the computation that creates and uses that cache. Together, they form a complete optimization stack for transformer inference, addressing both computational and memory bottlenecks across the entire generation lifecycle.
FlashAttention vs. Standard Attention
A technical comparison of the core algorithmic and performance characteristics between the standard attention mechanism and the IO-aware FlashAttention optimization.
| Feature / Metric | Standard Attention | FlashAttention |
|---|---|---|
Core Algorithm | Explicit materialization of the full NxN attention matrix (where N is sequence length) in High-Bandwidth Memory (HBM). | IO-aware exact attention that recomputes attention scores on-the-fly in SRAM, avoiding writing the large intermediate matrix to HBM. |
Memory Complexity | O(N²) for the attention matrix, leading to quadratic memory consumption with sequence length. | O(N) for storing the final output, achieving linear memory consumption with sequence length. |
Primary Performance Bottleneck | Memory-Bound: Dominated by slow HBM reads/writes for the large attention matrix. | Compute-Bound: Dominated by fast SRAM computation, minimizing HBM I/O. |
Kernel Fusion | Typically requires multiple kernel launches (softmax, matrix multiply) with intermediate HBM writes. | Fuses the entire attention operation (matmul, softmax, mask, dropout) into a single, optimized GPU kernel. |
Support for Attention Variants | Trivially supports causal masking, sliding windows, and ALiBi through explicit matrix operations. | Natively supports causal masking; support for other variants (e.g., sliding window) requires algorithm adaptation (e.g., FlashAttention-2). |
Numerical Precision | Standard 32-bit (FP32) or 16-bit (FP16/BF16) floating-point operations. | Uses tiling with online softmax rescaling, which can introduce slight numerical differences but is mathematically equivalent. |
Typical Speedup (Training, Long Context) | Baseline (1x). | Up to 3-5x faster for sequences of 2K tokens or longer, due to reduced HBM I/O. |
Typical Memory Reduction (Training) | Baseline (1x). | Up to 10-20x less memory usage, enabling larger batch sizes or longer contexts. |
Backward Pass Optimization | Requires storing the large attention matrix for gradient calculation, incurring significant memory overhead. | Recomputes the attention matrix in the backward pass (gradient checkpointing), trading extra FLOPs for massive memory savings. |
Primary Use Case Target | Conceptual clarity and flexibility for research prototyping. | Production-scale training and inference of large models with long sequence lengths. |
Integration Complexity | Straightforward to implement from equations; common in early transformer code. | Requires low-level CUDA/kernel programming expertise for implementation; typically used via libraries (e.g., FlashAttention library, xFormers). |
Frameworks and Implementations
FlashAttention is an IO-aware, exact attention algorithm that recomputes parts of the attention operation on-the-fly to avoid reading and writing the large intermediate attention matrix to high-bandwidth memory, dramatically speeding up both training and inference while reducing memory usage.
Core Algorithm: Tiling & Recomputation
FlashAttention's primary innovation is its IO-aware design. It splits the large Softmax(QK^T)V operation into smaller blocks or tiles that fit in fast SRAM. Instead of writing the massive attention matrix (size N x N) to slow HBM, it recomputes parts of the attention scores on-the-fly during the backward pass. This kernel fusion avoids the expensive HBM reads/writes that are the true bottleneck, trading extra FLOPs for vastly reduced memory I/O.
- Tiling: Loads queries, keys, and values in blocks from HBM to SRAM.
- Recomputation: Recalculates attention scores in SRAM during backpropagation.
- Result: Achieves exact attention with 2-4x faster training and 10-20x faster inference on long sequences.
Memory Hierarchy Optimization
The algorithm is explicitly designed for modern GPU memory architecture. It treats SRAM (on-chip, ~20TB/s bandwidth) as a fast cache and HBM (off-chip, ~1TB/s bandwidth) as slow main memory. By keeping the working set of tiles in SRAM, it minimizes the number of costly HBM accesses.
- Bandwidth Reduction: Reduces HBM reads/writes from O(N²) to O(N²d²/M), where M is SRAM size.
- Memory Footprint: Requires only O(N) memory instead of O(N²) to store the attention matrix.
- Practical Impact: Enables training transformers with 16k+ context length on a single GPU, where standard attention would run out of memory.
FlashAttention-2 & Hardware Extensions
FlashAttention-2 refines the original algorithm with better parallelism and work partitioning, achieving near-perfect utilization of NVIDIA GPU tensor cores. It rearranges the loop order to parallelize over sequence length and better saturate warps.
- Improved Parallelism: Reduces non-matrix-multiply operations, better aligning with GPU warp schedulers.
- Kernel Variants: Includes FlashDecoding for optimized inference (uneven keys/queries) and support for multi-query and grouped-query attention.
- Hardware Support: Optimized kernels exist for Hopper (FP8), Ampere, and AMD MI300 architectures.
Key Use Cases & Impact
FlashAttention directly enables new research and production capabilities by removing memory constraints.
- Long Context Models: Made training GPT-3 (8k context), Claude (100k context), and other long-context LLMs feasible.
- Higher Batch Sizes: Increases training throughput by allowing larger batches within the same GPU memory.
- Inference Speedup: Critical for reducing latency in autoregressive decoding, where attention over the KV cache is memory-bandwidth bound.
- Multimodal Models: Enables efficient attention over long sequences of image patches in vision transformers.
Related Optimizations & Ecosystem
FlashAttention is part of a broader ecosystem of attention and memory optimizations.
- PagedAttention (vLLM): Manages the KV cache in non-contiguous blocks for efficient memory sharing in inference serving.
- xFormers: A library of optimized transformer building blocks, including memory-efficient attention.
- Causal Masking: FlashAttention includes highly optimized kernels for the causal masks used in language modeling.
- Alibi & Rotary Embeddings: Supports common positional encoding schemes like RoPE without performance degradation.
- Distributed Training: Supports tensor parallelism and sequence parallelism for scaling to extremely long sequences across multiple GPUs.
Frequently Asked Questions
FlashAttention is a foundational algorithm for transformer inference and training, fundamentally altering how attention is computed to be IO-aware. These FAQs address its core mechanisms, trade-offs, and practical impact on modern AI systems.
FlashAttention is an IO-aware, exact attention algorithm that recomputes parts of the attention operation on-the-fly to avoid reading and writing the large intermediate attention matrix to high-bandwidth memory (HBM).
It works by leveraging the memory hierarchy of modern accelerators (like GPUs). Standard attention computes the full Softmax matrix, which is size O(N²) for sequence length N, and writes it to slow HBM, creating a massive memory bottleneck. FlashAttention uses tiling to load small blocks of the query (Q), key (K), and value (V) matrices from HBM into fast SRAM (on-chip memory). It performs the attention computation (matrix multiply, masking, softmax) on these blocks in SRAM, then writes only the final output back to HBM. Since the large intermediate matrices never leave SRAM, it achieves dramatic reductions in memory reads/writes (I/O), which is the primary constraint for attention on modern hardware. This technique is known as recomputation or online softmax.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
FlashAttention is a foundational algorithm that redefined attention computation. Its principles and optimizations are closely linked to these other key techniques for managing transformer memory and performance.
Multi-Query & Grouped-Query Attention
Attention variants designed to shrink the KV cache footprint.
- Multi-Query Attention (MQA): All query heads share a single key and value head, drastically reducing cache size.
- Grouped-Query Attention (GQA): A hybrid where groups of query heads share a key/value head, offering a tunable trade-off between MQA's efficiency and standard multi-head attention's model quality. Both reduce the memory I/O bottleneck that FlashAttention optimizes for.
KV Cache Quantization
A technique to store key and value tensors in lower precision formats (e.g., INT8, FP8) to reduce memory bandwidth and capacity requirements. This directly complements FlashAttention's I/O-aware design by making the data being read/written smaller. It's a primary method for enabling longer context windows within fixed GPU memory.
Continuous Batching
An inference scheduling paradigm that dynamically groups incoming requests into a single, continuously executing batch. New requests join and finished sequences exit independently. This maximizes GPU utilization and throughput. Efficient KV cache management (via PagedAttention) is essential for making continuous batching work with variable-length sequences.
Memory-Bound Regime
A computational state where system performance is limited by the speed of memory accesses (e.g., reading the KV cache) rather than by raw arithmetic speed (compute-bound). FlashAttention was explicitly designed for this regime, optimizing the expensive reads/writes of the attention matrix to and from high-bandwidth memory (HBM).
Operator/Kernel Fusion
A low-level optimization that combines multiple computational operations (like softmax, masking, and matrix multiplies in attention) into a single, custom GPU kernel. This minimizes costly reads/writes to slow memory. FlashAttention is a canonical example of extreme kernel fusion, implementing the entire attention operation in one fused, IO-aware kernel.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us