# Reformer: The Efficient Transformer

Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya · arXiv · 2020-1-13

- **Problem** Attention cost grows with the square of sequence length, and activations for every layer are stored for backpropagation, so large Transformers on long sequences exceed the memory of a single accelerator.
- **Method** Replaces full attention with LSH attention over shared query-key vectors, and uses reversible residual blocks plus chunked feed-forward computation to reduce activation memory.
- **Results** Reached 100% accuracy on the duplication task for a model trained with four hashes and evaluated with eight hashes. Reached 1.05 bits per dim on the enwik8 test set with a 12-layer Reformer trained longer with tuning.

## Where the memory goes

Sequences have grown as well, reaching 11 thousand tokens in one text example, and music and image inputs are longer still. The authors ask whether this scale really demands such resources or whether the resource use reflects inefficiency. A rough count points to inefficiency: 0.5B parameters take about 2GB, and 64K tokens at embedding size 1024 with batch size 8 add roughly another 0.5B floats, about 2GB more.

If memory were only per layer, a large Transformer should fit on one accelerator even for 64K-token sequences, since the whole BERT training corpus needs only 17GB of storage. That expectation fails, and the authors name three sources of memory use that the per-layer count leaves out.

Activations must be kept for every layer for backpropagation, so memory grows with the number of layers N. The feed-forward width \\(d\_{ff}\\) is usually much larger than \\(d\_{model}\\), so feed-forward activations take a large share of memory. Attention over a sequence of length L costs O(L^2) in both time and memory, so one 64K-token sequence can exhaust accelerator memory.

The QK^T matrix makes the attention cost concrete: for a 64K sequence at batch size 1 it is a 64K × 64K matrix, which takes 16GB in 32-bit floats. The authors note that this matrix need not be stored in full, because each query's attention can be computed separately and recomputed in the backward pass, though that may be less efficient.

## Hashing queries to nearby keys

Full attention compares each query with all keys, scales the scores, applies softmax and uses the result to weight the values, with queries, keys and values packed into matrices Q, K and V. \\\[ \\mathrm{Attention}(Q,K,V)=\\mathrm{softmax}\\left(\\frac{QK^{T}}{\\sqrt{d\_k}}\\right)V \\\] The method relies on the fact that softmax is dominated by its largest entries, so each query needs only the few keys closest to it.

A shared-QK Transformer produces queries and keys from one linear layer and produces values from a separate one. Hashing requires queries and keys to match, and this structure guarantees that they do. Keys are then normalized to \\(k\_j = q\_j/\\lVert q\_j \\rVert\\), so a key and its query fall into the same bucket. Sharing QK does not hurt performance, even with this key normalization.

Self-attention is forbidden in this setting, because a query's dot product with itself tends to be larger than with any other position.

The hash uses a random matrix R of size \\(\[d\_k, b/2\]\\), and \\(h(x)=\\arg\\max(\[xR; -xR\])\\), so the signed projections of x give b buckets. Points that are close on the sphere tend to share a bucket across hashes, as Figure 1 illustrates in a simplified 2D view.

Buckets come out uneven in size, and a bucket can hold many queries but no keys, which makes batching across buckets difficult. Queries are sorted by bucket number and then by position, so pairs from the same bucket cluster near the diagonal of the attention matrix. Sorted queries are cut into chunks of m consecutive entries, and each chunk attends to itself and the chunk before it, with \\(m = 2l/n\_{buckets}\\).

A single hash can separate similar vectors, so the method runs \\(n\_{rounds}\\) distinct hash functions and takes the union of the key sets they produce. \\\[ \\mathcal{P}\_i=\\bigcup\_{r=1}^{n\_{rounds}}\\mathcal{P}\_i^{(r)} \\\] Causal masking works by attaching each position index to its vector, applying the same sort permutation, and comparing the indices.

Table 1 gives the LSH memory term as \\(b\\,n\_h\\,l\\,n\_r(4l/n\_c)^2\\), while the full-attention term is \\(b\\,n\_h\\,l^2\\) inside the max.

## Reversible blocks and chunked feed-forward

During backpropagation the layers are therefore inverted one at a time, starting from the output, so intermediate activations need not be stored.

For the Transformer, F becomes the attention layer and G becomes the feed-forward layer, with Layer Normalization moved inside the residual blocks. The blocks are \\(Y\_1 = X\_1 + \\mathrm{Attention}(X\_2)\\) and \\(Y\_2 = X\_2 + \\mathrm{FeedForward}(Y\_1)\\). Because each block can be inverted, the whole network keeps one copy of activations, so the factor for the number of layers N disappears.

Both \\(x\_1\\) and \\(x\_2\\) have size \\(d\_{model}\\).

In a big Transformer the feed-forward width is usually 4K, and the paper counts 16 layers for that configuration, which at 64K tokens would use about 16GB. Feed-forward computation is independent across positions, so the sequence can be split into c chunks that are processed one at a time. \\\[ Y\_2=\\left\[X\_2^{(1)}+\\mathrm{FeedForward}(Y\_1^{(1)});\\ \\dots;\\ X\_2^{(c)}+\\mathrm{FeedForward}(Y\_1^{(c)})\\right\] \\\]

The reverse computation and the backward pass are chunked in the same way, and for models with a large vocabulary the output log-probabilities are chunked as well. With chunking and reversibility, activation memory no longer depends on the number of layers, but parameter count still grows with depth. The authors move layer parameters to CPU memory while a layer is idle, which would be slow in a standard Transformer but is amortized here because batch size times length is much larger.

## Duplication task and hash count

Each example has the form \\(0w0w\\), where w is a sequence of symbols from 1 to 127. The language model sees w of length 511, so the input has length 1024, and loss and accuracy are measured only on the second half. A one-layer Transformer solves the task perfectly, but the task needs non-local lookups, so a model restricted to sparse attention with a limited span cannot solve it.

The model has \\(d\_{model} = d\_{ff} = 256\\) and 4 heads, and it is trained for 150K steps in four settings: full attention and LSH attention with \\(n\_{rounds}\\) set to 1, 2 and 4.

A model trained with full attention scores 100% under full attention and drops to 52.5% when evaluated with one LSH hash. Evaluated with eight hashes, the same model reaches 94.8%. Table 2 places each training setting against each evaluation setting, which makes the effect of the hash count visible across rows.

A model trained with four hashes scores 100% with eight hashes and 99.9% with four. The model trained with one hash scores 99.9% with eight hashes, while its own one-hash score is 77.9%. Accuracy falls when fewer hashes are used at evaluation, and the authors note this drop for two and one hashes.

## Ablations on enwik8 and imagenet64

All models use \\(d\_{model} = 1024\\), \\(d\_{ff} = 4096\\), 8 heads and a total batch of 8 sequences, trained with the Adafactor optimizer on enwik8-64K and imagenet64.

Shared-QK attention sets k\_j to the normalized q\_j and blocks self-attention where other context exists. On the left of Figure 3, shared-QK attention does not perform worse than regular attention, and on enwik8 it appears to train slightly faster. The authors conclude that switching to a shared query-key space does not sacrifice accuracy.

On the right of Figure 3, the regular Transformer and the reversible Transformer have identical parameter counts, and their learning curves are nearly the same. The authors read this as memory savings that do not come at the cost of accuracy.

## Translation results and attention speed

Both encoder and decoder were made fully reversible in the Transformer-base architecture for English-to-German translation.

LSH attention is not applied in this setting, because the examples are single sentences and the typical configuration uses chunks of 128 tokens, while the WMT14 test examples are all shorter than 128 tokens.

Figure 4 shows LSH attention on imagenet64 coming closer to full attention as the number of hashes grows, and at 8 rounds it almost matches full attention. The hash count sets the computational cost, so it can be tuned to a compute budget, and more hashes can be used at evaluation time for better accuracy.

With the total number of tokens held fixed, regular attention slows as sequence length grows, while LSH attention speed stays flat.

## Large Reformer models

Up to 20-layer big Reformers were trained on enwik8 and imagenet64, and these models fit into memory and train. The Transformer baselines could not be trained at this scale, because they are too slow and memory-hungry. On the left of Figure 5, LSH attention performance on enwik8 improves as the number of layers increases.

A 12-layer model trained for 20K steps with dropout rate 0.1 reaches 1.19 bits/dim on the test set. A 12-layer Reformer trained longer, with further tuning and improvements, reaches 1.05 bits/dim on the enwik8 test set. The two runs differ in training length and tuning, so their gap is not a controlled comparison.

## Limitations

The duplication task is a one-layer synthetic setting, and the ablations use three-layer models. The main Reformer numbers on text come from enwik8 and the translation numbers from WMT14 with reversible layers only.

Reversible residuals change the model, though the authors found their effect on training negligible in every configuration they tried. LSH attention is the more major change, and its effect on training depends on the number of hashes used.

LSH attention is not applied to the translation experiments, because the WMT sentences are short. The Transformer baselines were not trained at the largest depths, so the 1.05 bits/dim result has no matched baseline.

## Paper info

- **Authors**: Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya
- **Venue**: arXiv · Preprint
- **First published**: 2020-1-13
- **Added**: 2026-10-20
- **Updated**: 2020-2-18
- **Version**: v2
- **arXiv**: 2001.04451
- **Category**: cs.LG · cs.CL · stat.ML
- **Original paper terms**: [arXiv non-exclusive 1.0](https://arxiv.org/licenses/nonexclusive-distrib/1.0/)
- **What we show**: Paper info and commentary

[Original paper ↗](https://arxiv.org/abs/2001.04451v2) · [PDF ↗](https://arxiv.org/pdf/2001.04451v2)

AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.

## Quote from the paper

Nikita Kitaev, Łukasz Kaiser, Anselm Levskaya (2020). Reformer: The Efficient Transformer. arXiv:2001.04451v2. https://arxiv.org/abs/2001.04451v2

**BibTeX**

```
@misc{kitaev2020reformer,
  title = {{Reformer: The Efficient Transformer}},
  author = {Nikita Kitaev and Łukasz Kaiser and Anselm Levskaya},
  year = {2020},
  eprint = {2001.04451},
  archivePrefix = {arXiv},
  url = {https://arxiv.org/abs/2001.04451v2}
}
```

## Other paper commentary

- [Generating Long Sequences with Sparse Transformers](https://refivu.com/en/papers/25192f20-3966-40d3-94ed-65ebcaba60f7-generating-long-sequences-with-sparse-transformers.md)
- [Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient Sparsity](https://refivu.com/en/papers/2712d011-b4e2-4181-89ce-e47fc4a5117c-switch-transformers-scaling-to-trillion-parameter-models.md)
- [Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer](https://refivu.com/en/papers/01d9fd25-ae98-40fb-a44a-08c4b727555b-outrageously-large-neural-networks-the-sparsely-gated.md)
- [FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://refivu.com/en/papers/cc000b48-2d42-4287-aae7-f3583a852720-flashattention-fast-and-memory-efficient-exact-attention.md)
- [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://refivu.com/en/papers/70da27bf-5c2f-4e05-bfe2-7c145011b0d9-distilbert-a-distilled-version-of-bert-smaller-faster.md)
- [QLoRA: Efficient Finetuning of Quantized LLMs](https://refivu.com/en/papers/27d2d955-4f1a-4d56-aef7-766870813fe4-qlora-efficient-finetuning-of-quantized-llms.md)
- [Gemma: Open Models Based on Gemini Research and Technology](https://refivu.com/en/papers/e2b5810b-65da-4a36-9bd2-a17a9a6f8512-gemma-open-models-based-on-gemini-research-and.md)
- [Decision Transformer: Reinforcement Learning via Sequence Modeling](https://refivu.com/en/papers/386e76e8-fee6-4cba-84e8-0ef90a33b3b6-decision-transformer-reinforcement-learning-via-sequence.md)
- [A Generalist Agent](https://refivu.com/en/papers/890475cb-e797-43df-8de3-0d0eb9ed882e-a-generalist-agent.md)
- [Denoising Diffusion Implicit Models](https://refivu.com/en/papers/211aa1a1-08e2-40a7-b187-72384021f47a-denoising-diffusion-implicit-models.md)
- [Phi-3 Technical Report: A Highly Capable Language Model Locally on Your Phone](https://refivu.com/en/papers/1ae6b2e4-9099-4676-8fc3-523fa63b6919-phi-3-technical-report-a-highly-capable-language.md)
- [BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models](https://refivu.com/en/papers/3bd907be-414a-4e3b-b195-d25379e2be77-blip-2-bootstrapping-language-image-pre-training-with.md)

## Terms in this paper

- [Transformer](https://refivu.com/en/terms/48e8be2570bc-transformer)
- [perplexity](https://refivu.com/en/terms/2b204e513801-perplexity)
- [BLEU](https://refivu.com/en/terms/42cd9b97719e-bleu)
- [layer normalization](https://refivu.com/en/terms/7af9eccdb60d-layer-normalization)
- [Adafactor](https://refivu.com/en/terms/b0f03894f97e-adafactor)
- [Reformer](https://refivu.com/en/terms/09e7750949bd-reformer)
- [Scaled Dot-Product Attention](https://refivu.com/en/terms/0e345f72fc32-scaled-dot-product-attention)
- [enwik8](https://refivu.com/en/terms/610a8bf17f12-enwik8)
- [bits per dim](https://refivu.com/en/terms/cd7b8b097e0e-bits-per-dim)
- [Chunking](https://refivu.com/en/terms/7397da755474-chunking)
- [locality-sensitive hashing](https://refivu.com/en/terms/a7e3d2290a38-locality-sensitive-hashing)
- [WMT 2014 English-to-German](https://refivu.com/en/terms/818e6329e850-wmt-2014-english-to-german)

---

AI-written text can contain mistakes. [Refivu](https://refivu.com/en/papers/0dd490a3-709f-4bac-ae3f-de0bc9e197db-reformer-the-efficient-transformer)
