Tuesday, November 24, 2026
HomeData ScienceEfficient Transformers – FlashAttention, Linear Attention, Sparse Attention and Ring Attention

Efficient Transformers – FlashAttention, Linear Attention, Sparse Attention and Ring Attention

Table of Content

📋 KEY INSIGHTS

  • Standard multi-head self-attention has O(n^2) time and memory complexity in the sequence length n: computing the n×n attention matrix requires n^2 dot products, and storing it requires n^2 memory. For n=512 (BERT), this is manageable; for n=4096 (GPT-4), it requires 64× more memory and compute than n=512; for n=100,000 (long-document processing), it is simply infeasible on current hardware. Efficient Transformer research attacks this quadratic scaling from two directions: exact algorithms that compute standard attention more efficiently (FlashAttention), and approximate algorithms that replace quadratic attention with sub-quadratic methods that trade a small quality loss for dramatic efficiency gains (linear attention, sparse attention, random feature approximations).
  • FlashAttention (Dao et al., 2022) achieves 2-4× speedup over standard attention without any approximation by exploiting GPU memory hierarchy: instead of materialising the full n×n attention matrix in slow HBM (High Bandwidth Memory), FlashAttention tiles the computation into blocks that fit in fast SRAM (on-chip cache), computing attention output for each block without writing the attention matrix to HBM. The key insight: the attention matrix A = softmax(QK^T/√d) is not needed as an intermediate output — only the final output O = AV is needed. By fusing the QK^T, softmax, and AV operations into a single CUDA kernel that operates block-by-block in SRAM, FlashAttention avoids the memory bandwidth bottleneck of writing and reading the n×n attention matrix, achieving IO complexity of O(n^2/M) SRAM reads/writes (where M is SRAM size) vs. O(n^2) for standard attention. FlashAttention-2 and FlashAttention-3 further optimise work partitioning and tensor core utilisation. The connection to our long-context LLMs guide is direct: FlashAttention is the foundational hardware optimisation that makes long-context LLMs (with context windows of 128k-1M tokens) feasible — without FlashAttention’s IO-efficient exact attention, the memory bandwidth requirements of standard attention would make 128k-token contexts impractical even on 8×H100 nodes.
  • Linear attention replaces the softmax attention kernel K(q,k) = exp(qk^T/√d) with a kernel that decomposes as K(q,k) = φ(q)^T φ(k) for some feature map φ. This decomposition enables computing the attention output as O_i = (Σ_j φ(k_j)v_j^T) φ(q_i) in O(nd^2) instead of O(n^2d) — a dramatic speedup for long sequences. The challenge: no efficient feature map exactly reproduces softmax, and approximations introduce errors. Random Fourier Features (RFF, the foundation of Performer, Choromanski et al., 2021) use random Fourier features to approximate the FAVOR+ (Fast Attention Via positive Orthogonal Random features) decomposition, achieving unbiased approximation of softmax attention with O(nd) complexity. RetNet (Sun et al., 2023) uses a decaying exponential recurrence instead of softmax attention, achieving O(n) training complexity and O(1) per-step inference complexity (like an RNN) while outperforming Transformer on language modelling at equal parameter count. The connection to our SSM/Mamba guide is direct: Mamba’s selective state space model and RetNet’s recurrent linear attention share the fundamental insight that RNN-like recurrent computation enables O(n) sequence processing — both can be viewed as special cases of linear attention with specific choices of feature map and gating mechanism, connecting the SSM and efficient Transformer research agendas.
  • Sparse attention restricts each token to attending to a subset of other tokens, reducing the n^2 attention matrix to a sparse matrix with O(n√n) or O(n log n) non-zero entries. BigBird (Zaheer et al., 2020) combines three attention patterns: local attention (each token attends to its w neighbours), random attention (each token attends to g randomly selected tokens), and global attention (a set of special “global” tokens attend to all tokens). The combination provably achieves the same expressive power as full attention (BigBird is Turing complete under certain conditions), while reducing complexity to O(n). Sliding window attention (Longformer, Beltagy et al., 2020) uses a fixed local window of size w per token, plus global attention for task-specific tokens (CLS, question tokens in QA), achieving O(n·w) complexity. The connection to our long-context LLMs guide is direct: sliding window attention and RoPE position encodings (described in that guide) are the two complementary techniques used in modern long-context LLMs — RoPE enables length generalisation beyond the training context window, while sliding window attention makes per-step attention computation tractable.
  • Ring Attention (Liu et al., 2023) enables training Transformers on sequences that do not fit on a single GPU by distributing the attention computation across multiple devices: each device holds a chunk of the key-value sequence, and devices form a ring, passing their KV blocks to neighbours while computing attention for their own query block against the received KV block. Ring Attention achieves perfect memory efficiency: the memory per device scales as O(n/N) where N is the number of devices, enabling training on sequences of arbitrary length by adding more devices. Combined with FlashAttention, Ring Attention enables training on 1 million-token sequences on a standard 8-GPU node. The connection to our big data guide is direct: Ring Attention is a distributed computing pattern for Transformers — the ring all-to-all communication topology is analogous to ring all-reduce in data parallel training described in that guide, applied to the KV cache rather than model gradients.
  • Mixture of Experts attention (MoE-Attention) and linear attention with hardware-aware kernels represent the frontier of efficient Transformer research. Jamba (AI21 Labs, 2024) interleaves Mamba SSM layers with standard Transformer attention layers, using fewer attention layers for global context and more Mamba layers for efficient sequence processing — combining the O(n) SSM efficiency with the proven quality of sparse attention. The key empirical finding: the optimal ratio of Mamba-to-attention layers is roughly 3:1 on language modelling benchmarks — most sequential processing benefits from the efficient Mamba recurrence, while a small number of full-attention layers provide the global context integration that pure SSMs lack. The connection to our MoE guide is direct: Jamba combines MoE feedforward layers (each token routed to 2 of 16 expert FFNs) with the interleaved Mamba/Attention architecture — both MoE routing and Mamba recurrence are efficiency mechanisms that reduce the per-token compute from O(d^2) (dense FFN) or O(nd) (full attention) to sub-linear scaling, composing naturally in a single architecture.

The quadratic scaling of standard Transformer attention is the dominant bottleneck preventing deployment of large models on long sequences — a 100,000-token document requires 10,000× more attention compute than a 1,000-token paragraph. The efficient Transformers research agenda is one of the most active in ML, producing FlashAttention (which makes exact attention faster without approximation), linear attention methods (which achieve sub-quadratic complexity through kernel approximations), sparse attention patterns (BigBird, Longformer, sliding window), and hybrid architectures that mix efficient SSMs with selective full attention. This guide covers the full efficient Transformers landscape: FlashAttention IO-aware exact attention, linear attention and kernel methods, sparse attention patterns, Ring Attention for distributed long-context training, and hybrid Mamba-Transformer architectures.

FlashAttention, Linear Attention and Sparse Attention

The GPU memory hierarchy has three levels relevant to attention computation: registers (fastest, ~1TB/s bandwidth, ~256KB), on-chip SRAM (fast, ~20TB/s bandwidth for NVIDIA A100, ~20MB), and off-chip HBM (slower, ~2TB/s bandwidth, ~40-80GB). Standard attention computation is memory-bandwidth bound rather than compute-bound: the GPU has sufficient FLOP capacity to perform the QK^T, softmax, and AV computations quickly, but the bottleneck is writing and reading the n×n attention matrix between SRAM and HBM. For n=4096 and d=64, the attention matrix is 4096×4096×4 bytes ≈ 64MB — far larger than SRAM, requiring multiple HBM reads/writes per attention layer. FlashAttention’s tiling approach: partition Q, K, V into blocks of size (B_r × d) and (B_c × d) that fit in SRAM, process each pair of Q-block and KV-block in SRAM using the online softmax trick (computing running max and sum for numerical stability without materialising the full softmax denominator), and accumulate the output O block-by-block. The result: the full attention computation fits entirely in SRAM, with only the final output O written to HBM — reducing HBM I/O from O(n^2) to O(nd) (the size of Q, K, V, and O). The 2-4× wall-clock speedup on A100 GPUs (and larger speedups on H100 with improved SRAM) makes FlashAttention the standard attention implementation in all major LLM training frameworks (HuggingFace Transformers, Megatron-LM, NanoGPT). The connection to our calculus and ML guide is direct: FlashAttention’s backward pass uses the online recomputation trick — instead of storing the n×n attention matrix for the backward pass (which would require O(n^2) memory), it recomputes attention on-the-fly during the backward pass from the saved softmax statistics (running max and sum). This is a specific application of gradient checkpointing (trading compute for memory) described in that guide’s discussion of memory-efficient backpropagation, achieving exact gradients with O(nd) memory rather than O(n^2). Performer’s FAVOR+ (Fast Attention Via positive Orthogonal Random features) constructs the feature map φ as random samples from the Fourier transform of the softmax kernel: φ(x) = exp(x^2/2) · (1/√m) · [cos(ω_1·x), sin(ω_1·x), …, cos(ω_m·x), sin(ω_m·x)] where ω_i are sampled from a standard Gaussian. This gives an unbiased estimator of softmax attention: E[φ(q)^T φ(k)] = exp(qk^T/d). The approximation quality improves with m (number of random features), and m = O(d log d) random features typically suffices for good approximation. The connection to our Gaussian processes guide is direct: Random Fourier Features (Rahimi & Recht, 2008) are a general technique for approximating any shift-invariant kernel (including the RBF kernel used in Gaussian process regression) described there — FAVOR+ applies RFF specifically to the softmax attention kernel, connecting the efficient Transformer and kernel methods literatures.

MethodComplexityExact?Parallelisable?Key Limitation
Standard attentionO(n^2 d)YesYesMemory: O(n^2); HBM bottleneck
FlashAttention-2/3O(n^2 d) FLOP; O(nd) IOYesYesNo complexity reduction; IO only
Linear attention (Performer)O(nd^2)No (approx)YesQuality gap vs. softmax on hard tasks
Sliding window (Longformer)O(n·w·d)Yes (within window)YesCannot attend beyond window without globals
BigBirdO(n·(w+g+r)·d)Yes (by construction)YesRandom attention pattern; not cache-friendly
Ring AttentionO(n^2/N · d) per deviceYesMulti-device ringRequires N devices; communication overhead
Mamba/RetNetO(n·d)No (recurrence approx)Parallel scan (train only)Bounded state; may miss long-range patterns

Ring Attention, Hybrid Architectures and Production Deployment

a colorful toy on a table
Photo by Shubham Dhage on Unsplash

The sequence parallelism challenge: LLM training with sequences longer than ~32k tokens requires distributing the attention computation across multiple GPUs even with FlashAttention, because the KV cache (K and V matrices for all n tokens) exceeds single-GPU memory. Tensor parallelism (splitting the attention heads across GPUs) works for wide models with many heads but introduces all-reduce communication overhead per attention layer. Ring Attention’s causal masking adaptation handles autoregressive (causal) attention: in the ring topology, devices process blocks in a specific order that respects the causal mask (future tokens cannot attend to past tokens), requiring careful scheduling of which device processes which block at each ring step. The connection to our MLOps CI/CD guide is direct: Ring Attention requires infrastructure changes to the distributed training framework — custom CUDA kernels for the inter-device KV transfer, modified attention computation to handle the ring scheduling, and monitoring of GPU-to-GPU interconnect utilisation (NVLink bandwidth must be sufficient to hide the KV transfer latency). These infrastructure requirements mean that Ring Attention is currently deployed primarily by hyperscalers (Google, Meta, Anthropic) with dedicated infrastructure teams rather than by standard model training frameworks. Hybrid architectures (Jamba, Zamba, MegaByte) represent the emerging consensus that neither pure Transformer nor pure SSM is optimal: some proportion of full-attention layers provides the global context integration that SSMs struggle with (the induction heads and attention patterns that enable in-context learning are hard to represent in bounded SSM state), while SSM layers provide efficient processing of the bulk of the sequence. The optimal proportion is an empirical question that depends on the task distribution: tasks requiring long-range precise information retrieval (retrieval-augmented generation, long-document QA) benefit from more attention layers; tasks requiring efficient processing of long sequential input (long documents, code, DNA sequences) benefit from more SSM layers. The connection to our neural architecture search guide is direct: searching over the ratio of Mamba-to-attention layers, the placement of full-attention layers within the network, and the size of the sliding window for sparse attention are NAS problems — the DARTS differentiable architecture search and evolutionary NAS methods described there can be applied to find the optimal attention/SSM ratio for a given compute budget and task distribution.

✦ SUMMARIZE THIS ARTICLE WITH AI

Long-context LLMs (FlashAttention enabling 128k+ context; RoPE and ALiBi for position extrapolation) are in our Long-Context LLMs guide. SSMs and Mamba (Mamba as linear attention alternative; Jamba hybrid architecture) are in our SSM/Mamba guide. MoE sparse models (MoE-Attention and Jamba combining MoE with efficient attention) are in our MoE guide. Gaussian processes (Random Fourier Features for kernel approximation connecting Performer to GP methods) are in our Gaussian Processes guide. Big data (Ring Attention as distributed computing for sequence parallelism) is in our Big Data guide. Neural architecture search (searching over attention/SSM ratios and sparse attention patterns) is in our NAS guide. Transformers (baseline multi-head attention that efficient methods optimise) are in our Transformers guide.

Leave feedback about this

  • Rating

Durgesh Kekare
Durgesh Kekarehttps://www.dataexpertise.in
Durgesh Kekare is a data science educator and founder of DataExpertise.in. With expertise in Python, machine learning, and analytics, he helps 10,000+ learners break into data careers.

Latest Posts

List of Categories