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 with head dimension computes an probability matrix and then applies it to . Time and memory are , and the dominant cost at is the matrix itself, which carries logits regardless of content. At , a single attention head materializes 67 MB of fp32 logits per batch element before softmax — and the model has of these per layer.
Wang et al. (§ 2 and Figure 2 of arXiv 2006.04768) ran a singular-value analysis of 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 . They proved (their Theorem 1, via Johnson–Lindenstrauss) that for any softmax attention matrix and any , there exists a rank- approximation with that achieves error in the resulting output — and crucially, does not grow with .
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 and along the sequence axis to a fixed dimension via two learned matrices. The resulting attention has cost — linear in — 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 , , be the queries, keys, and values for one head ( heads in parallel). Standard scaled dot-product attention is
Step 1: insert a sequence-axis projection. Introduce two learnable matrices and , where is a chosen rank (Wang et al. use or regardless of ). Apply them to and along the sequence axis:
Note that and act on the sequence dimension, not the feature dimension. The features are untouched. This is the load-bearing design choice: a feature-axis projection (reducing to ) 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 with :
The logit matrix is now , not . The softmax is over entries per row. The final matmul against is .
Step 3: count the FLOPs. Each query computes inner products against the projected keys, then weights projected values:
Linear in at fixed . The and projections themselves are 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 and any , there exists a matrix with such that, with probability , simultaneously for every column of .
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 depends on (head dimension) and the target error, not on — the projection rank can be a fixed hyperparameter and quality does not degrade as grows. Empirically (Figure 4 of the paper), is sufficient up to .
Step 5: parameter sharing. A naive instantiation has pairs of matrices per layer, parameters total. Wang et al. sweep three sharing modes (§ 4.2):
- Headwise: separate per head — most parameters, best quality.
- Key-Value shared: within a head — half the params, ~0.1 GLUE points worse.
- Layerwise shared: one pair shared across all heads in a layer — fewest params, best Pareto point.
The recommended default is layerwise sharing, which adds parameters per layer — roughly of the FFN’s parameter count at typical scales.
Why this works only for encoders. has shape , hard-coded at training time to the maximum sequence length . Two consequences:
- At inference time, the model cannot handle sequences longer than — the projection has no defined behavior on out-of-range positions.
- Causal masking is incompatible with . The projection mixes keys across all positions, so a query at position ends up attending to — a key that has already been contaminated by future positions .
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 , heads, sequence length , rank , with layerwise-shared projection:
The FLOP saving vs. standard attention is the factor .
§ 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 to before any -dependent computation. The remaining attention is
identical in shape to standard MHA with a “key sequence length” of . The implementation
fits in a single Hugging Face transformers patch (see linformer-pytorch by Lucidrains for a
production-style version: github.com/lucidrains/linformer).
§ 4 · Empirical evidence
Results
Pretraining quality at fixed (Wang et al. 2020, Table 3). A 12-layer Linformer with trained on the same RoBERTa pretraining recipe at matches the dense RoBERTa baseline within 0.5 GLUE points on average and matches on SQuAD-1.1. At the gap closes to within 0.1 GLUE points. The paper reports a 1.5× wall-clock speedup at that grows to 5.5× at (their Figure 3).
Quality at long sequences (Table 3 again). At and , Linformer at 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 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 across tasks, which is exactly the regime Linformer was designed for.
Sensitivity to (Wang et al. Figure 4). Quality is monotone-increasing in with a clear knee around for and around for . Past 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 as many projection parameters. Key-value sharing within a head () is essentially free at 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 instead of a sequence-axis projection.
Independent reproduction. The HuggingFace nielsr/linformer implementation reproduces
the GLUE numbers within 0.3 points using ; 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 -