AI Logic

Attention Mechanisms

Linformer

Updated:

Structure of Linformer. The left shows the computation flow (K and V are compressed from N to k by projections E and F, and attention with Q produces N × k weights). The right shows the attention matrix: only an N × k matrix is formed instead of the usual N × N, along with the projection that compresses the keys to k

What is Linformer

Linformer is a method that compresses keys and values along the sequence axis from NN to kk, shrinking the attention weight matrix from N×NN \times N to N×kN \times k. Wang et al. at Facebook AI proposed it in 2020 in the paper "Linformer: Self-Attention with Linear Complexity."

Standard multi-head attention computes weights for every pair of tokens, so computation and memory grow with the square of the sequence length NN. Linformer starts from the observation that the attention weight matrix of a trained model can in fact be represented almost entirely with little information (it is low-rank).

It therefore adds two learnable matrices E,FE, F (of size k×Nk \times N) to each head, compresses keys and values into kk "representatives," and then computes standard scaled dot-product attention. If kk is fixed much smaller than NN, computation and memory are O(Nk)O(Nk), that is, linear in NN.

In meeting terms, instead of listening to every one of the NN participants one by one, their remarks are summarized into kk memo sheets, and anyone with a question looks only at the memos. What goes into which memo is determined by learning.

The right side of the figure at the top of the article shows this difference. Standard attention forms an N×NN \times N matrix, whereas Linformer forms only an N×kN \times k matrix.

Theory

The ii-th head of standard attention is given by the following formula (Eq. (2) of the paper). Q,K,VQ, K, V are N×dmN \times d_m inputs, and WiQ,WiK,WiVW_i^Q, W_i^K, W_i^V are learned weights.

headi=softmax ⁣(QWiQ(KWiK)⊤dk)⏟P : N×NVWiV\mathrm{head}_i = \underbrace{\mathrm{softmax}\!\left(\frac{QW_i^Q (KW_i^K)^\top}{\sqrt{d_k}}\right)}_{P\,:\,N \times N} VW_i^V

The paper calls this PP the "context mapping matrix." Forming PP requires multiplying N×dN \times d matrices, so computation and memory are O(N2)O(N^2).

Linformer computes as follows.

  1. Produce Q, K, V: as usual, produce QWiQQW_i^Q, KWiKKW_i^K, and VWiVVW_i^V (all N×dN \times d).
  2. Compress keys to kk: multiply by the projection matrix EiE_i to get EiKWiKE_i KW_i^K (k×dk \times d). EiE_i mixes the NN rows along the sequence axis to produce kk rows.
  3. Compress values to kk as well: likewise, get FiVWiVF_i VW_i^V (k×dk \times d).
  4. Compute the reduced attention: compute the output with the following formula (Eq. (7) of the paper). The weight matrix Pˉ\bar{P} is N×kN \times k.
headi=softmax ⁣(QWiQ(EiKWiK)⊤dk)⏟Pˉ : N×k⋅FiVWiV⏟k×d\mathrm{head}_i = \underbrace{\mathrm{softmax}\!\left(\frac{QW_i^Q (E_i KW_i^K)^\top}{\sqrt{d_k}}\right)}_{\bar{P}\,:\,N \times k} \cdot \underbrace{F_i VW_i^V}_{k \times d}

The softmax is taken over each row of Pˉ\bar{P} (kk values), so each query's weights still sum to 1. Computation and memory are O(Nk)O(Nk), a large reduction when k≪Nk \ll N.

There are three ways to hold the projection matrices Ei,FiE_i, F_i, depending on the degree of sharing (Section 4 of the paper). For a model with 12 layers and 12 heads, the number of projection matrices is as follows.

Sharing schemeDescriptionNumber of projection matrices (12 layers, 12 heads)
Headwise sharingOne pair E,FE, F per layer, used by all heads24
Key-value sharingAdditionally set Ei=Fi=EE_i = F_i = E12
Layerwise sharingOne EE for all layers, heads, keys, and values1

Why compressing to k barely hurts performance

The paper shows both experimentally and theoretically that the attention weight matrix PP is low-rank.

Experiment: using pretrained RoBERTa (base and large), the PP matrices for sentences from WikiText-103 and IMDB were decomposed by singular value decomposition, and the cumulative share of singular values summed from largest to smallest was examined (Figure 1 of the paper). For every layer, head, and task, the singular value distribution had a long tail, showing that most of the information in PP can be recovered from the first few large singular values. Comparing the share of the top 128 out of length 512 per layer and head, higher layers tended to be more skewed and lower in rank.

Theory: Theorem 1 of the paper uses the Johnson–Lindenstrauss lemma, which states that distances are approximately preserved even when dimensionality is reduced by a random projection, to show that there is a matrix of rank Θ(log⁡N)\Theta(\log N) that approximates PP within error ϵ\epsilon. Theorem 2 further uses the fact that the rank of QK⊤QK^\top inside PP is at most dd to show that, with the projection dimension chosen as follows, Eq. (7) gives an approximation within error ϵ\epsilon.

k=min⁡{Θ ⁣(9dlog⁡dϵ2),  5 Θ ⁣(log⁡Nϵ2)}k = \min\left\{\Theta\!\left(\frac{9d\log d}{\epsilon^2}\right),\; 5\,\Theta\!\left(\frac{\log N}{\epsilon^2}\right)\right\}

The first term does not depend on the sequence length NN, so Linformer's claim is that the approximation holds with kk fixed even as NN grows.

Directly approximating PP at rank kk with singular value decomposition would also give O(Nk)O(Nk) complexity, but performing an SVD for every attention call is far too expensive. Instead of decomposing, Linformer simply adds learnable projections E,FE, F. The paper notes that, besides linear matrices, mean or max pooling, or a convolution with kernel size and stride N/kN/k, can also serve as the projection.

Experimental results

Pretraining: models were pretrained on masked-word prediction on BookCorpus and English Wikipedia, and the perplexity curves were compared with RoBERTa (Figure 3 of the paper).

  • Size of kk: larger kk is better; with k=128k = 128 for N=512N = 512 and k=256k = 256 for N=1024N = 1024, the results are almost the same as a standard Transformer.
  • Sharing scheme: even "layerwise sharing" with a single projection performs almost the same as no sharing.
  • Sequence length: with k=256k = 256 fixed, increasing NN from 512 to 4,096 gives almost the same perplexity after convergence.

Fine-tuning: models pretrained on the same data for the same number of steps (250,000) were compared on sentiment classification (SST-2, IMDB), natural language inference (QNLI), and paraphrase detection (QQP) (validation data; Table 2 of the paper).

Length NNModelSST-2IMDBQNLIQQPAverage
512RoBERTa-base93.194.190.990.992.25
512Linformer (k=128k = 128)92.494.090.490.291.75
512Linformer (k=256k = 256)93.294.090.690.592.08
512Linformer (k=256k = 256, layerwise sharing)93.194.191.290.892.30
512BERT-base92.793.591.889.691.90
512DistilBERT91.392.889.288.590.45
1024Linformer (k=256k = 256, layerwise sharing)93.294.290.890.592.18

With k=128k = 128 it falls slightly short of RoBERTa, while k=256k = 256 with layerwise sharing slightly surpasses RoBERTa. Since N=1024N = 1024 with k=256k = 256 performs about the same, the paper states that performance is determined mainly by kk rather than by the ratio N/kN/k.

Inference speed and memory: on a 16GB V100, the ratios of inference speed and of the largest batch size that fits in memory, relative to a standard Transformer (layerwise sharing; excerpted from Table 3 of the paper).

Length NNSpeed (k=128k = 128)Speed (k=256k = 256)Memory (k=128k = 128)Memory (k=256k = 256)
5121.5×1.3×1.7×1.5×
4,0963.4×3.2×14×13×
65,53620×18×60×52×

The longer the sequence, the larger the gap.

Practical considerations

Linformer's projections E,FE, F mix all positions of the sequence to compress them into kk.

Because the projections mix all positions, by design the "do not look at future positions" constraint of models that generate one token at a time from the beginning (autoregressive models) cannot be applied straightforwardly. The paper's experiments also cover only encoders that look in both directions (masked-word pretraining and classification). In addition, since E,FE, F have size k×Nk \times N, the maximum sequence length NN must be fixed in advance, and shorter inputs are padded.

When using it, keep the following in mind.

  • Do not make kk too small: in the paper, k=128k = 128 at N=512N = 512 reduced performance slightly, while k=256k = 256 matched a standard Transformer.
  • Strict evaluation on long sequences can reveal gaps: in the FlashAttention paper, which compared methods under the same conditions on Long-Range Arena, a benchmark of long sequences, Linformer's average accuracy over five tasks was 54.9%, lower than the standard Transformer (59.3%) and Performer (58.9%) (Table 3 of the FlashAttention paper).
  • The sharing scheme reduces added parameters: with layerwise sharing there is only one projection matrix, and in the paper performance did not drop even so.

Comparison with other methods

Methods for lightening attention on long sequences are compared by "which part of the attention matrix is computed."

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 fixed patternSome pairs unattendedO(NN)O(N\sqrt{N})–O(N)O(N)
Linformer (Wang et al., 2020)Shrinks the matrix to N×kN \times k (projects keys and values to kk)ApproximateO(Nk)O(Nk)
Linear attention (Katharopoulos et al., 2020)Does not form the matrix (replaces softmax with a dot product of feature maps)A different functionO(N)O(N)
Performer (Choromanski et al., 2020)Does not form the matrix (approximates softmax with random features)ApproximateO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs. The full matrix is never kept in memoryExact (same values)Computation O(N2)O(N^2), extra memory O(N)O(N)

Whereas sparse attention and similar methods restrict which pairs are attended, Linformer differs in that it compresses the attended tokens themselves into kk representatives. Information from all tokens is mixed into the representatives, so no pairs are left unattended, but individual tokens can no longer be distinguished.

In the FlashAttention paper's Long-Range Arena comparison (sequence lengths 1,024–4,096), Linformer was 2.5 times faster than the standard implementation and the fastest of the approximate methods compared, but it had the lowest average accuracy.

Guidelines for choosing:

  • To quickly process long, fixed-length inputs with an encoder that looks in both directions: Linformer fits.
  • To use it in a model that generates from left to right: consider linear attention, which can be written in a causal form.
  • To avoid losing accuracy: compute standard attention with FlashAttention.

PyTorch example

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


class LinformerSelfAttention(nn.Module):
    """Linformer multi-head attention (Eq. (7) of the paper). The projections E, F are "shared across heads""""

    def __init__(self, dim, heads, max_len, k, share_kv=False):
        super().__init__()
        self.heads = heads
        self.to_qkv = nn.Linear(dim, 3 * dim)
        # E, F: learned projections that compress N positions into k along the sequence axis. Shape [max_len, k]
        self.E = nn.Parameter(torch.randn(max_len, k) / k ** 0.5)
        self.F = self.E if share_kv else nn.Parameter(torch.randn(max_len, k) / k ** 0.5)
        self.out = nn.Linear(dim, dim)

    def forward(self, x):
        b, n, dim = x.shape                       # n is at most max_len (shorter inputs are assumed to be padded)
        q, k, v = self.to_qkv(x).chunk(3, dim=-1)
        k = torch.einsum("bnd,nk->bkd", k, self.E[:n])   # E K: [b, k, dim]
        v = torch.einsum("bnd,nk->bkd", v, self.F[:n])   # F V: [b, k, dim]
        split = lambda t: t.view(b, -1, self.heads, dim // self.heads).transpose(1, 2)
        q, k, v = split(q), split(k), split(v)    # q: [b, h, n, d], k, v: [b, h, k, d]
        y = F.scaled_dot_product_attention(q, k, v)  # weights are [n × k] (no N × N matrix)
        return self.out(y.transpose(1, 2).reshape(b, n, dim))


attn = LinformerSelfAttention(dim=256, heads=8, max_len=512, k=128)
x = torch.randn(2, 512, 256)
print(attn(x).shape)  # torch.Size([2, 512, 256])

# Note: E, F mix all positions, so this cannot be combined with is_causal=True (no peeking at the future).

FAQ

Q. How should the projection dimension $k$ be chosen?
A.

In the paper, k=128k = 128 at N=512N = 512 fell slightly short of a standard Transformer, while k=256k = 256 was almost the same. With k=256k = 256 fixed, extending NN to 4,096 did not change the pretraining results, so start around k=256k = 256 and adjust for the trade-off between speed and quality. Higher layers tend to have lower rank, so kk can also be varied per layer.

Q. Can it be used in a model that generates text one word at a time?
A.

Not as is. The projections E,FE, F mix all positions of the sequence into kk representatives, so information from future positions leaks into them. The paper's experiments also cover only encoders that look in both directions. To reduce computation in a generative model, consider methods such as linear attention, which can be written in a causal form.

Q. What does "attention is low-rank" mean?
A.

It means that the N×NN \times N weight matrix PP can be almost fully represented by combinations of a small number of matrix components. The paper decomposed the PP of pretrained RoBERTa by singular value decomposition and showed that most of the information is concentrated in the first few large singular values. If it can be represented by a small number of representatives, compressing keys and values to kk loses little information.

References

  1. S. Wang, B. Z. Li, M. Khabsa, H. Fang, and H. Ma, "Linformer: Self-Attention with Linear Complexity," arXiv:2006.04768, 2020.
  2. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.
  3. A. Vaswani et al., "Attention Is All You Need," NIPS, 2017.