AI Logic

Attention Mechanisms

Reformer (LSH attention)

Updated:

LSH attention in Reformer. The left side shows the computation: a shared linear layer produces Q = K, tokens are hashed into buckets, sorted by bucket, split into chunks of m, attend within their chunk and to the previous chunk, and are restored to the original order. The right side shows an example of 16 tokens sorted into the order of 4 buckets and the attention matrix in sorted order (only pairs in the same bucket are computed and used).

What is Reformer?

Reformer is a Transformer that runs fast and with little memory even on long sequences by gathering similar queries and keys into the same "bucket" with locality-sensitive hashing (LSH) and computing attention only within each bucket. Kitaev et al. at Google Research and UC Berkeley proposed it in 2020 in the paper "Reformer: The Efficient Transformer" (ICLR 2020).

Standard multi-head attention computes weights for every pair of tokens in a sequence of length LL, so its computation and memory grow in proportion to L2L^2. In the paper's example, QK⊤QK^\top for a sequence of length 64K takes 16 GB in 32-bit floats even with a batch size of 1.

Reformer starts from the property that the result of a softmax is dominated by its largest values. What matters for each query is only the few keys with large dot products (similar directions), so if those nearby keys can be found quickly, the remaining pairs need not be computed. Hashing takes on this job of "finding what is close."

Besides attention, Reformer combines two more techniques for reducing memory.

TechniqueWhat it reduces
LSH attentionTurns the O(L2)O(L^2) of attention into O(Llog⁡L)O(L \log L)
Reversible residual layersActivations stored per layer for backpropagation shrink to one copy for the whole model (the factor of the number of layers nln_l disappears)
Chunking the feed-forward layersActivations of the intermediate width dffd_{ff} are computed a piece at a time by splitting the sequence

As a library analogy: instead of comparing every book with every other book one by one, books with similar content are shelved together, and only books on the same shelf are compared.

The right side of the figure at the top of the article shows the essence of LSH attention. When tokens are sorted by bucket and split into chunks of fixed length, pairs in the same bucket gather near the diagonal. Only that region is computed.

Theory: the steps of LSH attention

Reformer's LSH attention is computed in the following steps (Section 2 and Figure 2 of the paper).

  1. Build Q and K from the same linear layer (shared-QK): QQ and KK are produced from the input by the same linear layer, and the keys are normalized to kj=qj/∥qj∥k_j = q_j / \lVert q_j \rVert. Because queries and keys live in the same space, h(qj)=h(kj)h(q_j) = h(k_j), so each bucket holds equal numbers of queries and keys. VV is produced by a separate linear layer.
  2. Split into buckets by hashing: To make bb buckets, fix one random matrix RR of size dk×b/2d_k \times b/2 and determine the bucket number with the equation below. Vectors with similar directions are more likely to get the same number (angular LSH; Andoni et al., 2015).
  3. Sort: Tokens are sorted by bucket number, and by position within each bucket (VV is sorted in the same order). Pairs in the same bucket gather near the diagonal of the sorted matrix.
  4. Split into chunks: The sorted sequence is divided into chunks of mm tokens each. The paper uses m=2L/nbucketsm = 2L / n_{\text{buckets}} (twice the average bucket size).
  5. Attend within the chunk and to the previous chunk: Each query takes dot products only with keys in its own chunk and the chunk before it, and among those, keys from other buckets are masked.
  6. Restore the original order: The outputs are put back in the original positional order.

The hash in step 2 is the following equation, where [u;v][u; v] denotes the concatenation of vectors.

h(x)=arg⁡max⁡([ xR ; −xR ])h(x) = \arg\max\bigl([\,xR\,;\,-xR\,]\bigr)

Standard attention written for a single query position ii is the following equation (Eq. (2) in the paper; zz is the softmax denominator, and the division by dk\sqrt{d_k} is omitted). Pi\mathcal{P}_i is the set of positions that position ii can attend to.

oi=∑j∈Piexp⁡(qi⋅kj−z(i,Pi)) vjo_i = \sum_{j \in \mathcal{P}_i} \exp\bigl(q_i \cdot k_j - z(i, \mathcal{P}_i)\bigr)\, v_j

LSH attention restricts Pi\mathcal{P}_i to only the positions in the same bucket (Eq. (4)). The chunking in steps 4–5 corresponds to computing over the range P~i\tilde{\mathcal{P}}_i of Eq. (5), where sis_i is the sorted position.

Pi={ j:h(qi)=h(kj) },P~i={ j:⌊sim⌋−1≤⌊sjm⌋≤⌊sim⌋ }\mathcal{P}_i = \{\, j : h(q_i) = h(k_j) \,\}, \qquad \tilde{\mathcal{P}}_i = \Bigl\{\, j : \Bigl\lfloor \frac{s_i}{m} \Bigr\rfloor - 1 \le \Bigl\lfloor \frac{s_j}{m} \Bigr\rfloor \le \Bigl\lfloor \frac{s_i}{m} \Bigr\rfloor \,\Bigr\}

Multi-round hashing: Hashing leaves some probability that nearby tokens happen to land in different buckets. Reformer therefore prepares nroundsn_{\text{rounds}} hash functions, computes them in parallel, and takes the union Pi=⋃rPi(r)\mathcal{P}_i = \bigcup_r \mathcal{P}_i^{(r)} as the set of positions to attend to (Eq. (6)). The output of each round is weighted by its own softmax denominator and summed (Appendix A of the paper).

Causal masking: In a generative model (decoder), each token keeps its original position index through sorting, and future positions are masked by comparing indices. In addition, since a shared Q and K make a token's dot product with itself almost always the largest, attention to itself is masked (except for cases such as the first token, which has no other position to attend to).

Reducing memory with reversible layers and chunking

LSH attention removes only the L2L^2 term of attention; memory proportional to the number of layers and to the width of the feed-forward layers remains. The paper reduces it with two techniques (Section 3 of the paper).

Reversible residual layers: In an ordinary residual layer y=x+F(x)y = x + F(x), each layer's input must be stored for backpropagation, so memory grows in proportion to the number of layers nln_l. Reformer adopts the idea of RevNet (Gomez et al., 2017), a reversible version of ResNet: it splits the activations into two parts (x1,x2)(x_1, x_2) and, with attention as FF and the feed-forward layer as GG, computes the following (Eq. (9)). Layer normalization is placed inside the residual blocks.

Y1=X1+Attention(X2),Y2=X2+FeedForward(Y1)Y_1 = X_1 + \mathrm{Attention}(X_2), \qquad Y_2 = X_2 + \mathrm{FeedForward}(Y_1)

In this form, the inputs can be recomputed from the outputs by subtraction (Eq. (8)).

X2=Y2−FeedForward(Y1),X1=Y1−Attention(X2)X_2 = Y_2 - \mathrm{FeedForward}(Y_1), \qquad X_1 = Y_1 - \mathrm{Attention}(X_2)

During backpropagation, the gradients are computed while recomputing the inputs layer by layer from the top, so the activations of each layer need not be stored. Both x1x_1 and x2x_2 have width dmodeld_{\text{model}}, keeping the number of parameters the same as in a standard Transformer.

Chunking the feed-forward layers: Feed-forward layers compute each position independently, so splitting the sequence into cc chunks and processing them one at a time gives the same result (Eq. (10)). Activations of the intermediate width dffd_{ff} (which can be 4K or more) never need to be held all at once. When the vocabulary is large, the output log-probabilities and the loss are also computed one section of the sequence at a time.

Table 3 in the paper summarizes the memory used as each technique is added, as follows (bb is the batch size, nhn_h the number of heads, nrn_r the number of hash rounds; c=1282c = 128^2 denotes the constant when the number of chunks is L/32L/32).

ModelMemory use
Transformermax⁡(bLdff, bnhL2) nl\max(b L d_{ff},\ b n_h L^2)\, n_l
Reversible Transformermax⁡(bLdff, bnhL2)\max(b L d_{ff},\ b n_h L^2)
Chunked reversible Transformermax⁡(bLdmodel, bnhL2)\max(b L d_{\text{model}},\ b n_h L^2)
LSH Transformermax⁡(bLdff, bnhLnrc) nl\max(b L d_{ff},\ b n_h L n_r c)\, n_l
Reformermax⁡(bLdmodel, bnhLnrc)\max(b L d_{\text{model}},\ b n_h L n_r c)

In Reformer, the L2L^2 term, the factor of the number of layers nln_l, and dffd_{ff} have all disappeared.

Like gradient checkpointing, reversible layers "recompute instead of storing," but they differ in not even storing the inputs needed for recomputation. In exchange, backpropagation spends time recomputing each layer's forward pass.

Why attending within a bucket is enough

LSH attention gets by with only a few pairs because the following two facts hold.

  • A softmax is decided by its large values: After taking exp⁡\exp, keys with large dot products receive overwhelmingly large weights, and keys with small dot products receive weights close to 0. In the paper's example, even at length 64K, each query needs to look at only its nearest 32–64 keys.
  • Hashing puts nearby vectors in the same bucket: Points on the sphere are projected with a random rotation RR, and the bucket is decided by which axis direction they are closest to, so vectors with similar directions land in the same bucket with high probability and vectors with distant directions land in different buckets (Figure 1 in the paper). Because the key lengths are normalized by ∥qj∥\lVert q_j \rVert, the size of a dot product is decided by closeness in direction.

As for cost, if the chunk length is constant, the number of keys each query looks at does not depend on the sequence length. In Table 1 of the paper, the time for LSH attention is max⁡(bnhLdk, bnhnrL(4L/nc)2)\max(b n_h L d_k,\ b n_h n_r L (4L/n_c)^2) (ncn_c is the number of chunks). Including the O(Llog⁡L)O(L \log L) of sorting, the total is O(Llog⁡L)O(L \log L).

Whether shared-QK hurts performance was checked experimentally in the paper. On the learning curves for enwik8 and imagenet64, the model with shared Q and K was no worse than standard attention, and on enwik8 it even trained slightly faster (Figure 3, left, in the paper).

Experimental results

Number of hashes on a copy task: On a task of predicting the second half of a length-1,024 sequence 0w0w0w0w, formed by repeating a symbol sequence ww (length 511) twice, the accuracy of a one-layer Transformer (dmodel=dff=256d_{\text{model}} = d_{ff} = 256, 4 heads) was compared (Table 2 in the paper). Because this task requires referring to distant positions, sparse attention, which looks only at fixed ranges, cannot solve it.

Trained with ↓ / evaluated with →StandardLSH-8LSH-4LSH-2LSH-1
Standard attention100%94.8%92.5%76.9%52.5%
LSH-40.8%100%99.9%99.4%91.9%
LSH-20.8%100%99.9%98.1%86.8%
LSH-10.8%99.9%99.6%94.8%77.9%

(LSH-nn means nn rounds of hashing.) More hash rounds give higher accuracy, and even the model trained with 1 round reached 99.9% when evaluated with 8 rounds. In other words, the number of hashes can be increased even after training. The paper also shows that with nrounds=8n_{\text{rounds}} = 8 on imagenet64, performance is nearly the same as standard attention (Figure 4).

Speed: When the sequence was made longer while keeping the total number of tokens constant, standard attention became slower while the speed of LSH attention stayed almost the same (Figure 5, right, in the paper).

Reversible layers in machine translation: On WMT 2014 English–German translation, the BLEU of Transformers with reversible encoders and decoders was as follows (newstest2014; Table 4 in the paper). The sentences in this experiment are shorter than 128 tokens, so LSH attention was not used.

ModelBLEU
Vaswani et al. (2017) base27.3
Vaswani et al. (2017) big28.4
Reversible Transformer (base, 100K steps)27.6
Reversible Transformer (base, 500K steps, no weight sharing)28.0
Reversible Transformer (big, 300K steps, no weight sharing)29.1

Large models: On enwik8 with length 64K, Reformers of up to 20 layers could be trained within the memory of a single device. The Transformer used for comparison was too slow and did not fit in memory, so it could not be trained. A 12-layer Reformer reached 1.19 bits/character on the test data (20K training steps), and 1.05 bits/character after further tuning and longer training.

Comparison with other methods under the same conditions: On Long-Range Arena, a benchmark for long sequences, the FlashAttention paper compared the methods under the same conditions; Reformer's average accuracy over the five tasks was 57.6%, lower than the standard Transformer (59.3%), and its speed was 1.3× that of the standard implementation (Table 3 in the FlashAttention paper).

Practical considerations

Reformer is an approximation that shares Q and K and computes only nearby pairs. The weights of a standard Transformer cannot necessarily be reused as is.

LSH attention assumes that Q and K come from the same linear layer (shared-QK). Applying LSH attention as is to a model trained with standard attention dropped accuracy even on the copy task to 52.5% (1 round) to 94.8% (8 rounds) (Table 2 in the paper). If LSH attention is to be used, the model should basically be trained with LSH attention from the start.

Keep the following points in mind when using it.

  • No gain on short sequences: The paper's standard setting computes attention in chunks of 128 tokens after sorting. If the sequence is shorter than a chunk, the computation is the same as standard attention. The paper itself did not use LSH attention for translating sentences shorter than 128 tokens.
  • Use the number of hashes to trade accuracy for compute: Compute grows in proportion to the number of rounds nroundsn_{\text{rounds}}. In the paper, 8 rounds gave performance nearly equal to standard attention. The number can also be increased only at evaluation time.
  • Bucket sizes can be uneven: The chunk length is set to twice the average bucket size on the assumption that buckets rarely become too large. If many tokens gather in one bucket, partners that spill outside the chunk can no longer be seen.
  • Reversible layers trade time for memory: Instead of storing activations, backpropagation recomputes the forward pass.

Comparison with other methods

Methods that make attention cheaper for long sequences are compared below by "which part of the attention matrix they compute."

MethodWhich part of the N×NN \times N matrix is computedResultComplexity (in sequence length NN)
Multi-head attentionAll pairsExactO(N2)O(N^2)
Sparse attention, Longformer, BigBirdOnly some pairs, in a pattern fixed by positionSome pairs are skippedO(NN)O(N\sqrt{N}) to O(N)O(N)
Reformer (Kitaev et al., 2020)Only pairs chosen by content (pairs in the same bucket)Some pairs are skipped (approximate)O(Nlog⁡N)O(N \log N)
Linformer (Wang et al., 2020)Shrinks the matrix to N×kN \times kApproximateO(Nk)O(Nk)
Performer (Choromanski et al., 2020)Never builds the matrix (softmax approximated with random features)ApproximateO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs, without keeping the whole matrix in memoryExact (same values)O(N2)O(N^2) compute, O(N)O(N) extra memory

Whereas sparse attention and similar methods decide which pairs to look at by position, Reformer decides by content (the direction of the vectors). As a result, it can attend to positions far away as long as their content is similar. This property is why it can solve problems such as the copy task, which require referring to distant positions.

As a rough guide to choosing among them:

  • Training on very long sequences (tens of thousands of tokens) with limited memory: Reformer, which combines LSH attention with reversible layers, is a candidate.
  • Not wanting to sacrifice exactness, or sequences that are not that long: The first choice is to compute standard attention with FlashAttention.
  • Reducing only memory: Reversible layers and feed-forward chunking can be used independently of LSH attention.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F


def lsh_hash(x, n_buckets, n_rounds=1):
    """Angular LSH (Section 2 of the paper): h(x) = argmax([xR; -xR]). x: [L, d] -> [n_rounds, L]"""
    R = torch.randn(n_rounds, x.shape[-1], n_buckets // 2, device=x.device)
    xr = torch.einsum("ld,rdb->rlb", x, R)
    return torch.cat([xr, -xr], dim=-1).argmax(dim=-1)


def lsh_attention(qk, v, n_buckets=8, causal=False):
    """LSH attention with 1 round and 1 head (a small implementation for checking the mechanism).
    qk: [L, d] (Q and K shared), v: [L, d]. L must be a multiple of n_buckets"""
    L, d = qk.shape
    m = 2 * L // n_buckets                         # chunk length m = 2L / n_buckets
    buckets = lsh_hash(qk, n_buckets)[0]           # [L]
    pos = torch.arange(L)
    order = torch.argsort(buckets * L + pos)       # by bucket, then by position within a bucket
    q, b, p, vv = qk[order], buckets[order], pos[order], v[order]
    k = F.normalize(q, dim=-1)                     # k_j = q_j / ||q_j||
    out = torch.empty_like(vv)
    for c in range(0, L, m):                       # per chunk
        lo = max(0, c - m)                         # from the previous chunk
        s = q[c:c + m] @ k[lo:c + m].T / d ** 0.5
        mask = b[c:c + m, None] != b[None, lo:c + m]          # mask other buckets
        if causal:
            mask |= p[c:c + m, None] < p[None, lo:c + m]      # mask future positions
        self_mask = p[c:c + m, None] == p[None, lo:c + m]     # also mask self
        s = s.masked_fill(mask, float("-inf"))
        s_no_self = s.masked_fill(self_mask, float("-inf"))
        only_self = torch.isinf(s_no_self).all(dim=-1, keepdim=True)  # rows with no other partner
        s = torch.where(only_self, s, s_no_self)   # allow self only in those rows
        out[c:c + m] = torch.softmax(s, dim=-1) @ vv[lo:c + m]
    return out[torch.argsort(order)]               # restore the original order


x = torch.randn(64, 32)
to_qk, to_v = nn.Linear(32, 32), nn.Linear(32, 32)  # Q and K share one linear layer (shared-QK)
y = lsh_attention(to_qk(x), to_v(x), n_buckets=8, causal=True)
print(y.shape)  # torch.Size([64, 32])

# Hugging Face Transformers also has a Reformer implementation (transformers.ReformerModel).
# Increasing num_hashes (number of hash rounds) in the config at inference makes the approximation more accurate.

FAQ

Q. How many hash rounds $n_{\text{rounds}}$ should be used?
A.

More rounds give higher accuracy, and compute grows in proportion to the number of rounds. In the paper, 8 rounds on imagenet64 gave performance nearly equal to standard attention. On the copy task, even a model trained with 1 round improved from 77.9% to 99.9% accuracy when evaluated with 8 rounds. It is also possible to train with few rounds and increase them at evaluation time.

Q. Doesn't making Q and K the same hurt performance?
A.

In the paper's experiments on enwik8 and imagenet64, the model with shared Q and K (and normalized key lengths) was no worse than standard attention. However, because a token's dot product with itself is almost always the largest, attention to itself is masked.

Q. Can reversible layers be used on their own?
A.

Yes. Reversible layers are independent of LSH attention. In the paper's machine translation experiments, only reversible layers were used without LSH attention, and the base setting reached BLEU 27.6–28.0, comparable to the standard Transformer (27.3). In exchange, backpropagation spends time recomputing the forward pass.

References

  1. N. Kitaev, Ł. Kaiser, and A. Levskaya, "Reformer: The Efficient Transformer," ICLR, 2020.
  2. A. N. Gomez, M. Ren, R. Urtasun, and R. B. Grosse, "The Reversible Residual Network: Backpropagation Without Storing Activations," NIPS, 2017.
  3. A. Andoni, P. Indyk, T. Laarhoven, I. Razenshteyn, and L. Schmidt, "Practical and Optimal LSH for Angular Distance," arXiv:1509.02897, 2015.
  4. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.