Skip to main content
This guide demonstrates how to implement Flash Attention v2 using CUTLASS CuTe DSL. Flash Attention is a memory-efficient attention mechanism that reduces memory usage from O(N²) to O(N) through online softmax computation.

Overview

Flash Attention v2 computes scaled dot-product attention:
Where:
  • Q: Query matrix (B×Sq×N×H)
  • K: Key matrix (B×Sk×N×H)
  • V: Value matrix (B×Sk×N×H)
  • O: Output matrix (B×Sq×N×H)
  • B: batch size, Sq/Sk: sequence length, N: number of heads, H: head dimension

Key Features

  • Online softmax: Computes softmax incrementally without materializing full attention matrix
  • Tiled computation: Processes attention in blocks to fit in shared memory
  • Register pipeline: Overlaps shared memory loads with computation
  • Causal masking: Optional support for autoregressive models

Architecture

Implementation

Running Examples

Performance Profiling

Key Concepts

The online softmax algorithm processes attention in blocks without materializing the full matrix:Traditional approach (memory intensive):
Flash Attention approach (memory efficient):
This reduces memory from O(N²) to O(N).
The register pipeline overlaps shared memory loads with computation:
Choosing optimal tile sizes:m_block_size (Query tile):
  • Larger: Better arithmetic intensity, more registers
  • Smaller: Lower SMEM usage, better for long sequences
  • Typical: 64, 128
n_block_size (Key/Value tile):
  • Affects online softmax accuracy
  • Should match m_block_size for balanced computation
  • Typical: 64, 128
head_dim:
  • Usually fixed by model (64, 128, 256)
  • Must be 16-byte aligned
  • Pad if necessary
Constraint: (m_block_size * head_dim + 2 * n_block_size * head_dim) * sizeof(dtype) must fit in SMEM

Memory Analysis

Constraints

  • Only fp16 and bf16 data types supported
  • Head dimension must be 16-byte aligned (multiple of 8 elements)
  • m_block_size * 2 must be divisible by num_threads
  • Total SMEM: (m_block + 2*n_block) * head_dim * sizeof(dtype) < capacity
  • Log-sum-exp for training backward pass not computed

Source Code

Flash Attention v2 (Ampere)

Complete source: examples/python/CuTeDSL/ampere/flash_attention_v2.py

Flash Attention (Hopper)

Hopper variant: examples/python/CuTeDSL/hopper/fmha.py