Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

Reformer

Reformer (Kitaev, Kaiser and Levskaya, ICLR 2020) makes Transformers fit very long sequences on one accelerator with three ideas. Locality-sensitive-hashing (LSH) attention hashes shared queries and keys with random rotations so each token attends only to keys in its bucket, about O(L log L) with sorting. Reversible residual layers recompute activations in the backward pass instead of storing them. Chunked feed-forward layers bound peak memory. It processed 64 K-token sequences. This page covers angular LSH, multi-round hashing, reversible layers and the memory savings. In the exercises you implement LSH hashing, collision probabilities and reversible blocks, then measure how much of the true attention LSH recovers on clustered keys. With 32 buckets, one hashing round captures 62% of the attention mass while comparing 7.3% of key pairs; four rounds capture 96% at 16%.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Only compare with likely matches

Attention gives most of its weight to a few very similar keys. Reformer finds those likely matches cheaply: it hashes every vector into a bucket so that similar vectors usually land in the same bucket, then compares each word only with words in its bucket. Hashing a few times with different random hashes catches matches that one hash missed. Reformer also saves memory by recomputing intermediate results instead of storing them. The demo shows how sparse attention patterns reduce work.

Transformer lab
Full attention stores 16,777,216 scores per head; a linear-time method with 64 features stores 262,144, 64 times fewer.
Why engineers care

Memory, not compute, often limits sequence length on accelerators. Reformer’s reversible layers and hashing show two general ways to trade a little extra work for much less memory.

📝 Quick check (Level 0)
0/3 answered
  1. 1. LSH attention compares a token with…
  2. 2. Hashing several times…
  3. 3. Reversible layers save…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Angular LSH:
    • h(x) = argmax([xR; −xR]) with a random d × (b/2) matrix R, giving b buckets;
    • scaling x does not change its bucket;
    • for b = 2 (one random hyperplane), vectors at angle θ collide with probability 1 − θ/π: 1 at θ = 0, 0.5 at π/2.
  • Rounds: if one round collides with probability p, n independent rounds give 1 − (1 − p)ⁿ. For p = 0.5 and 4 rounds that is 0.9375.
  • Shared QK: Reformer uses keys equal to normalised queries, so a query and its keys hash consistently. Tokens do not attend to themselves (except when nothing else is available).
  • Cost:
    • sort tokens by bucket and attend within chunks;
    • with balanced buckets each query compares with about L/b keys per round;
    • for L = 65,536, b = 1024 and 4 rounds, 0.4% of all pairs.
  • Reversible layers:
    • y₁ = x₁ + F(x₂) and y₂ = x₂ + G(y₁), inverted by x₂ = y₂ − G(y₁) and x₁ = y₁ − F(x₂);
    • only the last layer’s activations are stored, a factor of the number of layers less (12 for 12 layers).
  • Chunked FFN: process the d_ff-wide hidden layer in sequence chunks. 64 chunks cut its peak memory 64-fold.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Collision probability for θ = π/2 with one hyperplane:
  2. 2. Recall of 4 rounds at p = 0.5:
  3. 3. Reversible layers store activations…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Reformer in code

Exercise 1.

  • The LSH bucket was invariant to scaling.
  • Simulated random hyperplanes reproduced the 1 − θ/π collision rate within 0.01.
  • A reversible block recovered its inputs exactly.

Practice.

  • Hugging Face ReformerModel alternates LSH and local attention layers (attn_layers), with num_hashes rounds and num_buckets, and uses axial position embeddings for very long inputs.
  • Hashing is not differentiable, so gradients flow only through the attention computed within buckets.
  • On GPUs, FlashAttention (E12-20) and simpler sparse patterns often beat LSH in practice, but reversible layers and activation recomputation (gradient checkpointing) remain widely used.
def lsh(x, n_buckets, rng):
    R = torch.randn(x.shape[-1], n_buckets // 2, generator=rng)
    p = x @ R
    return torch.cat([p, -p], -1).argmax(-1)                  # bucket per token
order = lsh(qk, 64, rng).argsort(-1)                          # sort by bucket, then attend within chunks
🐍 Exercise 1: hashing and reversibility
Implement angular LSH, the one-hyperplane collision probability and a reversible block with its inverse.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Hugging Face argument for hash rounds:
  2. 2. Is hashing differentiable?
  3. 3. A widely used relative of reversible layers:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why LSH approximates attention.

  • Softmax attention is dominated by the keys with the largest dot products, the nearest in angle for normalised vectors.
  • Angular LSH puts nearby vectors in the same bucket with high probability, so computing attention only within buckets keeps most of the mass.
  • What is missed is far keys (small weight) and near keys split by an unlucky hash, which extra rounds recover.

Recall versus cost.

  • More buckets mean fewer comparisons per round but more splitting of true neighbours.
  • More rounds raise recall but multiply cost.
  • Exercise 2 maps this trade-off: with 32 buckets, 1 round captures 62% of the mass at 7% of the pairs, and 4 rounds 96% at 16%.

Reversibility.

  • Backpropagation normally stores every layer’s activations, using memory proportional to depth.
  • Reversible blocks (Gomez et al., 2017) let each layer’s input be recomputed from its output during the backward pass, costing about one extra forward computation.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Softmax attention is dominated by…
  2. 2. More buckets…
  3. 3. Reversible networks were introduced by…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

How much attention does hashing recover?

History.

  • N. Kitaev, Ł. Kaiser and A. Levskaya, “Reformer: the efficient Transformer” (ICLR 2020).
  • A. Gomez, M. Ren, R. Urtasun and R. Grosse introduced reversible residual networks (NeurIPS 2017).
  • Angular LSH comes from Andoni et al. (2015).

Exercise 2.

  • Data: 512 keys of dimension 32 drawn around 32 cluster centres and normalised to length 8, so attention is peaked as in trained models. Queries share them (shared QK).
  • Hashing: angular LSH with 8 or 32 buckets, over 1–8 rounds.
  • Measurement: the share of each query’s full softmax attention mass on keys sharing a bucket in some round, and the share of key pairs compared.
buckets, rounds mass captured pairs compared gain over random
8, 1 0.629 14.7% 4.3×
8, 4 0.989 44.3% 2.2×
32, 1 0.622 7.3% 8.5×
32, 2 0.799 10.4% 7.7×
32, 4 0.955 16.2% 5.9×
32, 8 0.993 26.6% 3.7×
  • LSH concentrates comparisons where the attention is: one round with 32 buckets captures 62% of the mass from 7% of the pairs, 8.5 times better than comparing random keys.
  • Rounds buy recall at linear cost. Four rounds reach 96%, eight reach 99%, but the share of pairs compared grows.
  • The gains depend on peaked attention. With keys of length 4 (flatter attention), one 32-bucket round captured only 22% of the mass. LSH helps most when attention is sharply focused.
  • A second seed gave similar values: 0.50 and 0.96 for one and four 32-bucket rounds.
🐍 Exercise 2 (research): how much attention does hashing recover?
Hash clustered keys with angular LSH and measure the share of softmax attention mass kept, against the share of pairs compared.

Reformer in AI, robotics and aerospace

  • Memory-limited training: reversible layers and recomputation let large models train on modest accelerators, as on-premise or embedded training setups require.
  • Similarity search: LSH is also a general tool for fast nearest-neighbour search over sensor signatures or map features.
  • Long sequences: combine hashing or sparsity with chunking to process long recordings on one device.

References

  1. N. Kitaev, Ł. Kaiser, A. Levskaya (2020). “Reformer: the efficient Transformer.” Proc. ICLR.
  2. A. N. Gomez, M. Ren, R. Urtasun, R. B. Grosse (2017). “The reversible residual network: backpropagation without storing activations.” Proc. NeurIPS.
  3. A. Andoni et al. (2015). “Practical and optimal LSH for angular distance.” Proc. NeurIPS.