Attention Mechanisms  · June 2020

Linformer — Low-Rank Attention Projection

advanced

efficiency

Project keys and values down to a fixed low-rank subspace before attention — making attention O(N) by replacing the N×N attention matrix with an N×k one, where k is a fixed projection rank.

§ 1 · Premise

Attention is approximately low-rank — bake that in

Standard self-attention over a sequence of length NN with head dimension dhd_h computes an N×NN \times N probability matrix P=softmax(QK/dh)P = \mathrm{softmax}(QK^\top/\sqrt{d_h}) and then applies it to VRN×dhV \in \mathbb{R}^{N \times d_h}. Time and memory are Θ(N2dh)\Theta(N^2 d_h), and the dominant cost at NdhN \gtrsim d_h is the matrix PP itself, which carries N2N^2 logits regardless of content. At N=4,096N = 4{,}096, a single attention head materializes 67 MB of fp32 logits per batch element before softmax — and the model has HH of these per layer.

Wang et al. (§ 2 and Figure 2 of arXiv 2006.04768) ran a singular-value analysis of PP in pretrained RoBERTa and observed that its singular spectrum decays rapidly: ~90% of the spectral energy is captured by the top-128 singular vectors at N=512N = 512. They proved (their Theorem 1, via Johnson–Lindenstrauss) that for any softmax attention matrix and any ε>0\varepsilon > 0, there exists a rank-kk approximation with k=Θ(dhlog(dh)/ε2)k = \Theta(d_h \log(d_h) / \varepsilon^2) that achieves ε\varepsilon error in the resulting output — and crucially, kk does not grow with NN.

The architectural question: can the low rank be enforced at training time rather than discovered post hoc on a trained model? Linformer’s bet: yes, by projecting KK and VV along the sequence axis to a fixed dimension kk via two learned matrices. The resulting attention has Θ(Nkdh)\Theta(N k d_h) cost — linear in NN — and trains end-to-end.

The predecessor lineage is the broader “fast transformer” line of 2019–2020 — Sparse Transformer (entry) commits to a structured sparsity pattern, Reformer (entry) hashes to learned buckets. Linformer differs by attacking the low-rank structure of the dense probability matrix itself, not the sparsity of its support.

§ 2 · Derivation

Project the sequence axis, not the feature axis

Let QRN×dhQ \in \mathbb{R}^{N \times d_h}, KRN×dhK \in \mathbb{R}^{N \times d_h}, VRN×dhV \in \mathbb{R}^{N \times d_h} be the queries, keys, and values for one head (HH heads in parallel). Standard scaled dot-product attention is

Attn(Q,K,V)  =  softmax ⁣(1dhQK)V    RN×dh.\mathrm{Attn}(Q, K, V) \;=\; \mathrm{softmax}\!\Bigl(\tfrac{1}{\sqrt{d_h}} Q K^\top\Bigr) V \;\in\; \mathbb{R}^{N \times d_h}.

Step 1: insert a sequence-axis projection. Introduce two learnable matrices ERk×NE \in \mathbb{R}^{k \times N} and FRk×NF \in \mathbb{R}^{k \times N}, where kk is a chosen rank (Wang et al. use k=128k = 128 or 256256 regardless of NN). Apply them to KK and VV along the sequence axis:

K~  =  EK    Rk×dh,V~  =  FV    Rk×dh.\tilde{K} \;=\; E K \;\in\; \mathbb{R}^{k \times d_h}, \qquad \tilde{V} \;=\; F V \;\in\; \mathbb{R}^{k \times d_h}.

Note that EE and FF act on the sequence dimension, not the feature dimension. The features dhd_h are untouched. This is the load-bearing design choice: a feature-axis projection (reducing dhd_h to d<dhd' < d_h) loses the model’s representational dimensionality; a sequence-axis projection only loses the number of distinct “memory slots” the queries can attend to, which the low-rank result says is safe.

Step 2: attend against the projected sequence. Replace K,VK, V with K~,V~\tilde{K}, \tilde{V}:

LinAttn(Q,K,V)  =  softmax ⁣(1dhQK~)V~    RN×dh.\mathrm{LinAttn}(Q, K, V) \;=\; \mathrm{softmax}\!\Bigl(\tfrac{1}{\sqrt{d_h}} Q \tilde{K}^\top\Bigr) \tilde{V} \;\in\; \mathbb{R}^{N \times d_h}.

The logit matrix QK~Q \tilde{K}^\top is now N×kN \times k, not N×NN \times N. The softmax is over kk entries per row. The final matmul against V~\tilde{V} is N×kk×dhN \times k \cdot k \times d_h.

Step 3: count the FLOPs. Each query computes kk inner products against the kk projected keys, then weights kk projected values:

FLOPsLinformer  =  Θ(Nkdh)QK~+Θ(Nkdh)attnV~+Θ(Nkdh)EK and FV  =  Θ(Nkdh).\mathrm{FLOPs}_{\text{Linformer}} \;=\; \underbrace{\Theta(N k d_h)}_{Q \tilde{K}^\top} + \underbrace{\Theta(N k d_h)}_{\text{attn} \cdot \tilde{V}} + \underbrace{\Theta(N k d_h)}_{EK \text{ and } FV} \;=\; \Theta(N k d_h).

Linear in NN at fixed kk. The EKEK and FVFV projections themselves are k×NN×dh=Θ(Nkdh)k \times N \cdot N \times d_h = \Theta(N k d_h) matmuls, so they cost the same as the attention step rather than dominating.

Step 4: why is the approximation tight? Wang et al. (Theorem 1 of arXiv 2006.04768, restated):

For any Q,KRN×dhQ, K \in \mathbb{R}^{N \times d_h} and any ε,δ(0,1)\varepsilon, \delta \in (0, 1), there exists a matrix ERk×NE \in \mathbb{R}^{k \times N} with k=Θ(dhlogdh/ε2)k = \Theta(d_h \log d_h / \varepsilon^2) such that, with probability 1δ\ge 1 - \delta, softmax(QK)vsoftmax(Q(EK))(Ev)    εsoftmax(QK)v\bigl\lVert \mathrm{softmax}(QK^\top) v - \mathrm{softmax}(Q (EK)^\top) (E v) \bigr\rVert \;\le\; \varepsilon \lVert \mathrm{softmax}(QK^\top) v \rVert simultaneously for every column vv of VV.

The proof reduces softmax-attention error to Johnson–Lindenstrauss inner-product preservation on the unnormalized logits, then exploits the Lipschitz constant of softmax. The key takeaway is that the required kk depends on dhd_h (head dimension) and the target error, not on NN — the projection rank can be a fixed hyperparameter and quality does not degrade as NN grows. Empirically (Figure 4 of the paper), k=128k = 128 is sufficient up to N=4,096N = 4{,}096.

Step 5: parameter sharing. A naive instantiation has HH pairs of (Eh,Fh)(E_h, F_h) matrices per layer, 2HkN2 H k N parameters total. Wang et al. sweep three sharing modes (§ 4.2):

  1. Headwise: separate (Eh,Fh)(E_h, F_h) per head — most parameters, best quality.
  2. Key-Value shared: Eh=FhE_h = F_h within a head — half the params, ~0.1 GLUE points worse.
  3. Layerwise shared: one (E,F)(E, F) pair shared across all heads in a layer — fewest params, best Pareto point.

The recommended default is layerwise sharing, which adds 2kN2 k N parameters per layer — roughly 0.5%0.5\% of the FFN’s parameter count at typical k,Nk, N scales.

Why this works only for encoders. EE has shape k×Nk \times N, hard-coded at training time to the maximum sequence length NmaxN_{\text{max}}. Two consequences:

Wang et al. address only the bidirectional (encoder) case. Subsequent work — Linear Attention (Katharopoulos et al. 2020), Performer (entry) — solves the decoder case via a feature-map kernel rather than a sequence-axis projection.

Parameter count and complexity summary. Per layer at head dim dhd_h, HH heads, sequence length NN, rank kk, with layerwise-shared projection:

θLinformer  =  4Hdh2QKVO projections+2kNLinformer projections,|\theta_{\text{Linformer}}| \;=\; \underbrace{4 H d_h^2}_{\text{QKVO projections}} + \underbrace{2 k N}_{\text{Linformer projections}}, FLOPsLinformer/layer  =  Θ(NkdhH).\mathrm{FLOPs}_{\text{Linformer}}/\text{layer} \;=\; \Theta(N k d_h H).

The FLOP saving vs. standard attention is the factor k/Nk / N.

§ 3 · Reference implementation

Sketch

def linformer_attention(Q, K, V, E, F):
    # Q, K, V: [B, T, d_h]            T <= T_max, fixed at training time
    # E, F:    [k, T_max]              shared across heads in this layer
    K_proj = einsum("kt,btd->bkd", E, K)            # [B, k, d_h]
    V_proj = einsum("kt,btd->bkd", F, V)            # [B, k, d_h]
    logits = einsum("btd,bkd->btk", Q, K_proj)      # [B, T, k]
    logits = logits / d_h**0.5
    attn   = logits.softmax(-1)                     # softmax over k, not over T
    return einsum("btk,bkd->btd", attn, V_proj)      # [B, T, d_h]

The load-bearing change vs. MHA is the two einsum projections that compress the sequence axis from TT to kk before any QQ-dependent computation. The remaining attention is identical in shape to standard MHA with a “key sequence length” of kk. The implementation fits in a single Hugging Face transformers patch (see linformer-pytorch by Lucidrains for a production-style version: github.com/lucidrains/linformer).

Linformer multiplies K and V by learned matrices E, F ∈ ℝ^(k × L) to reduce the sequence axis from L to k. The attention matrix is L × k instead of L × L.K (L × d_h)L = 64d_h = 32E · KK' (k × d_h)k = 16softmax(Q · K'^T)k = 16softmax(Q · K^T)naive: L × LFLOP comparison (d_h = 32)Naive softmax: L · L · d_h = 131.1 KLinformer: L · k · d_h × 2 ≈ 65.5 KSpeedup: 2.00× at this kNote: E and F are learned per layer; depend on a fixed sequence length.
Linformer compresses the sequence axis of K and V from L to k via two learned matrices E, F ∈ ℝ^(k × L). The attention matrix becomes L × k instead of L × L; total cost is O(L · k · d_h). The catch: E and F are tied to a specific L, so a model trained at L = 4096 doesn't transfer cleanly to L = 8192. Linformer was a clean encoder-side technique; for decoders the fixed-L coupling never made sense.

§ 4 · Empirical evidence

Results

Pretraining quality at fixed NN (Wang et al. 2020, Table 3). A 12-layer Linformer with k=128k = 128 trained on the same RoBERTa pretraining recipe at N=512N = 512 matches the dense RoBERTa baseline within 0.5 GLUE points on average and matches on SQuAD-1.1. At k=256k = 256 the gap closes to within 0.1 GLUE points. The paper reports a 1.5× wall-clock speedup at N=512N = 512 that grows to 5.5× at N=4,096N = 4{,}096 (their Figure 3).

Quality at long sequences (Table 3 again). At N=1024N = 1024 and N=2048N = 2048, Linformer at k=256k = 256 remains within ~0.3 GLUE points of the dense baseline that was not trained at these lengths — Linformer is the first transformer in their suite to support these sequence lengths on the same hardware. The paper does not have a dense-attention comparison at N4,096N \ge 4{,}096 because it does not fit on the V100 hardware they used.

Long Range Arena (Tay et al. 2020, arXiv 2011.04006, Table 1). Independent reproduction by the LRA benchmark suite scores Linformer at average 51.36 across the five LRA tasks (ListOps 35.7, Text 53.9, Retrieval 52.3, Image 38.6, Pathfinder 76.3), vs. 54.39 for the dense softmax-attention baseline — a ~3-point gap. Linformer is mid-pack among the LRA variants: better than Reformer (50.67) and Performer (51.41), worse than BigBird (55.0) and Longformer (53.5). LRA uses a fixed N=4,096N = 4{,}096 across tasks, which is exactly the regime Linformer was designed for.

Sensitivity to kk (Wang et al. Figure 4). Quality is monotone-increasing in kk with a clear knee around k=128k = 128 for N1,024N \le 1{,}024 and around k=256k = 256 for N4,096N \le 4{,}096. Past k=512k = 512 there is no measurable improvement and the speedup over dense attention shrinks toward 1×.

Sharing scheme (Wang et al. Table 5). Layerwise sharing loses ~0.1–0.2 GLUE points vs. headwise sharing but uses 1/H1/H as many projection parameters. Key-value sharing within a head (E=FE = F) is essentially free at 0.1\le 0.1 point cost. Their recommended default ships layerwise-shared projections.

Why no decoder LLM ships it. Beyond the causality and variable-length issues laid out in § 2, Wang et al. did not run a decoder-side ablation. Subsequent surveys (Tay et al. 2022, “Efficient Transformers: A Survey”, arXiv 2009.06732, §3.4) classify Linformer as a “fixed-pattern + low-rank” hybrid suitable only for the encoder setting. The lineage descendant that does work autoregressively is Linear Attention (Katharopoulos et al. 2020), which uses a feature-map kernel ϕ(q)ϕ(k)\phi(\mathbf{q})^\top \phi(\mathbf{k}) instead of a sequence-axis projection.

Independent reproduction. The HuggingFace nielsr/linformer implementation reproduces the GLUE numbers within 0.3 points using k=128k = 128; the FAIR fairseq reference shipped a Linformer variant in 2021 that reproduces the speedup curves on TPU v3 hardware.

No public production-LLM adoption. I do not know of any frontier decoder-only LLM that ships Linformer. The technique persists in long-document encoder applications and as a baseline in efficient-attention research, but not in production generative models.

Cite

BibTeX entry for the original paper
@article{arxiv2006_04768,
  title  = {Linformer: Self-Attention with Linear Complexity},
  author = {Sinong Wang and others (Facebook AI)},
  year   = {2020},
  eprint = {2006.04768},
  archivePrefix = {arXiv},
  url    = {https://arxiv.org/abs/2006.04768}
}

Or cite the paper directly: arXiv:2006.04768.

Export

BibTeX
@article{arxiv_2006_04768,
  title         = {Linformer: Self-Attention with Linear Complexity},
  author        = {Sinong Wang et al. (Facebook AI)},
  year          = {2020},
  eprint        = {2006.04768},
  archivePrefix = {arXiv},
  url           = {https://arxiv.org/abs/2006.04768}
}
CSL JSON
{
  "id": "arxiv_2006_04768",
  "type": "article-journal",
  "title": "Linformer: Self-Attention with Linear Complexity",
  "author": [
    {
      "literal": "Sinong Wang et al. (Facebook AI)"
    }
  ],
  "issued": {
    "date-parts": [
      [
        2020
      ]
    ]
  },
  "URL": "https://arxiv.org/abs/2006.04768",
  "number": "2006.04768",
  "source": "arXiv"
}
RIS
TY  - JOUR
TI  - Linformer: Self-Attention with Linear Complexity
AU  - Sinong Wang et al. (Facebook AI)
PY  - 2020
JO  - arXiv
AN  - arXiv:2006.04768
UR  - https://arxiv.org/abs/2006.04768
ER  -