Foundations to Frontier
Tests
E. Deep Learning › E12 Transformer Architectures

Linformer

Linformer (Wang and colleagues, 2020) makes attention linear in sequence length by projecting the n keys and values down to k rows with learned matrices, so the attention matrix is n × k instead of n × n. The justification is that attention matrices in trained models are approximately low rank. It matched RoBERTa-level accuracy at a fraction of the memory, but needs a fixed maximum length and does not suit causal decoding. This page covers the projection, the low-rank argument, costs and limits. In the exercises you implement Linformer attention and check it reduces to exact attention with identity projections. You then test the low-rank premise directly. Attention over clustered tokens has effective rank 5–8 of 256, and a rank-32 approximation changes its output by 2–11%. Sharp attention over unstructured tokens is nearly full-rank (223 of 256), and rank 32 loses 91% of the output.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Summarise the keys first

Attention compares each word with every other word: n × n comparisons. Linformer first squeezes the n keys into a short summary of k “super-keys”, say 256, and compares each word only with those. The cost then grows linearly with length. This works when the full attention pattern has a simple structure (low rank) that a few summaries can capture. The research exercise checks when that is true. The demo shows how cost grows with length.

Transformer lab
Full attention stores 16,777,216 scores per head; a linear-time method with 64 features stores 262,144, 64 times fewer.
Why engineers care

Low-rank approximations cut memory and compute wherever matrices have structure. Knowing when the low-rank assumption holds avoids silent accuracy loss.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Linformer compresses…
  2. 2. Its attention matrix is…
  3. 3. Linformer relies on attention being…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Projection:
    • K̃ = EK and Ṽ = FV, with learned E, F of size k × n;
    • attention = softmax(QK̃ᵀ/√d) Ṽ, an n × k matrix;
    • with identity projections (k = n) it is exact attention; selecting rows keeps only those keys.
  • Cost:
    • scores and weighted sum take 2nkd, plus the projections 2knd, so 4nkd in total, against full attention’s 2n²d;
    • at n = 4096, k = 256 that is 1/8 of the work;
    • break-even is n = 2k, so below 512 tokens full attention is cheaper for k = 256.
  • Low rank:
    • an attention matrix P has effective rank r if r singular values hold 90% of its energy;
    • uniform attention has rank 1, while one-hot attention (the identity) is full rank, needing 9 of 10 directions for 90%;
    • entropy measures sharpness: ln n for uniform, 0 for one-hot.
  • Limits:
    • E and F are sized for a fixed maximum n;
    • projecting along the sequence mixes future tokens into every summary, so causal masking breaks;
    • sharing E, F across heads and layers saves parameters.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Linformer's work relative to full attention at n = 4096, k = 256:
  2. 2. Effective rank of uniform attention:
  3. 3. Why is Linformer hard to use causally?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Linformer in code

Exercise 1.

  • With identity projections Linformer equalled exact attention.
  • With a selection of 16 rows it equalled attention over those 16 keys.
  • The cost for n = 4096, k = 256, d = 64 was 268 M multiply–adds.

Practice.

  • Implement E and F as nn.Linear(n, k, bias=False) applied along the sequence axis (transpose first). Share them across heads and layers to save parameters.
  • Pad or truncate inputs to the fixed n.
  • Wang et al. found k = 256 adequate for n from 512 to 4096 when fine-tuning pre-trained models, matching RoBERTa-base on several benchmarks.
  • For decoders and variable lengths, FlashAttention (exact, E12-20) or kernel methods (E12-19) are more practical.
class LinformerAttention(nn.Module):
    def __init__(self, n, k, d):
        super().__init__(); self.E = nn.Linear(n, k, bias=False); self.F = nn.Linear(n, k, bias=False)
    def forward(self, q, kx, v):                          # (B, n, d)
        k_ = self.E(kx.transpose(1, 2)).transpose(1, 2)   # (B, k, d)
        v_ = self.F(v.transpose(1, 2)).transpose(1, 2)
        return torch.softmax(q @ k_.transpose(1, 2) / q.shape[-1] ** 0.5, -1) @ v_
🐍 Exercise 1: Linformer attention
Implement Linformer's projected attention and its cost; check the identity and selection cases.
📝 Quick check (Level 2)
0/3 answered
  1. 1. E and F are applied along…
  2. 2. Wang et al.'s typical k:
  3. 3. An exact, memory-efficient alternative:

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why attention can be low rank.

  • If many queries attend in similar ways, as when tokens fall into a few clusters or attention is spread broadly, the rows of P are nearly linear combinations of a few patterns.
  • A few singular vectors then capture P, and projecting keys to k ≥ rank loses little.
  • Wang et al. showed the spectrum of RoBERTa’s attention matrices concentrates in the first singular values. Their theorem uses Johnson–Lindenstrauss random projections to bound the error.

When it is not.

  • Sharp attention that picks a different key for each query, such as attending to oneself or to exact positional offsets, makes P close to a permutation matrix, which has full rank.
  • No projection to k ≪ n can represent it.
  • Exercise 2 shows rank depends on both sharpness and structure: diffuse or clustered attention is low rank; sharp attention over unstructured tokens is not.

Learned projections. E and F are trained with the model, so they adapt to the data’s structure rather than relying on random projections.

📝 Quick check (Level 3)
0/3 answered
  1. 1. A permutation-like attention matrix has…
  2. 2. Linformer's theorem uses…
  3. 3. Low rank arises when queries…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

When is attention low rank?

History.

  • S. Wang, B. Li, M. Khabsa, H. Fang and H. Ma, “Linformer: self-attention with linear complexity” (2020).
  • Low-rank and kernel views of attention followed: Performer (E12-19), Nyströmformer (2021).

Exercise 2.

  • Inputs: attention over 256 tokens (dimension 32), either clustered around 8 centres or random directions. Token norms of 1–12 set how sharp attention is.
  • Measurement:
    • attention entropy;
    • effective rank (singular values holding 90% of the energy);
    • the error in the output P·V when P is replaced by its best rank-32 approximation, the best any Linformer-style projection could do.
tokens norm entropy effective rank (of 256) rank-32 output error
clustered 1 5.54 1 0.000
clustered 3 5.33 5 0.022
clustered 6 3.69 8 0.111
clustered 12 3.16 117 0.595
random 3 5.49 4 0.121
random 6 2.91 223 0.913
random 12 0.00 231 0.931
  • Diffuse or clustered attention is low rank. A rank-32 summary keeps the output within 2–11% for clustered tokens up to norm 6.
  • Sharp attention over unstructured tokens is nearly full-rank: each token attends mainly to itself, and rank 32 loses over 90% of the output.
  • Structure delays the breakdown: at norm 6, clustered tokens have rank 8 against 223 for random ones.
  • Linformer’s premise holds for some attention patterns, not all. Trained models’ heads vary, and positional or copying heads are exactly the sharp, high-rank kind.
🐍 Exercise 2 (research): when is attention low rank?
Measure attention entropy, effective rank and best rank-32 output error for clustered and random tokens at different sharpness.

Linformer in AI, robotics and aerospace

  • Long sensor sequences with smooth structure: low-rank attention can summarise slowly varying signals efficiently.
  • Model compression: checking singular-value spectra of weight or attention matrices tells when low-rank factorisation is safe.
  • Caution: tasks needing precise, token-specific lookups (copying identifiers, exact timing) need high-rank attention.

References

  1. S. Wang, B. Z. Li, M. Khabsa, H. Fang, H. Ma (2020). “Linformer: self-attention with linear complexity.” arXiv:2006.04768.
  2. Y. Xiong et al. (2021). “Nyströmformer: a Nyström-based algorithm for approximating self-attention.” Proc. AAAI.