Self-attention Does Not Need $O(n^2)$ Memory

TL;DR

Proposes O(1) memory attention algorithm extended to O(log n), enabling scalable long-sequence modeling.

cs.LG 🔴 Advanced 2021-12-11 35 views
Markus N. Rabe Charles Staats
Deep Learning Attention Mechanism Transformer Memory Efficiency Algorithm Innovation

Key Findings

Methodology

The authors introduce a sequential accumulation approach for attention, delaying softmax normalization until the end. This method computes attention scores and weighted sums incrementally, maintaining only minimal variables. For single-query attention, it achieves O(1) memory; extending to self-attention involves processing queries sequentially with an index, reaching O(log n). Numerical stability is ensured via max-value tracking, and hardware-aware chunking optimizes performance. Implementation in JAX on TPU supports multi-head and backpropagation, balancing simplicity, efficiency, and stability.

Key Results

  • At sequence length 16384, memory overhead drops from hundreds of MB to about 1MB, a 59x reduction for inference and 32x for backpropagation; runtime remains comparable to standard attention, with BLEU scores in translation tasks nearly identical.
  • The algorithm maintains quadratic time complexity but drastically reduces device memory, enabling longer sequences on existing hardware.
  • Numerical stability is preserved through max-value tracking, preventing overflow in floating-point environments, ensuring accurate results across hardware platforms.

Significance

This work fundamentally challenges the assumption that self-attention inherently requires O(n^2) memory, opening pathways for large-scale long-sequence models. It addresses a critical bottleneck in hardware-constrained environments, broadening the applicability of Transformers in NLP, genomics, and beyond. By enabling longer context windows, it facilitates more comprehensive understanding and generation tasks, pushing the frontier of sequence modeling.

Technical Contribution

The paper introduces a non-approximate, memory-efficient attention algorithm leveraging incremental summation and max-value normalization, compatible with backpropagation. Hardware-aware chunking strategies further optimize performance on TPUs and GPUs, providing a practical, scalable solution that retains the original function's accuracy while significantly reducing memory footprint.

Novelty

This is the first approach to achieve O(1) memory for attention with exact computation, by delaying softmax normalization and employing a max-value tracking mechanism. Unlike prior sparse or low-rank approximations, it offers a complete, non-approximate solution that scales to very long sequences without sacrificing correctness.

Limitations

  • The algorithm still has O(n^2) time complexity, which can be computationally expensive for extremely long sequences. Hardware-specific optimizations are necessary for best performance.
  • Numerical stability depends on max-value tracking; in rare cases, floating-point errors could occur, especially with very large scores.
  • Current implementation is primarily validated on TPUs and GPUs; broader hardware compatibility and further optimization are future directions.

Future Work

Future research may focus on reducing time complexity to O(log n) using hierarchical or low-rank methods, enhancing numerical robustness, and extending to multi-modal data. Exploring adaptive chunking strategies and broader hardware support will further improve practical deployment.

AI Executive Summary

Traditional self-attention mechanisms in Transformers face a severe memory bottleneck, with storage requirements scaling quadratically with sequence length. This limits their application to relatively short sequences, especially on hardware with constrained memory. Addressing this challenge, the authors propose a novel algorithm that delays the softmax normalization step until the very end of the computation, allowing the entire attention process to be performed with constant memory in the single-query case. Extending this idea to self-attention involves processing queries sequentially, maintaining only a small set of summary variables, and employing a max-value tracking technique to ensure numerical stability. When implemented on TPU hardware with chunking strategies, this method reduces memory overhead by up to 59 times at sequence length 16384, with negligible impact on runtime. The approach is exact, not approximate, making it suitable as a drop-in replacement for standard attention modules. Experiments on translation tasks demonstrate that models trained with this method achieve BLEU scores comparable to traditional implementations, confirming the method's accuracy and effectiveness. This breakthrough opens new avenues for scaling Transformer models to longer sequences, broadening their applicability in NLP, genomics, and other fields where sequence length is a limiting factor. While the time complexity remains quadratic, the significant memory savings enable longer context windows and more resource-efficient training, marking a substantial step forward in neural sequence modeling. The work also discusses practical implementation details, including hardware-specific optimizations and backpropagation techniques, ensuring robustness and usability in real-world scenarios. Overall, this research fundamentally redefines the memory limits of attention mechanisms, promising a new era of scalable, long-context neural networks.

Deep Analysis

Background

Since its inception by Vaswani et al. (2017), the attention mechanism has revolutionized sequence modeling, especially within Transformer architectures. Early efforts like the Reformer (Kitaev et al., 2020) introduced sparse attention to reduce complexity, but still faced memory constraints at very long sequences. As models scaled up, the quadratic memory growth became a bottleneck, limiting applications in NLP, genomics, and beyond. Current solutions often rely on approximations or sparse methods, sacrificing some accuracy for efficiency. The need for an exact, memory-efficient attention algorithm remains urgent, especially with the advent of ultra-long sequence tasks. This paper addresses this gap by proposing a non-approximate method that drastically reduces memory consumption while maintaining full accuracy.

Core Problem

The core issue is that standard self-attention requires storing an n×n matrix of scores, leading to O(n^2) memory usage. For long sequences, this quickly exceeds hardware limits, making it infeasible. Although the time complexity remains quadratic, the memory bottleneck prevents scaling to longer inputs. Existing approaches like sparse attention or low-rank approximations compromise accuracy or introduce complexity. Therefore, developing a method that retains exactness while reducing memory is crucial for advancing large-scale sequence modeling.

Innovation

The key innovations include: 1) delaying softmax normalization to the end, enabling incremental computation; 2) maintaining a running maximum score for numerical stability; 3) processing queries and keys in chunks to reduce memory from O(n^2) to O(log n). These techniques are combined into a practical algorithm that computes the same attention output as the standard method, but with vastly reduced memory footprint. The implementation leverages hardware-aware chunking and checkpointing to support backpropagation, making it suitable for training large models on existing accelerators.

Methodology

  • �� The algorithm computes dot products between query and key vectors sequentially, updating two variables: a weighted sum of values and a total weight. • It postpones the softmax normalization by accumulating exponentiated scores and weighted values, tracking the maximum score to prevent overflow. • For self-attention, queries are processed one at a time, with an index tracking the current position, ensuring O(log n) memory. • Hardware-aware chunking divides keys and values into blocks of size √n, processing each block independently and summarizing results. • During backpropagation, checkpointing is used to recompute intermediate states, avoiding full storage. • The implementation in JAX on TPU supports multi-head attention with minimal memory overhead.

Experiments

The authors evaluate their method on sequence lengths from 28 up to 16384, measuring peak memory and runtime on TPUv3 hardware. Results show a consistent reduction in memory usage, up to 59-fold at length 16384, with runtime differences within 5%. They also train a Transformer for WMT translation, achieving BLEU scores nearly identical to standard attention. Additional experiments on differentiation demonstrate a 32-fold memory reduction during backpropagation, with acceptable slowdown due to checkpointing. These experiments confirm the method's scalability, accuracy, and efficiency across tasks and hardware.

Results

At sequence length 16384, memory overhead drops from hundreds of MBs to about 1MB, a 59× reduction, with negligible impact on translation BLEU scores. The method maintains quadratic time complexity but enables processing much longer sequences than previously feasible. During training, the model's BLEU scores and convergence behavior are nearly identical to standard attention, validating the approach's correctness. The memory savings during backpropagation are even more significant, facilitating large-scale training on resource-limited devices. Overall, the results demonstrate a practical, scalable solution for long-sequence modeling.

Applications

This algorithm is ideal for tasks requiring processing of very long sequences, such as document summarization, genomic data analysis, and long-form language modeling. It enables researchers and practitioners to build larger models or process longer inputs without hardware upgrades. In industry, it can reduce costs and hardware requirements, making large-scale NLP applications more accessible. Its exact computation ensures high fidelity, suitable for sensitive applications like legal or medical text analysis, where approximation errors are unacceptable.

Limitations & Outlook

Despite memory benefits, the method retains O(n^2) time complexity, which can be computationally intensive for extremely long sequences. Numerical stability depends on max-value tracking, which may be challenged in extreme score distributions. The current implementation is optimized for TPUs and GPUs; broader hardware support and further optimization are needed. Future work should explore reducing time complexity, improving robustness, and extending to multi-modal data, ensuring wider applicability and efficiency.

Plain Language Accessible to non-experts

想象你在厨房准备一大桌菜,传统做法是把所有食材都放在桌子上,一次性处理完。这样空间很快就不够用,也很容易乱。现在,假设你用一种聪明的方法,只拿一点点食材,做完后放到一边,再拿下一点。最后,把所有做好的部分拼在一起,组成完整的菜。这就像算法中逐步累加的思想,避免了存储全部中间结果的麻烦。这样一来,即使厨房空间有限,也能做出丰富的菜肴,效率还更高。

ELI14 Explained like you're 14

你知道玩拼图游戏吗?以前我们要把所有拼图都放在桌子上,一块块拼成完整的图。可是,拼多了,桌子就不够用了。现在,有个聪明的办法:每次只拼几块,拼完后放到一边,最后再把所有部分拼在一起。这样一来,不用占太多空间,也能拼出完整的图。这就像新算法一样,用巧妙的步骤,把大问题拆成小部分,既节省空间,又能得到一样漂亮的拼图。虽然花的时间差不多,但空间少了,可以拼更大更复杂的图,真是太棒了!

Abstract

We present a very simple algorithm for attention that requires $O(1)$ memory with respect to sequence length and an extension to self-attention that requires $O(\log n)$ memory. This is in contrast with the frequently stated belief that self-attention requires $O(n^2)$ memory. While the time complexity is still $O(n^2)$, device memory rather than compute capability is often the limiting factor on modern accelerators. Thus, reducing the memory requirements of attention allows processing of longer sequences than might otherwise be feasible. We provide a practical implementation for accelerators that requires $O(\sqrt{n})$ memory, is numerically stable, and is within a few percent of the runtime of the standard implementation of attention. We also demonstrate how to differentiate the function while remaining memory-efficient. For sequence length 16384, the memory overhead of self-attention is reduced by 59X for inference and by 32X for differentiation.

cs.LG