Inferensys

Glossary

FlashAttention

FlashAttention is an input-output exact attention algorithm that minimizes high-bandwidth memory reads and writes between GPU HBM and on-chip SRAM, significantly accelerating and reducing the memory footprint of self-attention.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
IO-AWARE EXACT ATTENTION

What is FlashAttention?

An algorithm that accelerates the self-attention mechanism by minimizing slow, high-bandwidth memory reads and writes between GPU HBM and on-chip SRAM, delivering exact results with a significantly smaller memory footprint.

FlashAttention is an input-output exact attention algorithm that fundamentally restructures the computation of self-attention to be IO-aware. Instead of materializing the large intermediate attention matrix in slow GPU High Bandwidth Memory (HBM), it employs tiling to load blocks of the query, key, and value matrices into fast on-chip SRAM, computing the softmax reduction incrementally on the fly. This algorithmic reordering drastically reduces the number of HBM reads and writes, turning a memory-bound operation into a compute-bound one.

By avoiding the storage of the quadratic N x N attention matrix, FlashAttention reduces the memory complexity from O(N^2) to O(N), enabling the training of Transformers on significantly longer sequences without approximations. The algorithm also leverages recomputation during the backward pass, discarding the softmax normalization statistics from the forward pass and recalculating them on demand, further conserving memory. This exact computation yields wall-clock speedups of 2-4x over standard PyTorch attention and has become a critical optimization for scaling Vision Transformers and large language models.

IO-AWARE EXACT ATTENTION

Key Features of FlashAttention

FlashAttention is an algorithm that computes exact self-attention while dramatically reducing the number of reads and writes between GPU high-bandwidth memory (HBM) and on-chip SRAM. By fusing operations into a single CUDA kernel and using tiling to avoid materializing the full attention matrix, it delivers significant speedups and memory savings for transformer models.

01

IO-Awareness and Memory Hierarchy

FlashAttention's core innovation is IO-awareness—it accounts for the speed gap between GPU HBM and SRAM. Standard attention materializes the large intermediate N×N attention matrix in slow HBM. FlashAttention instead tiles the computation, loading blocks of Q, K, and V into fast on-chip SRAM, computing softmax reductions incrementally, and writing only the final output back to HBM. This reduces HBM accesses from O(N²) to O(N²d²/M), where M is SRAM size.

02

Exact Attention with Tiling

Unlike approximate methods such as sparse or low-rank attention, FlashAttention computes mathematically exact self-attention. It achieves this through tiling: the input sequences are split into blocks that fit in SRAM. The algorithm uses a numerically stable online softmax that rescales previously computed block statistics as new blocks are processed. This ensures the final output is bitwise identical to a standard attention implementation, with no approximation error.

03

Recomputation Over Storage

During the backward pass, standard attention implementations store the large intermediate attention matrix to compute gradients. FlashAttention avoids this by recomputing the attention matrix on-the-fly during backpropagation using the stored softmax normalization statistics from the forward pass. This gradient checkpointing strategy trades a small amount of extra computation for a dramatic reduction in memory footprint, enabling longer sequence lengths during training.

04

Memory Complexity Reduction

Standard self-attention has O(N²) memory complexity due to the explicit attention matrix. FlashAttention reduces this to O(N) by never materializing the full matrix. This enables training transformers on much longer sequences—up to 8K or 16K tokens—without running out of GPU memory. The memory savings are most pronounced for large models and long contexts, where the attention matrix would otherwise dominate the memory footprint.

05

Fused CUDA Kernel Design

FlashAttention is implemented as a single, highly optimized fused CUDA kernel that performs all attention operations in one pass. By fusing the matrix multiply, softmax, dropout, and masking operations, it eliminates redundant data movement between separate kernel launches. This kernel-level fusion minimizes kernel launch overhead and maximizes arithmetic intensity, achieving up to 7.6x speedup over standard PyTorch attention on long sequences.

06

FlashAttention-2 and Parallelism

FlashAttention-2 improves upon the original by optimizing work partitioning across thread blocks and warps. It reduces non-matmul FLOPs, increases occupancy, and parallelizes over the sequence length dimension rather than batch and head dimensions. This yields approximately 2x speedup over FlashAttention-1. The algorithm also supports ALiBi positional biases and multi-query attention variants, making it compatible with modern architectures like LLaMA and GPT-4.

FLASHATTENTION EXPLAINED

Frequently Asked Questions

Clear, technically precise answers to the most common questions about the FlashAttention algorithm, its mechanisms, and its impact on transformer performance.

FlashAttention is an input-output exact attention algorithm that computes the standard self-attention operation with significantly fewer high-bandwidth memory (HBM) reads and writes. It works by tiling the attention computation into blocks that fit entirely within the GPU's fast on-chip SRAM. Instead of materializing the full N x N attention matrix in slow HBM, the algorithm loads blocks of the Query, Key, and Value matrices into SRAM, computes the attention scores for that block, and immediately applies the softmax reduction using an online stable softmax algorithm. The output is then written back to HBM in blocks. This kernel fusion avoids the quadratic memory footprint of standard attention implementations, reducing peak memory usage from O(N^2) to O(N) and dramatically accelerating both training and inference of transformer models.

ATTENTION MECHANISM COMPARISON

FlashAttention vs. Other Attention Optimizations

A technical comparison of FlashAttention against alternative self-attention optimization strategies for Vision Transformers, evaluating algorithmic approach, memory complexity, and suitability for medical imaging workloads.

FeatureFlashAttentionDeformable AttentionToken Merging (ToMe)

Algorithmic Approach

IO-aware exact attention with tiling and recomputation

Sparse attention at learned sampling offsets

Gradual token reduction via similarity-based merging

Memory Complexity

O(N) memory for sequence length N

O(NK) where K is number of sampling points

O(N) with progressively reduced token count

Exact Attention Output

Training Acceleration

Inference Acceleration

Requires Architectural Changes

High-Resolution Medical Image Support

Enables longer sequences on same hardware

Multi-scale feature maps supported natively

Reduces compute but may lose fine-grained detail

Integration with Pre-trained ViTs

Drop-in replacement for standard attention

Requires replacing attention module

Applied as post-hoc layer modification

HIGH-PERFORMANCE COMPUTING

Applications of FlashAttention

FlashAttention's IO-aware exact attention algorithm has become a foundational primitive for scaling Transformer models. By reducing the memory footprint from quadratic to linear in sequence length, it enables training and inference on long sequences that were previously computationally prohibitive.

01

Long Document Understanding

FlashAttention enables processing of full-length documents (10k-100k+ tokens) without truncation. This is critical for:

  • Legal contract analysis where clauses span hundreds of pages
  • Scientific literature review requiring cross-referencing entire papers
  • Medical record summarization where patient histories contain years of clinical notes

The memory reduction from O(N²) to O(N) in the attention computation means a 64k-token document requires only ~1GB of HBM instead of ~16GB.

64k+
Max Sequence Length
16×
Memory Reduction
02

High-Resolution Medical Imaging

Vision Transformers processing gigapixel whole slide images in digital pathology benefit directly from FlashAttention. Key applications:

  • 3D CT/MRI volume analysis where the token sequence is flattened from volumetric patches
  • Multi-modal diagnostic fusion combining radiology images with genomic sequences in a single attention context
  • Swin UNETR segmentation on high-resolution 3D medical scans

The algorithm's tiling strategy maps naturally to the spatial locality present in medical imagery, keeping KV-cache blocks in SRAM during forward passes.

10⁵
Tokens per WSI
5-8×
Training Speedup
03

Large-Scale Video Understanding

Video Transformers operating on spatiotemporal patches generate extremely long token sequences. FlashAttention makes feasible:

  • Surgical workflow analysis from hours-long operating room footage
  • Autonomous vehicle perception processing multi-camera streams with temporal context
  • Embodied intelligence training where agents learn from extended egocentric video

Without IO-aware attention, the memory cost of processing even 30 seconds of video at standard frame rates would exceed GPU capacity.

10⁴-10⁵
Tokens per Video Clip
Linear
Memory Scaling
04

Protein Structure and Genomics

Attention over long biological sequences is essential for:

  • Protein folding models like AlphaFold where attention spans thousands of amino acid residues
  • Genomic sequence analysis requiring context windows across millions of base pairs
  • Molecular dynamics simulation where attention captures long-range atomic interactions

FlashAttention's exact computation (not an approximation) is critical here—biological structure prediction cannot tolerate the errors introduced by sparse or low-rank attention approximations.

10⁶
Base Pair Context
Exact
Attention Fidelity
05

Multi-Turn Agentic Reasoning

Autonomous agents maintaining extended conversation histories and tool-calling contexts depend on FlashAttention for:

  • Long-horizon planning where the agent must attend to all previous actions and observations
  • Retrieval-augmented generation with large retrieved document sets concatenated into the prompt
  • Multi-agent debate protocols where transcripts from multiple agents are pooled into a shared context

The KV-cache compression from FlashAttention-2 and FlashAttention-3 directly reduces the latency of autoregressive decoding, enabling real-time agentic loops.

2-4×
Decoding Throughput
100k+
Context Window
06

On-Device and Edge Deployment

FlashAttention's memory efficiency is transformative for resource-constrained hardware:

  • Small language models running on mobile devices with limited SRAM budgets
  • TinyML diagnostic tools deployed on point-of-care ultrasound devices
  • Edge AI architectures where HBM is scarce but SRAM is available for tiled computation

The algorithm's IO-aware design philosophy—minimizing HBM reads/writes—aligns perfectly with the memory hierarchy constraints of edge accelerators and NPUs.

10-20×
Memory Savings
SRAM
Primary Compute
Prasad Kumkar

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.