Architecture · Long context · Memory efficiency

Reformer: The Efficient Transformer

Hash similar tokens into attention buckets and invert each layer during backprop, so a Transformer runs on 64K-token sequences.

Reformer replaces quadratic self-attention with angular locality-sensitive hashing, replaces standard residual blocks with reversible layers that recompute inputs on the backward pass, and chunks feed-forward layers along the sequence so 65,536-token models fit in single-accelerator memory.

Explaining the paperReformer: The Efficient TransformerKitaev, Kaiser, Levskaya · ICLR 2020 · arXiv:2001.04451 ↗
Listen26 min narrated explainer0:00 / 26:06
Visual explainer24:53Watch on YouTube

Training a 16-layer Transformer on 65,536 tokens hits three separate memory walls (the quadratic attention matrix, the 16 saved layer inputs, and the 4× feed-forward expansion), and Reformer replaces each one with a dedicated mechanism.

Where Transformer memory goes

Start with the paper's back-of-the-envelope calculation from Section 1. The largest single Transformer layer reported before 2020 held 0.5 billion parameters, which takes 2 GB in 32-bit floats. Input activations for a batch of 8 sequences, each 64K tokens long ( is , or 65,536) with embedding width of 1024, hold 8 × 65,536 × 1024 = 536.9M floats, another 2 GB. Counting only one layer's weights and one layer's input, a 64K-token Transformer should fit comfortably inside a single 16 GB GPU or TPU core.

In practice it runs out of memory immediately, because three multipliers sit between that single-layer estimate and a real training step:

  1. The quadratic attention matrix. Standard scaled dot-product attention packs queries , keys , and values into matrices of shape (batch size, heads, sequence length, head width) and computes:
    (1)
    The intermediate score matrix has shape . Even for a single sequence ( of 1) and a single head ( of 1) at 65,536 tokens, storing 65,536² ≈ 4.29 billion 32-bit floats takes 16 GB. Across 8 heads and 16 layers, the score matrices alone demand 2,048 GB.
  2. The depth multiplier . Backpropagation needs every layer's input activations to compute weight gradients. A 16-layer model stores 16 copies of the activation tensor across the stack (4 GB for the residual stream alone at batch size 1).
  3. The feed-forward width . Inside each Transformer block, the position-wise feed-forward network (FFN) expands every token vector from to a wider hidden dimension , typically (4096 when is 1024). Storing those intermediate tensors across 16 layers at 65,536 tokens and batch size 1 takes 65,536 × 4096 × 16 × 4 bytes, another 16 GB.

Even the paper's baseline memory-efficient attention (computing one query row's softmax and value sum at a time, then recomputing it during backprop, an early precursor to FlashAttention) solves only attention memory, leaving attention compute at and leaving both the and memory terms untouched.

Use Figure 1 to test each piece of Reformer on a 16-layer, 8-head model at 64K tokens (batch size 1, fp32). Toggle locality-sensitive hashing (LSH) attention on by itself first: total activation memory drops from 2,068 GB to 52.0 GB, still over a 16 GB chip because all 16 layers store their LSH scores (32 GB), feed-forward intermediates (16 GB), and residual streams (4 GB). Adding reversible layers removes the 16× depth multiplier, dropping the total to 3.50 GB; adding chunked feed-forward cuts the 1 GB FFN spike down to 64 MB, bringing total activation memory to 2.56 GB.

Figure 1 · three memory walls
L = 64Klayers = 16
Activation memory on a log scale for batch size 1 in fp32 (width 1024, FFN width 4096, 8 heads). Toggle LSH attention, Reversible layers, and Chunked FFN independently, or sweep sequence length and depth. All three fixes together bring 64K-token activations comfortably below the 16 GB line.

Reformer pairs one targeted mechanism with each bottleneck: locality-sensitive hashing cuts attention from to , reversible residual layers eliminate the activation multiplier, and sequence chunking removes the spike without changing a single output number.

Shared-QK attention and why tokens stop attending to themselves

Equation (1) only uses the entries of to produce softmax probabilities. Because exponentiation amplifies gaps between scores, a small subset of keys (often 32 or 64 out of 65,536) receives nearly all of the softmax weight for any given query . Finding the output for therefore reduces to finding the keys with the largest dot products , a nearest-neighbor search in .

Before applying hashing to that search, Reformer makes one structural change to multi-head attention. A standard Transformer projects the incoming activation tensor of shape through three separate weight matrices , , and . If queries and keys live in different projections and you hash both into buckets, a bucket can easily end up holding many queries and zero keys, or uneven numbers of each. Reformer prevents that mismatch by sharing one linear projection for queries and keys and normalizing every key to unit Euclidean length:

(2)

Sharing queries and keys guarantees that token 's query and key always fall in the exact same hash bucket, so every bucket has equal numbers of queries and keys. Unit-normalizing serves two purposes: no single key can dominate dot products by having a large norm, and for any fixed query , the dot product equals , so maximizing it is equivalent to minimizing the angle between and . (In the official Trax code, length_normalized divides by its RMS norm , and attend then divides by ; the two factors of cancel, leaving unit-normalized keys with the scale already folded in.)

Sharing queries and keys breaks one default of standard causal self-attention. By the Cauchy-Schwarz inequality, a vector's dot product with its own unit-normalized self is always at least as large as its dot product with any other unit vector:

Take a concrete 2D vector with components [3, 4], norm 5, and normalized key [0.6, 0.8]. Its self-score is 5.0, while another token just away scores (about 4.33), and a token away scores 2.50. If a token is allowed to attend to itself, its own diagonal entry dominates the softmax at every position.

Reformer therefore forbids self-attention ( attending to ) as well as future attention (). Instead of masking self-attention with , however, the mask subtracts a large finite penalty of (-1e5 in Trax, vs -1e9 for future positions). Position 0 has no earlier tokens to attend to (and in chunked LSH, a token occasionally lands alone with no earlier key in its window). Masking the diagonal with would leave an all- row and produce NaN in softmax; masking with lets a lone token attend to itself with weight 1 (since cancels in softmax normalization), while shrinking its self-weight to (underflowing to 0) whenever any earlier key is present.

On 3-layer models tested on both enwik8-64K (64K-byte Wikipedia text sequences) and ImageNet-64 (12K-byte serialized 64×64 images) (Paper Figure 3, left), shared-QK with self-exclusion matches separate-QK training curves, and converges slightly faster early on enwik8.

How locality-sensitive hashing attention works

With unit keys from Equation (2), finding the largest dot products for query means finding keys at the smallest angle to . An ordinary cryptographic hash like SHA-256 scrambles similar inputs into unrelated buckets. A locality-sensitive hash (LSH) does the opposite: it maps every vector to a discrete bucket ID in so that vectors with a small angle land in the same bucket with high probability, vectors far apart rarely collide, and buckets stay roughly similar in size.

Reformer uses the angular cross-polytope LSH scheme of Andoni et al. (2015). To create buckets (with even), sample a fixed random Gaussian matrix of shape and assign each vector to:

(3)

where concatenates the projections and their negatives into a vector of length . Geometrically, the columns of and define signed directions radiating from the origin (the vertices of a randomly projected cross-polytope; in 2D with 4 buckets, these are the four compass points rotated by a random angle). Taking the argmax labels every vector by whichever signed axis it aligns with most closely, slicing the unit sphere into equal angular cones. Because scaling by any positive number multiplies every entry of by , the argmax depends only on direction, confirming that always equals .

Work through a concrete example with head dimension 4 and 8 buckets, so the random matrix has shape . Suppose multiplying query by gives four projections, which we concatenate with their negatives:

The maximum entry is at index 5, so is 5. Any nearby vector also has its most negative projection along column 1 of , landing in bucket 5. (At long lengths where , say 2,048 buckets for 64K tokens, Trax factorizes 2,048 as 64 × 32 and runs two small cross-polytope hashes of 32 and 16 columns combined as , keeping the random projection cheap instead of .)

One random rotation always leaves sharp seams: two vectors apart can still straddle a bucket boundary and miss each other. Running independent random matrices in parallel drives the miss rate down exponentially. If one round catches a nearby pair with probability , the chance all rounds miss is , so the probability of colliding in at least one round rises to . In Figure 2, drag around the circle and raise from 1 to 8: with 8 buckets (each wide), two vectors apart collide only 51% of the time in 1 round, but 94% of the time across 4 rounds and 99.7% across 8 rounds, while distant vectors beyond still never collide.

Figure 2 · angular LSH in 2D
θ = 22°
b = 8n_r = 4
Cross-polytope angular LSH on the unit circle (Round 1 buckets shown left; exact collision probability right). Drag the key k around the circle or sweep , adjust bucket count and rounds , and resample . Raising lifts the multi-round curve close to 1 for small angles while keeping distant angles at zero.

Sorting, chunking, and multi-round hashing

To turn bucket IDs into a fast batched GPU or TPU kernel, rewrite attention for a single query position over an allowed key set (for causal full attention, all indices ):

(4)

In Equation (4), is the log-partition function (the log-sum-exp normalizer of the softmax; the paper calls it the "partition function" as shorthand, and omits because unit-normalized keys already fold it in). For fixed-shape batching, we compute scores over a larger regular set containing and subtract a mask that equals when and 0 otherwise:

(5)

In single-round LSH attention, the target set is every valid key sharing query 's bucket (those with equal to , intersected with in a causal decoder). Hardware accelerators cannot batch ragged buckets directly because one bucket might hold 3 tokens while another holds 9. Reformer solves raggedness in three steps:

  1. Sort by bucket, then position. Compute the sort key bucket_id * L + pos, mapping each original index to its sorted slot . Tokens with the same hash now sit side by side along the sequence axis, so same-bucket pairs cluster into diagonal blocks.
  2. Slice into fixed chunks of length . Set the number of buckets to so the average bucket holds tokens (in Trax, default is 128 or 64).
  3. Attend within the chunk and one chunk back. A bucket can straddle a chunk boundary (starting near the end of chunk and finishing in chunk ). Letting every query in chunk attend to all keys in chunk and chunk defines the batched attention window:
    (6)
    Because tokens inside each bucket are sorted by original position, causal keys () always sit to the left of query inside its bucket. Whenever the largest bucket has fewer than tokens, looking one chunk back guarantees that every target in falls inside .

Step through all four stages in Figure 3 on a 32-token sequence whose six buckets have uneven sizes (from 3 to 9 tokens). In stage 4 at chunk size 8, every same-bucket pair fits inside the teal chunk-plus-one-back boxes. Then drag down to 4: the 9-token bucket spans more than two chunks, and the amber-outlined pairs drop out of the window entirely, showing the exact failure mode when buckets grow too imbalanced.

Figure 3 · hash, sort, and chunk
m = 8
32 tokens hashed into 6 uneven buckets (largest size 9; bucket IDs shown on the margin strips). Switch between Full, Hashed, Sorted, and Chunked, click any query row to inspect it, and drag chunk length to 4 to see overflowed pairs miss the chunk + prev window.

To run hashing rounds in parallel, each round independently hashes, sorts, chunks, and returns two tensors in sorted order: its local attention output and its per-query log-sum-exp normalizer . Both tensors are unsorted back to original token order. Combining two softmax outputs computed on separate subsets of keys does not mean averaging them equally; a round that found a high-scoring key has a larger log-sum-exp and receives more weight. Weighting each round by its share of the total partition function gives the multi-round combination from Appendix A:

(7)

Appendix A of the paper also writes down two stricter masking rules: masking out tokens from neighboring buckets that happen to sit inside the same chunk (setting to for ), and subtracting where is the number of rounds in which pair collided, so duplicate pairs are not over-counted in the union. In the authors' official Trax implementation (LSHSelfAttention in efficient_attention.py), both are omitted: queries attend to all causally valid tokens in the chunk and previous chunk (including neighboring buckets) and combine rounds directly with Equation (7), which avoids tracking cross-round collision counts while slightly enlarging the candidate pool.

# Multi-round LSH attention for one head (Trax LSHSelfAttention)
# x: [L, d_model], w_q: [d_model, d_k], w_v: [d_model, d_v]
q = x @ w_q                                     # [L, d_k]
v = x @ w_v                                     # [L, d_v]

# 1. Angular LSH buckets via n_r random rotations R: [d_k, n_r, b/2], (3)
rot = einsum('ld,drh->rlh', q, R)               # [n_r, L, b/2]
buckets = argmax(cat([rot, -rot], axis=-1))     # [n_r, L] in 0..b-1
buckets = (buckets + arange(n_r)[:, None] * b).reshape(-1)  # [n_r * L]

# 2. Sort by (bucket_id, position) and gather sorted queries/values
pos = arange(n_r * L) % L                       # [n_r * L]
key = buckets * L + pos                         # primary: bucket, tie: pos
order = argsort(key)                            # i -> s_i permutation
sq, sv, spos = q[pos[order]], v[pos[order]], pos[order]     # [n_r * L, ...]

# 3. Reshape into chunks of m and attend to self + 1 chunk back, (6)
sq = sq.reshape(n_c, m, d_k)                    # n_c = (n_r * L) // m
sk = l2_normalize(sq, axis=-1)                  # unit keys k_j, (2)
sv = sv.reshape(n_c, m, d_v)
sk_adj = cat([roll(sk, 1, axis=0), sk], axis=1) # [n_c, 2*m, d_k]
sv_adj = cat([roll(sv, 1, axis=0), sv], axis=1) # [n_c, 2*m, d_v]

dots = einsum('cmd,ckd->cmk', sq, sk_adj)       # [n_c, m, 2*m]
dots = mask_causal_and_self(dots, spos)         # future: -1e9, self: -1e5
z_r  = logsumexp(dots, axis=-1, keepdims=True)  # [n_c, m, 1]
so   = einsum('cmk,ckv->cmv', exp(dots - z_r), sv_adj)      # [n_c, m, d_v]

# 4. Unsort and combine rounds by log-sum-exp weight, (7)
o_r  = unsort(so.reshape(n_r * L, d_v), order).reshape(n_r, L, d_v)
z_r  = unsort(z_r.reshape(n_r * L, 1),  order).reshape(n_r, L, 1)
w_r  = exp(z_r - logsumexp(z_r, axis=0, keepdims=True))     # [n_r, L, 1]
out  = sum(w_r * o_r, axis=0) @ w_o             # [L, d_model]

Now count the exact operations for one head at sequence length and chunk size . There are chunks per round, and each chunk computes an score matrix, so one round evaluates dot products, linear in for a fixed chunk size (at 65,536 tokens, chunk size 64, and 8 rounds, that is 8 × 128 × 65,536 ≈ 67.1M scores per head, 64 times fewer than full attention's 4.29 billion). Sorting the hash codes per round adds integer comparisons, giving the headline complexity. (Paper Tables 1 and 3 contain three arithmetic typos in their summary formulas; the Provenance panel below documents each one.)

Reversible Transformer layers

With attention reduced from to , Figure 1 showed that activation memory across layers becomes the next wall. A standard residual layer adding to (as in ResNet and the original Transformer) is not invertible: knowing the output does not tell you , because depended on itself. Backpropagation therefore saves at every layer, costing memory. Gradient checkpointing reduces that to by saving one activation every layers and re-running the forward pass in between.

Reformer adopts reversible residual networks (RevNets; Gomez et al., 2017) to drop depth memory all the way to . Instead of one activation stream , a reversible block carries a pair of streams and updates each stream using only the other stream:

(8)

Because takes (which is already part of the block's output) and takes (which we get right after undoing ), the block inverts exactly by subtraction, for any functions and (they do not need to be invertible themselves):

(9)

To build a Reversible Transformer, Reformer sets to the attention sub-layer and to the feed-forward sub-layer, moving Layer Normalization inside both residual branches (pre-LN) so the outer skip paths remain pure additions:

(10)

Original RevNets for images split the channel dimension in half so each stream had width . Reformer instead duplicates the embedded input tensor into two full-width streams , each of shape (tl.Dup() in reformer.py), so and keep the exact same weight shapes and parameter count as a standard Transformer. Duplicating the stream costs 2 activation copies instead of 1 for a single-layer model, so memory shrinks as soon as depth reaches 3 layers (an 8× reduction in residual memory at 16 layers). At the end of the stack, Trax concatenates to width before the final LayerNorm and vocabulary projection.

Follow one numerical example through Layer 1 of Figure 4. Starting from duplicated input (2.00, 2.00), suppose is 0.38 and is −0.04. The forward pass computes = 2.00 + 0.38 = 2.38 and = 2.00 − 0.04 = 1.96, passes (2.38, 1.96) to Layer 2, and immediately frees (2.00, 2.00) from memory. Later, when backpropagation arrives back at Layer 1 holding (2.38, 1.96), evaluating simultaneously yields −0.04 to recover = 1.96 − (−0.04) = 2.00 and builds the local autodiff graph needed to compute the gradients for 's weights and in one pass. The same step on recovers = 2.38 − 0.38 = 2.00 and computes the attention gradients. Press Play or scrub Figure 4 across all four layers to compare the RAM occupancy of Standard vs Reversible stacks.

Figure 4 · reversible forward and backward trace
bwd layer 4
4-layer forward pass (steps 1 to 4) followed by backward pass (steps 5 to 8). Switch between Reversible (Reformer) and Standard Transformer, press Play, or scrub the slider to watch reverse subtraction rebuild each layer's inputs from RAM holding only one active layer pair.

The compute price of constant depth memory is one extra evaluation of and per layer during the backward pass. Since standard training spends roughly 1 unit of compute on the forward pass and 2 on the backward pass, recomputing adds about 1 unit, raising total training FLOPs by roughly 33% (similar to full per-layer checkpointing, without saving any layer checkpoints).

Two practical details in the official Trax codebase (trax/layers/reversible.py, lines 262–269) make reversible Transformers work reliably in training. First, any stochastic layer inside or (such as dropout) receives a deterministic per-layer PRNG key split from the step's seed, so recomputation generates the exact same dropout mask as the forward pass. Second, floating-point subtraction can introduce tiny rounding drift; for smooth layers that drift is harmless, but LSH's argmax hash is discontinuous and a rounding error could flip a token into a different bucket. Trax therefore saves the integer bucket IDs (shape , a few megabytes) from the forward pass and reuses them during reverse backpropagation.

# One reversible Transformer block, forward (10) and reverse_and_grad (9)
# X1, X2: [B, L, d_model] (at layer 0, X1 = X2 = embed(tokens))
def forward_block(X1, X2, weights, rng_attn, rng_ff):
    # (10): LayerNorm sits inside both F (Attn) and G (FFN)
    Y1, buckets = X1 + Attn(LayerNorm(X2), weights.attn, rng_attn)
    Y2          = X2 + ChunkedFFN(LayerNorm(Y1), weights.ff, rng_ff)
    return Y1, Y2, buckets                      # only tiny int buckets kept

def backward_block(Y1, Y2, dY1, dY2, weights, buckets, rng_attn, rng_ff):
    # (9): recover X2 by subtracting G(Y1) using identical RNG key
    g_out, vjp_g = vjp(lambda y: ChunkedFFN(LayerNorm(y), weights.ff, rng_ff), Y1)
    X2 = Y2 - g_out                             # [B, L, d_model]
    dY1_from_g, dW_ff = vjp_g(dY2)
    dY1_total = dY1 + dY1_from_g

    # (9): recover X1 by subtracting F(X2) reusing saved LSH buckets
    f_out, vjp_f = vjp(lambda x: Attn(LayerNorm(x), weights.attn, rng_attn,
                                      buckets=buckets), X2)
    X1 = Y1 - f_out                             # [B, L, d_model]
    dX2_from_f, dW_attn = vjp_f(dY1_total)
    return X1, X2, dY1_total, dY2 + dX2_from_f, (dW_attn, dW_ff)

Chunked feed-forward layers and weight swapping

Reversible layers eliminate the factor, leaving only one layer's activations live at a time. Even inside a single layer, however, the feed-forward network projects every token from width 1024 up to 4096, quadrupling peak activation memory (at 65,536 tokens and batch size 8, one single layer's FFN hidden tensor is 8 × 65,536 × 4096 × 4 bytes, or 8 GB).

Unlike attention, a Transformer's feed-forward sub-layer acts identically and independently on every token position: token 100 never interacts with token 101 inside . Reformer splits the sequence dimension into chunks and runs the feed-forward layer (forward, reverse, and backward) one chunk at a time:

(11)

Choosing at least (for example 16 chunks of 4,096 tokens on a 64K sequence) keeps the peak FFN activation smaller than the residual tensor. Unlike LSH attention or reversible layers, chunking is not an approximation or an architectural change: it computes the exact same mathematical function as the unchunked layer. For models with large vocabularies (), Reformer applies the same sequence chunking to the final vocabulary log-probabilities and cross-entropy loss. (For long sequences, Trax's ReformerLM also replaces a flat learned position table with axial positional encodings, factorizing length 65,536 as 256 × 256 so two tiny tables concatenated along the channel axis take 1 MB instead of 256 MB.)

Shrinking activations exposes one last memory consumer: the layer weights themselves, which still grow linearly with depth . Because Reformer can now process much larger total token counts per accelerator step, each layer performs far more arithmetic per weight loaded, which allows swapping inactive layers' weights between accelerator memory and host CPU RAM while overlapping the transfer with compute.

Experiments and limits

The authors test Reformer across four benchmarks, isolating each component before combining them:

Figure 5 plots both the speed crossover from Paper Figure 5 (right) and the exact duplication-task matrix from Paper Table 2. In Speed view, look at the left edge at length 1,024 (batch 32, total 32,768 tokens/step): 8-hash LSH takes ~0.32 seconds/step, nearly twice as slow as full attention (~0.17 s/step). Sorting, gathering, and running 8 hash rounds carry real fixed overhead. The two curves cross at length 2,048; by length 32,768, full attention climbs to ~3.55 s/step while 8-hash LSH stays near ~0.45 s/step, about an 8× speedup. Switch to the Duplication Task tab and click Train LSH-1 to see both the 99.9% eval-time LSH-8 jump and the 0.8% collapse when evaluated under standard full attention.

Figure 5 · speed crossover and hash-round accuracy
32K/1L = 32K
Speed vs length (Paper Fig. 5, fixed 32,768 tokens/step): full attention grows steeply while 8-hash LSH stays nearly flat past the length-2048 crossover. Duplication task (Paper Table 2): pick a training setting to compare accuracy across eval rounds.

Reformer's limitations explain why modern long-context language models took a different engineering path two years later. Hashing is approximate: when many queries cluster into one bucket exceeding tokens, valid keys overflow the one-chunk lookback, and closing the quality gap to full attention requires 8 rounds, which pushes the wall-clock break-even length into the thousands of tokens. Subsequent systems separated the memory problem from the compute problem: FlashAttention eliminated attention memory with zero approximation by tiling softmax in fast on-chip static RAM (SRAM, the GPU's small scratchpad memory), while selective activation recomputation paired with long-context caching and multi-query attention cut memory without reversible layers' floating-point drift or architecture changes.

Provenance Verified against primary literatureHow we verify
Vaswani et al. (2017)Scaled dot-product and multi-head self-attention (Eq. 1), the Transformer architecture, and the WMT 2014 En-De baselines (27.3 base, 28.4 big BLEU).
Andoni et al. (2015)Practical and optimal cross-polytope angular LSH: random rotation followed by argmax over signed coordinates, partitioning the sphere into b angular cones.
Gomez et al. (2017)Reversible residual networks (RevNets): additive coupling equations and exact input reconstruction by subtraction for O(1) activation memory in depth.
Ba et al. (2016) & Shazeer & Stern (2018)Layer Normalization (moved inside each reversible residual block) and the Adafactor optimizer used in Reformer ablations.
Kitaev, Kaiser & Levskaya (2020)Reformer (ICLR 2020; arXiv:2001.04451v2): shared-QK LSH attention, sort-and-chunk batching, reversible Transformer layers, chunked FFN, and experiments on synthetic copy, enwik8-64K, ImageNet-64, and WMT14.
google/trax (official code)Verified implementation details in trax/models/reformer/reformer.py (lines 104-135, 197-208: axial positions, tl.Dup, tl.Concatenate), trax/layers/reversible.py (lines 262-269: saved LSH buckets for reverse stability), and trax/layers/research/efficient_attention.py (lines 54-269, 1889-1997).
correctionTwo sets of discrepancies verified against arXiv:2001.04451v2 and the official Trax code. First, the paper's complexity tables contain three slips: Table 1 prints Memory-Efficient Attention memory as max(b n_h l d_k, b n_h l^2) even though the prose above it states it is linear in l; Table 1 and Table 3 write LSH chunk attention as l(4l/n_c)^2 instead of n_c * 2(l/n_c)^2 = 2 l^2 / n_c (multiplying by l instead of n_c inflates the factor by l/n_c); and Table 3 includes a stray head count n_h in the feed-forward time term b n_h l d_ff for Reversible and Chunked Reversible Transformers. Second, Appendix A (Eq. 12-16) defines cross-bucket masking and a multi-round deduplication penalty -log N_{i,j}, whereas the authors' official Trax LSHSelfAttention (trax/layers/research/efficient_attention.py, lines 145-160 and 1962-1992) omits both, attending across the full chunk-plus-one-back window and combining rounds directly via logsumexp.

Questions you might still have

?

If Reformer cuts attention to O(L log L), why do modern LLMs use FlashAttention instead?
Two reasons. First, FlashAttention removes the O(L^2) memory wall while keeping exact dense attention, with no hash misses, no sorting overhead, and no shared-QK constraint. Second, on modern GPUs dense matrix multiplications are so much faster than gather/sort/scatter operations that 8-round LSH is slower than dense attention up to several thousand tokens, and only pulls ahead on very long sequences. The FlashAttention explainer covers how tiling attention in on-chip SRAM achieves exact O(L) memory.

?

Why do LSH-trained models score 0.8% (chance) when evaluated with standard Full Attention in Table 2?
The synthetic vocabulary has 127 non-zero symbols, so random guessing scores 1/127 = 0.79%, which rounds to 0.8%. LSH attention trains with shared-QK and self-exclusion masking (subtracting 10^5 on the diagonal) because q_i . (q_i / ||q_i||) = ||q_i|| beats every other key. Evaluating those weights with standard full attention allows self-attention (or attends over unbucketed keys the model never saw), so every position copies itself instead of looking 512 tokens back. In the paper's LaTeX source, a commented-out table row notes that 1,000 steps of full-attention fine-tuning restores accuracy to 100%.

?

How does LSH attention work during autoregressive token-by-token generation?
Sorting the entire sequence from scratch on every generated token would be wasteful. In Trax's incremental decode path (trax/layers/research/efficient_attention.py, lines 2033-2109), the decoder caches each past token's integer bucket IDs across all n_r rounds. When a new token arrives, it hashes only the new query vector, finds past positions that share any bucket across the n_r rounds, gathers a fixed-size buffer of matching keys and values, and runs standard attention over that buffer.

?

Does subtracting residuals backward across 20 reversible layers accumulate floating-point error?
Yes, slightly, because floating-point addition and subtraction are not exact: (x + f) - f can differ from x in the least significant bits, especially in 16-bit precision. For smooth functions that small drift barely affects gradients, as Gomez et al. (2017) verified for RevNets. For LSH attention, however, argmax over hash projections is discontinuous, so a tiny drift can flip a token into a different bucket and break the backward pass. Trax avoids this by saving the small integer bucket IDs from the forward pass and reusing them during reverse recomputation.

?

Why did the authors skip LSH attention on WMT 2014 English-German translation?
Every sentence in the WMT14 test set is shorter than 128 tokens, which is already the default chunk length m in Trax's LSH attention. When L <= m, there is only one chunk, so hashing, sorting, and chunking cannot skip any pairs and only add overhead. The WMT experiment therefore tests reversible layers alone on an encoder-decoder Transformer.

?

Why not use fixed local sliding-window attention instead of LSH?
A local window of width w also runs in O(w L) time and memory, and works well for nearby syntax. It fails completely whenever a token must retrieve information farther back than w in a single layer, as in the paper's 1,024-token duplication task where the matching symbol always sits 512 positions earlier. Angular LSH groups tokens by vector similarity regardless of distance, so a query at position 900 can land in the same bucket as a key at position 388 in one layer.

Footnotes & further reading

  1. The paper: Kitaev, Kaiser & Levskaya, Reformer: The Efficient Transformer (ICLR 2020; arXiv:2001.04451v2, February 2020).
  2. Official reference implementation in Google Trax: trax/models/reformer, efficient_attention.py, and reversible.py.
  3. Cross-polytope angular LSH: Andoni, Indyk, Laarhoven, Razenshteyn & Schmidt, Practical and Optimal LSH for Angular Distance (NeurIPS 2015).
  4. Reversible residual networks: Gomez, Ren, Urtasun & Grosse, The Reversible Residual Network: Backpropagation Without Storing Activations (NeurIPS 2017). Compare with Gradient Checkpointing and Reducing Activation Recomputation.
  5. Baseline Transformer and optimizer: Vaswani et al., Attention Is All You Need (NeurIPS 2017); Ba, Kiros & Hinton, Layer Normalization (2016); Shazeer & Stern, Adafactor: Adaptive Learning Rates with Sublinear Memory Cost (ICML 2018).
  6. Later exact memory-efficient attention: Dao et al., FlashAttention (NeurIPS 2022) and FlashAttention-2 (2023).