Skip to main content

FlashAttention: High-Speed, Memory-Efficient Attention for Transformers

Transformers have become the standard architecture in NLP and vision, but the quadratic complexity of attention in both computation and memory makes it a bottleneck for long sequences. FlashAttention, introduced in 2022, proposes a memory-aware exact attention algorithm that significantly boosts performance by optimizing GPU memory usage.

2. Bottlenecks in Standard Attention

The classic attention operation is defined as:

$Attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d}}) V$

Here, intermediate results like the $QK^T$ matrix are materialized and stored in GPU HBM, leading to extensive memory I/O and $O(n^2)$ memory consumption, which severely limits sequence length and throughput.

3. Core Ideas of FlashAttention 1

FlashAttention rethinks the attention operation with the following ideas:

  • Tile-based streaming computation: Avoids storing $QK^T$ by breaking computations into tiles and using GPU SRAM and registers.
  • Online softmax accumulation: Uses a streaming algorithm to incrementally compute the normalized softmax outputs.
  • Numerical stability: Uses max-subtraction trick to prevent overflow in exponentials.

3.1 Streaming Softmax Algorithm

for each query tile:
  initialize sum = 0, max = -inf
  for each key tile:
    score = Q · Kᵀ
    max = max(prev_max, max(score))
    score = exp(score - max)
    sum += score
    acc += score · V
output = acc / sum

This results in exact softmax attention with drastically reduced memory I/O.

4. Improvements in FlashAttention-2

In 2023, FlashAttention-2 further enhanced the algorithm. The key improvements include:

  • Improved work partitioning: Better parallelization along the query dimension using warps and threads.
  • Fewer register spills: Optimized for minimal register use per thread.
  • Better FP16/BF16 support: More stable performance on low-precision hardware.

4.1 Partitioning Strategies

FlashAttention-2 uses multiple parallelism schemes:

  1. Block-per-query: Each CUDA block handles one query.
  2. Warp-per-query: A warp computes a full attention score for a query.
  3. Thread-per-query: Allows finer-grained control and high throughput.

4.2 Triton Kernel Structure

The implementation uses the Triton language, enabling precise control over GPU memory and registers. It aggressively exploits shared memory and instruction-level parallelism.

5. Performance Comparison

MethodSpeedupMemory UsageAccuracy
Standard AttentionBaselineHighExact
FlashAttention 11.7x ~ 2.7xLowExact
FlashAttention 22.5x ~ 4.0xVery LowExact

6. Use Cases

FlashAttention is supported in HuggingFace Transformers and NVIDIA’s Megatron-LM. It is now widely adopted in training LLaMA, BERT, and GPT models, reducing training time while increasing memory headroom.

7. Conclusion

FlashAttention represents a breakthrough in GPU-aware algorithm design. By minimizing memory I/O while maintaining exact outputs, it allows training of larger models and faster inference. This makes it an essential tool for next-generation LLMs and high-throughput AI systems.

References

Comments

Popular

How to Fine-Tune LLaMA 3.2-1B-Instruct for Korean Instruction Tasks with LoRA and Hugging Face

LLaMA 3.2-1B-Instruct is a lightweight instruction-tuned language model released by Meta. It is designed to handle a wide range of instruction-based tasks with relatively low computational resources. Although the model was trained with multilingual capabilities, its performance on languages not included in its training set—such as Korean—is limited. This tutorial demonstrates how to fine-tune this open-source model on a Korean dataset using Hugging Face Transformers and PEFT (specifically LoRA), enabling it to better respond to Korean instructions. 1. Prerequisites Before running the example code below, ensure you have the following libraries installed: pip install torch transformers datasets peft accelerate mlflow huggingface_hub To use the LLaMA model or KoAlpaca datasets, you'll need a Hugging Face token. Additionally, you may need to handle potential CUDA Out-Of-Memory (OOM) errors. The following code takes care of both: from huggingface_hub import login login("y...

RF-DETR: Overcoming the Limitations of DETR in Object Detection

RF-DETR (Region-Focused DETR), proposed in April 2025, is an advanced object detection architecture designed to overcome fundamental drawbacks of the original DETR (DEtection TRansformer) . In this technical article, we explore RF-DETR's contributions, architecture, and how it compares with both DETR and the improved model D-FINE . We also provide experimental benchmarks and discuss its real-world applicability. RF-DETR Architecture diagram for object detection Limitations of DETR DETR revolutionized object detection by leveraging the Transformer architecture, enabling end-to-end learning without anchor boxes or NMS (Non-Maximum Suppression). However, DETR has notable limitations: Slow convergence, requiring heavy data augmentation and long training schedules Degraded performance on low-resolution objects and complex scenes Lack of locality due to global self-attention mechanisms Key Innovations in RF-DETR RF-DETR intr...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...