AI Logic

Attention Mechanisms

Nyströmformer

Updated:

Structure of Nyströmformer. The left side shows the computation: landmarks are built from Q, K, and V by segment means, three softmax matrices are formed, the pseudoinverse is approximated iteratively, the output is obtained by matrix products, and a skip connection with a depthwise convolution of V is added. The right side shows an n × n matrix approximated by the product of three matrices of size n × m, m × m, and m × n, and 16 keys averaged in segments of 4 into 4 landmarks.

What is Nyströmformer?

Nyströmformer is a method that builds mm "landmarks" from the sequence and approximates the n×nn \times n attention matrix by a product of three small matrices that go through the landmarks. Xiong et al. at the University of Wisconsin–Madison proposed it in 2021 in the paper "Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention" (AAAI 2021).

Standard multi-head attention computes weights for every pair of tokens in a sequence of length nn, so its computation and memory grow in proportion to n2n^2. Nyströmformer applies the Nyström method, a numerical technique that reconstructs a large matrix from a subset of its rows and columns, to the softmax matrix of attention. If the number of landmarks mm is fixed far below nn, computation and memory grow in proportion to nn.

As an analogy: instead of building a table of how well every pair of students in a class (nn students) get along, pick a representative from each group (mm students), build only three tables, "students vs. representatives," "representatives vs. representatives," and "representatives vs. students," and combine them to estimate the table for the whole class.

The right side of the figure at the top of the article shows this approximation. The n×nn \times n matrix is never built; instead, three matrices of size n×mn \times m, m×mm \times m, and m×nm \times n are multiplied together.

Theory

Standard attention is the following equation (Eq. (2) in the paper). Q,K,VQ, K, V are n×dn \times d matrices.

D(Q,K,V)=SV=softmax ⁣(QK⊤dq)VD(Q, K, V) = SV = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_q}}\right) V

The Nyström method takes only mm rows and mm columns from a matrix SS and reconstructs the whole. Splitting SS into the sampled block ASA_S (m×mm \times m) and the rest, the remaining block CSC_S can be approximated by FSAS+BSF_S A_S^+ B_S (Eq. (4); AS+A_S^+ is the Moore–Penrose pseudoinverse).

S=[ASBSFSCS]≈[ASFS]AS+[ASBS]S = \begin{bmatrix} A_S & B_S \\ F_S & C_S \end{bmatrix} \approx \begin{bmatrix} A_S \\ F_S \end{bmatrix} A_S^+ \begin{bmatrix} A_S & B_S \end{bmatrix}

For a softmax matrix, however, this cannot be used as is. Because softmax divides by the sum of all values in a row, even extracting a few columns of SS requires computing every element of QK⊤QK^\top (n2n^2 elements) (Figure 1 in the paper).

Nyströmformer therefore builds landmarks from QQ and KK before the softmax and uses them to construct the three matrices directly (Algorithm 1 in the paper).

  1. Build landmarks: Split the nn queries into mm segments (of length l=n/ml = n/m) and take each segment's mean as a landmark q~j\tilde{q}_j (segment means, Eq. (16)). Key landmarks k~j\tilde{k}_j are built the same way.
  2. Build three softmax matrices: F~=softmax(QK~⊤/dq)\tilde{F} = \mathrm{softmax}(Q\tilde{K}^\top/\sqrt{d_q}) (n×mn \times m), A~=softmax(Q~K~⊤/dq)\tilde{A} = \mathrm{softmax}(\tilde{Q}\tilde{K}^\top/\sqrt{d_q}) (m×mm \times m), and B~=softmax(Q~K⊤/dq)\tilde{B} = \mathrm{softmax}(\tilde{Q}K^\top/\sqrt{d_q}) (m×nm \times n).
  3. Approximate the pseudoinverse of A~\tilde{A}: Singular value decomposition is slow on GPUs, so Z⋆≈A~+Z^\star \approx \tilde{A}^+ is obtained with an iterative formula that uses only matrix products (Eq. (14)).
  4. Compute the output: Working from the right, compute B~V\tilde{B}V (m×dvm \times d_v) first, then F~Z⋆(B~V)\tilde{F} Z^\star (\tilde{B} V) (Eq. (17)).
  5. Add a skip connection: Add VV passed through a 1D depthwise convolution to the output (Figure 4 in the paper).

The segment means in step 1 are given by the following equation (j=1,…,mj = 1, \dots, m). When nn is not divisible by mm, the sequence is padded.

q~j=1l∑i=(j−1)l+1jlqi,k~j=1l∑i=(j−1)l+1jlki\tilde{q}_j = \frac{1}{l}\sum_{i=(j-1)l+1}^{jl} q_i, \qquad \tilde{k}_j = \frac{1}{l}\sum_{i=(j-1)l+1}^{jl} k_i

The iteration in step 3 is the following (Razavi et al., 2014). The initial value is Z0=A~⊤/(∥A~∥1∥A~∥∞)Z_0 = \tilde{A}^\top / (\lVert \tilde{A} \rVert_1 \lVert \tilde{A} \rVert_\infty). In the paper's experiments, about 6 iterations gave a sufficient approximation.

Zj+1=14Zj(13I−A~Zj (15I−A~Zj (7I−A~Zj)))Z_{j+1} = \frac{1}{4} Z_j \bigl(13I - \tilde{A}Z_j\,(15I - \tilde{A}Z_j\,(7I - \tilde{A}Z_j))\bigr)

The output in step 4 is the following (Eq. (17) in the paper).

S^V=softmax ⁣(QK~⊤dq)Z⋆ softmax ⁣(Q~K⊤dq)V\hat{S}V = \mathrm{softmax}\!\left(\frac{Q\tilde{K}^\top}{\sqrt{d_q}}\right) Z^\star\, \mathrm{softmax}\!\left(\frac{\tilde{Q}K^\top}{\sqrt{d_q}}\right) V

Why a few landmarks are enough

There are two reasons the Nyströmformer approximation works.

  • The closer the landmarks are to the original points, the more accurate the approximation: Lemma 2 in the paper shows that in the ideal case where the landmarks coincide with the original queries and keys, the approximation equals standard attention. Segment means average nearby positions, so in sequences where neighboring tokens are similar, the landmarks represent the original points well.
  • Attention matrices are low-rank: The error of the Nyström method depends on the eigenvalue distribution of the matrix being approximated, and it shrinks as the rank decreases. As the Linformer paper showed, attention matrices can be represented almost entirely by a few components, so a few landmarks suffice. The paper states that 64 landmarks are enough in many cases.

The cost is O(n)O(n) for the segment means, O(m3)O(m^3) for the pseudoinverse iteration, and O(nm2+mndv+nmdv)O(nm^2 + mnd_v + nmd_v) for the matrix products. Memory is O(mdq+nm+m2+ndv)O(md_q + nm + m^2 + nd_v). When m≪nm \ll n, both time and memory grow in proportion to nn.

The order of computation matters. Multiplying F~Z⋆B~\tilde{F} Z^\star \tilde{B} first produces an n×nn \times n matrix. Computing B~V\tilde{B} V (m×dvm \times d_v) first and then multiplying by F~Z⋆\tilde{F} Z^\star (n×mn \times m) avoids ever building an n×nn \times n matrix. This is the same idea as linear attention, which reorders the computation to avoid N×NN \times N.

Experimental results

Speed and memory: These values measure only the attention part for a single input (Nvidia 1080Ti; excerpted from Table 1 in the paper; the numbers in parentheses are the factor relative to the standard Transformer). Nyströmformer-64 uses 64 landmarks, Linformer-256 uses a projection dimension of 256, and Longformer-257 uses a window size of 257.

MethodMemory (nn = 512)Time (nn = 512)Memory (nn = 8,192)Time (nn = 8,192)
Standard Transformer54 MB0.8 ms10,233 MB155.4 ms
Linformer-25641 MB (1.3×)0.7 ms (1.1×)635 MB (16.1×)11.3 ms (13.8×)
Longformer-25732.2 MB (1.7×)2.4 ms (0.3×)455 MB (22.5×)36.2 ms (4.3×)
Nyströmformer-6435 MB (1.5×)0.7 ms (1.1×)450 MB (22.8×)12.3 ms (12.7×)
Nyströmformer-3226 MB (2.1×)0.6 ms (1.2×)383 MB (26.7×)11.5 ms (13.4×)

Pretraining and fine-tuning: The attention in BERT-base was replaced with Nyströmformer, pretrained on BookCorpus and English Wikipedia, and then fine-tuned on GLUE tasks and IMDB (validation sets; F1 for MRPC and QQP, accuracy for the others; Table 2 in the paper).

ModelSST-2MRPCQNLIQQPMNLI (m/mm)IMDB
BERT-base90.088.490.387.382.4/82.493.3
Nyströmformer91.488.188.786.380.9/82.293.2

It outperformed BERT-base on SST-2, and the gaps on the other tasks were small. Fine-tuning on IMDB with a sequence length of 1,024 gave an accuracy of 93.0, nearly the same as with 512 (93.2).

Long-sequence benchmark: On Long-Range Arena, the same Transformer (2 layers, 64-dimensional embeddings, 2 heads) was compared with only the attention swapped (accuracy %; Table 3 in the paper).

MethodListOpsTextRetrievalImagePathfinderAverage
Standard attention37.1065.0279.3538.2074.1658.77
Reformer19.0564.8878.6443.2969.3655.04
Linformer37.2555.9179.3737.8467.6055.59
Performer18.8063.8178.6237.0769.8753.63
Nyströmformer37.1565.5279.5641.5870.9458.95

Its average accuracy was nearly the same as standard attention and 3–5 points higher than the other approximation methods. This comparison uses the benchmark as reimplemented in PyTorch by the paper's authors.

Practical considerations

Nyströmformer is an approximation through landmarks. How the landmarks are built determines where it can be used.

Segment means build each landmark by averaging the tokens in a segment, so a landmark also mixes in information from later positions in that segment. As a result, the "do not look at future positions" mask of a model that generates tokens one at a time from left to right cannot be applied as is. The paper's experiments, too, cover only encoders that look in both directions (masked-word pretraining and classification, and Long-Range Arena).

Keep the following points in mind when using it.

  • Start with around 64 landmarks mm: The paper says 64 are enough in many cases but that it depends on the application. Increasing mm makes the pseudoinverse computation heavier at O(m3)O(m^3).
  • Make the sequence length divisible by mm: Segment means split the sequence into segments of length l=n/ml = n/m, so lengths that do not divide evenly are padded.
  • Short sequences gain little speed: In Table 1 of the paper, a length of 512 was only about 1.1× faster, and the gap widened at lengths of 4,096 and above.
  • The number of pseudoinverse iterations changes the approximation accuracy: The initial value of the iteration does not guarantee convergence when A~\tilde{A} is singular, but the paper reports that its experiments obtained good approximations.

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)
Reformer (Kitaev et al., 2020)Only pairs in the same bucket (decided by hashing)Some pairs are skippedO(nlog⁡n)O(n \log n)
Linformer (Wang et al., 2020)Shrinks the matrix to n×kn \times k (keys and values compressed by learned projections)ApproximateO(nk)O(nk)
Performer (Choromanski et al., 2020)Never builds the matrix (softmax approximated with random features)ApproximateO(n)O(n)
Nyströmformer (Xiong et al., 2021)Expresses the matrix as a product of three matrices (n×mn \times m, m×mm \times m, m×nm \times n with the landmarks)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

The difference from Linformer lies in how the sequence is summarized. Linformer compresses only the keys and values into kk items with learned projections and uses the queries as they are. Nyströmformer builds landmarks from both the queries and the keys and reconstructs the whole matrix from the relationships among the landmarks (the pseudoinverse of A~\tilde{A}). Because the landmarks are segment means, no learned parameters are added (except the convolution in the skip connection).

As a rough guide to choosing among them:

  • Processing inputs of several thousand tokens quickly in a bidirectional encoder: Nyströmformer or Linformer fits. In the paper's comparison, Nyströmformer achieved higher accuracy on Long-Range Arena.
  • Using it in a model that generates from left to right: Consider methods such as linear attention, which can be written in a causal form.
  • Not wanting to sacrifice exactness: Compute standard attention with FlashAttention.

PyTorch example

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


def iterative_pinv(a, n_iter=6):
    """Approximate the Moore-Penrose pseudoinverse using only matrix products (Eq. (14) of the paper). a: [..., m, m]"""
    eye = torch.eye(a.shape[-1], device=a.device, dtype=a.dtype)
    # initial value Z0 = Aᵀ / (||A||_1 ||A||_∞). softmax matrices are non-negative, so no abs is needed
    norm1 = a.sum(dim=-2).amax(dim=-1, keepdim=True)    # max column sum
    norm_inf = a.sum(dim=-1).amax(dim=-1, keepdim=True)  # max row sum
    z = a.transpose(-1, -2) / (norm1 * norm_inf).unsqueeze(-1)
    for _ in range(n_iter):
        az = a @ z
        z = 0.25 * z @ (13 * eye - az @ (15 * eye - az @ (7 * eye - az)))
    return z


class NystromAttention(nn.Module):
    """Nyströmformer attention (Eq. (17) and Figure 4 of the paper)"""

    def __init__(self, dim, heads=8, num_landmarks=64, conv_kernel=33):
        super().__init__()
        self.h, self.m = heads, num_landmarks
        self.to_qkv = nn.Linear(dim, 3 * dim)
        self.out = nn.Linear(dim, dim)
        d = dim // heads
        # skip connection on V: 1D depthwise convolution along the sequence (per head)
        self.conv = nn.Conv2d(heads, heads, (conv_kernel, 1), padding=(conv_kernel // 2, 0), groups=heads, bias=False)

    def forward(self, x):
        b, n, dim = x.shape                       # n must be divisible by num_landmarks
        q, k, v = self.to_qkv(x).chunk(3, dim=-1)
        q, k, v = (t.view(b, n, self.h, -1).transpose(1, 2) for t in (q, k, v))  # [b, h, n, d]
        q = q / q.shape[-1] ** 0.5                # 1/√d
        # build landmarks by segment means (Eq. 16): [b, h, m, d]
        q_l = q.reshape(b, self.h, self.m, n // self.m, -1).mean(dim=-2)
        k_l = k.reshape(b, self.h, self.m, n // self.m, -1).mean(dim=-2)
        f = F.softmax(q @ k_l.transpose(-1, -2), dim=-1)    # F~ [n × m]
        a = F.softmax(q_l @ k_l.transpose(-1, -2), dim=-1)  # A~ [m × m]
        bb = F.softmax(q_l @ k.transpose(-1, -2), dim=-1)   # B~ [m × n]
        y = (f @ iterative_pinv(a)) @ (bb @ v)    # compute B~V first; never build n × n
        y = y + self.conv(v)                      # skip connection
        return self.out(y.transpose(1, 2).reshape(b, n, dim))


attn = NystromAttention(dim=256, heads=8, num_landmarks=64)
x = torch.randn(2, 1024, 256)
print(attn(x).shape)  # torch.Size([2, 1024, 256])

FAQ

Q. How should the number of landmarks $m$ be chosen?
A.

The paper states that 64 landmarks give a sufficient approximation in many cases. For attention on a sequence of length 8,192, memory dropped to 1/22.8 with 64 landmarks and 1/26.7 with 32 (Table 1 in the paper). Increasing mm makes the approximation more accurate, but the pseudoinverse computation becomes heavier at O(m3)O(m^3).

Q. How does it differ from Linformer?
A.

Linformer compresses the keys and values into kk items with learned projections. Because the projection size depends on the maximum sequence length, the length must be fixed in advance. Nyströmformer averages both the queries and the keys over segments to form landmarks and reconstructs the whole matrix from the relationships among the landmarks. In the paper's Long-Range Arena comparison, the average accuracy was 55.59% for Linformer and 58.95% for Nyströmformer.

Q. Can't the pseudoinverse be computed with singular value decomposition?
A.

It can, but the paper uses an iterative formula that needs only matrix products because singular value decomposition is inefficient on GPUs. Since only matrix products are involved, gradients are also straightforward to compute. In the paper's experiments, about 6 iterations gave a sufficient approximation.

References

  1. Y. Xiong, Z. Zeng, R. Chakraborty, M. Tan, G. Fung, Y. Li, and V. Singh, "Nyströmformer: A Nyström-Based Algorithm for Approximating Self-Attention," AAAI, 2021.
  2. S. Wang, B. Z. Li, M. Khabsa, H. Fang, and H. Ma, "Linformer: Self-Attention with Linear Complexity," arXiv:2006.04768, 2020.
  3. Official implementation of Nyströmformer (mlpen/Nystromformer)