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

Markus N. Rabe, Charles Staats
12/10/2021
cs.LG

Official code: google-research/google-research (39,000 stars, Apache-2.0, last commit 2026-04-30). 1 more implementation below.

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.

View on arXivView PDF

Code Implementations(2)

Apache-2.0

Google Research

39,0008,488C, ROct 4, 20185 months agoApache-2.0
aimachine-learningresearch
MIT

Implementation of a memory efficient multi-head attention as proposed in the paper, "Self-attention Does Not Need O(n²) Memory"

39337PythonMar 3, 20223 years agoMIT
artificial-intelligenceattention-mechanismdeep-learningmemory-efficient

Similar Papers

Cite this paper

@article{rabe2021selfattention,
  title  = {Self-attention Does Not Need $O(n^2)$ Memory},
  author = {Markus N. Rabe and Charles Staats},
  year   = {2021},
  eprint = {2112.05682},
  archivePrefix = {arXiv},
  url    = {https://arxiv.org/abs/2112.05682}
}

Add a badge to your README

Shows whether official code is linked for this paper.

Code of Paper badge
[![Code of Paper](https://codeofpaper.com/badge/2112.05682.svg)](https://codeofpaper.com/paper/2112.05682)

Discussion