AI Logic

Attention Mechanisms

Linear Attention

Updated:

Structure of linear attention. The left shows the computation flow (Q and K pass through a feature map φ, keys and values are first aggregated into a d × d_v matrix, and each query reads from it). The right shows that no attention matrix (N × N) is formed; instead, a d × d_v matrix whose size does not depend on N is formed

What is linear attention

Linear attention is a method that reorders the attention computation so that the N×NN \times N weight matrix never has to be formed. Katharopoulos et al. proposed it in 2020 in the paper "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention."

Standard scaled dot-product attention first computes QK⊤QK^\top (N×NN \times N) and then multiplies by VV. As a result, computation and memory grow with the square of the sequence length NN.

Linear attention replaces the softmax function with "the dot product of vectors passed through a feature map ϕ\phi." The expression then consists only of matrix products, so the order of multiplication can be rearranged freely (associativity).

(ϕ(Q) ϕ(K)⊤) V=ϕ(Q) (ϕ(K)⊤V)\bigl(\phi(Q)\,\phi(K)^\top\bigr)\,V = \phi(Q)\,\bigl(\phi(K)^\top V\bigr)

The left side forms an N×NN \times N matrix, but the right side computes ϕ(K)⊤V\phi(K)^\top V first, so the only matrix it forms is a small d×dvd \times d_v one (vector length by vector length). Since its size does not depend on NN, computation and memory grow linearly with NN (O(N)O(N)).

As an analogy, instead of comparing everyone's business cards one by one (N×NN \times N times), the contents of the cards are first compiled into a single directory (d×dvd \times d_v), and each question only consults the directory. Once built, the directory can be reused no matter how many people ask.

The right side of the figure at the top of the article shows this difference. Softmax attention forms an N×NN \times N matrix, whereas linear attention forms only a d×dvd \times d_v matrix instead.

Theory

The paper generalizes attention as "a weighted average based on a similarity sim\mathrm{sim}" (Eq. (3) of the paper). QiQ_i is the ii-th row of QQ (the ii-th query).

Vi′=∑j=1Nsim(Qi,Kj) Vj∑j=1Nsim(Qi,Kj)V'_i = \frac{\sum_{j=1}^{N} \mathrm{sim}(Q_i, K_j)\, V_j}{\sum_{j=1}^{N} \mathrm{sim}(Q_i, K_j)}

Setting sim(q,k)=exp⁡(q⊤k/D)\mathrm{sim}(\boldsymbol{q}, \boldsymbol{k}) = \exp(\boldsymbol{q}^\top \boldsymbol{k} / \sqrt{D}) gives standard softmax attention (DD is the length of queries and keys). The only condition sim\mathrm{sim} needs for this to be a weighted average is that its values are non-negative.

Linear attention is computed as follows.

  1. Express similarity as a dot product: let sim(q,k)=ϕ(q)⊤ϕ(k)\mathrm{sim}(\boldsymbol{q}, \boldsymbol{k}) = \phi(\boldsymbol{q})^\top \phi(\boldsymbol{k}). ϕ\phi is a function (feature map) that maps a vector to a vector with non-negative values.
  2. Choose the feature map: the paper uses ϕ(x)=elu(x)+1\phi(x) = \mathrm{elu}(x) + 1 (Eq. (7) of the paper). ELU returns values greater than −1-1, so adding 1 makes it always positive.
  3. Aggregate keys and values first: compute ∑jϕ(Kj)Vj⊤\sum_{j} \phi(K_j) V_j^\top (a d×dvd \times d_v matrix) and ∑jϕ(Kj)\sum_j \phi(K_j) (a vector of length dd) only once.
  4. Read out per query: compute the output with the following formula (Eq. (5) of the paper). The two quantities from step 3 are reused for every query.
Vi′=ϕ(Qi)⊤∑j=1Nϕ(Kj) Vj⊤ϕ(Qi)⊤∑j=1Nϕ(Kj)V'_i = \frac{\phi(Q_i)^\top \sum_{j=1}^{N} \phi(K_j)\, V_j^\top}{\phi(Q_i)^\top \sum_{j=1}^{N} \phi(K_j)}

In step 2, the paper chose ELU rather than ReLU to avoid zero gradients when inputs are negative.

The complexity of softmax attention is O(N2max⁡(D,M))O(N^2 \max(D, M)) (MM is the length of values), while linear attention is O(NCM)O(NCM), where CC is the length of the feature map. With ϕ=elu+1\phi = \mathrm{elu} + 1, C=DC = D, so it becomes O(NDM)O(NDM).

Causal attention and its relation to RNNs

In a model that generates text one word at a time from the beginning, position ii attends only to earlier positions (j≤ij \le i). In linear attention, the sum in this case can be written with the following two "running totals" (Eqs. (10)–(12) of the paper).

Si=∑j=1iϕ(Kj) Vj⊤,Zi=∑j=1iϕ(Kj),Vi′=ϕ(Qi)⊤Siϕ(Qi)⊤ZiS_i = \sum_{j=1}^{i} \phi(K_j)\, V_j^\top, \qquad Z_i = \sum_{j=1}^{i} \phi(K_j), \qquad V'_i = \frac{\phi(Q_i)^\top S_i}{\phi(Q_i)^\top Z_i}

SiS_i and ZiZ_i can be updated simply by adding one term to the previous Si−1,Zi−1S_{i-1}, Z_{i-1}. In other words, this has the same form as an RNN that holds an internal state S,ZS, Z, updates the state each time an input arrives, and produces an output (Eqs. (16)–(20) of the paper). The paper's title, "Transformers are RNNs," refers to this relationship.

This property helps in training and inference as follows.

  • Training: since the whole sequence is available, all positions can be computed in parallel, just as in a standard Transformer.
  • Inference: each generation step only updates S,ZS, Z, so the time and memory per step are constant. A standard Transformer attends to every position generated so far, so the computation per step grows with sequence length.

A naive implementation of causal linear attention stores every SiS_i (NN matrices of size d×dvd \times d_v) for backpropagation, increasing memory by a factor of max⁡(D,M)\max(D, M). The paper shows that gradients can also be computed with cumulative sums (Eqs. (13)–(15) of the paper) and provides a GPU program (about 200 lines of CUDA) that avoids storing them.

Experimental results

The paper compares linear attention with standard softmax attention (softmax) and Reformer, which reduces computation with hashing (lsh-X, where X is the number of hashing rounds).

Speed and memory: the sequence length was varied from 292^9 to 2162^{16}, and the time and memory for one forward and backward pass were measured (GTX 1080 Ti, 11GB). The maximum length that fit in 11GB was 4,096 for softmax and 16,384 for lsh-4 and lsh-8. Linear attention was faster and used less memory than the other two at every length. On an artificial task of copying a sequence, it also converged stably to the same loss as softmax.

Image generation: models that generate images one pixel at a time were compared on performance (bits/dim, lower is better) and the number of images generated per second (Tables 1 and 2 of the paper).

DatasetMethodbits/dimImages generated per second
MNISTsoftmax0.6210.45 (1×)
lsh-10.7450.68 (1.5×)
lsh-40.6760.27 (0.6×)
Linear attention0.644142.8 (317×)
CIFAR-10softmax3.470.004 (1×)
lsh-13.390.015 (3.75×)
lsh-43.510.005 (1.25×)
Linear attention3.4017.85 (4,462×)

On MNIST, performance falls slightly short of softmax, but generation is more than 300 times faster. For CIFAR-10, every model was trained for one week on a single GPU. In the same time, linear attention completed about three times as many training iterations as softmax, and its bits/dim was also better than softmax.

Speech recognition (WSJ, trained with the CTC loss; lower error rate is better; Table 3 of the paper)

MethodPhoneme error rate (%)Time per epoch (s)
Bidirectional LSTM10.941047
softmax5.122711
lsh-49.332250
Linear attention8.08824

Linear attention was better than LSTM and Reformer and trained more than three times faster than softmax. However, softmax had the lowest error rate.

Practical considerations

Linear attention is not a computation that returns the same values as standard attention.

Linear attention replaces the softmax function (exponential similarity) with a different function, ϕ(q)⊤ϕ(k)\phi(\boldsymbol{q})^\top\phi(\boldsymbol{k}). The feature map corresponding to the exponential is infinite-dimensional, so softmax attention itself cannot be made linear. Performance can therefore change; in the paper's speech recognition, the phoneme error rate was 8.08% compared with 5.12% for softmax. It is also not possible to swap out only the attention of a pretrained model.

When using it, keep the following in mind.

  • Keep the values of ϕ\phi strictly positive: when the denominator ϕ(Qi)⊤∑jϕ(Kj)\phi(Q_i)^\top \sum_j \phi(K_j) approaches 0, the division becomes unstable. Implementations add a small value (such as 10−610^{-6}) to the denominator.
  • Short sequences rarely get faster: the difference between linear attention's O(NDM)O(NDM) and softmax's O(N2max⁡(D,M))O(N^2 \max(D, M)) appears only when NN is sufficiently larger than the vector length DD. The paper also notes that a second-degree polynomial feature map (O(ND2M)O(ND^2M)) pays off when N>D2N > D^2.
  • The causal case is faster with a dedicated program: writing the cumulative sum naively stores every SiS_i and increases memory.

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 (Child et al., 2019)Only some pairs in a fixed patternSome pairs unattendedO(NN)O(N\sqrt{N})
Linear attention (Katharopoulos et al., 2020)Does not form the matrix (changes the order of computation)Replaces softmax with another functionO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs. Split into small tiles; the full matrix is never kept in memoryExact (same values)Computation O(N2)O(N^2), extra memory O(N)O(N)

The FlashAttention paper compares these under the same conditions on Long-Range Arena, a benchmark of long sequences (sequence lengths 1,024–4,096) (Table 3 of the FlashAttention paper; average accuracy over five tasks).

MethodAverage accuracy (%)Speed relative to the standard implementation
Standard Transformer59.3—
FlashAttention59.82.4×
Linear attention59.62.3×
Performer58.91.8×
Reformer57.61.3×
Linformer54.92.5×

At these lengths, linear attention became faster with almost no loss in accuracy, but it was about as fast as FlashAttention, which speeds up exact computation. On the other hand, on Path-X, a task of length 16,384, the approximate methods including linear attention and the Transformer with the standard implementation all either ran out of memory or stayed at chance-level accuracy, while FlashAttention reached 61.4%.

Guidelines for choosing:

  • To run step-by-step generation of text or images at a constant speed even for long sequences: the RNN form of linear attention is a good fit.
  • To avoid losing accuracy: compute standard attention with a fast implementation such as FlashAttention.
  • When sequences are tens of thousands of tokens or longer and the N2N^2 computation itself is heavy: consider linear attention or sparse attention, and verify experimentally whether the performance drop is acceptable.

PyTorch example

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


def feature_map(x):
    """Eq. (7) of the paper: phi(x) = elu(x) + 1 (always positive)"""
    return F.elu(x) + 1


def linear_attention(q, k, v, eps=1e-6):
    """Non-causal linear attention (Eqs. 5 and 6). q, k: [B, H, N, D], v: [B, H, N, M]"""
    q, k = feature_map(q), feature_map(k)
    kv = torch.einsum("bhnd,bhnm->bhdm", k, v)        # aggregate first: sum_j phi(K_j) V_j^T  [B, H, D, M]
    z = k.sum(dim=2)                                   # sum_j phi(K_j)  [B, H, D]
    num = torch.einsum("bhnd,bhdm->bhnm", q, kv)       # phi(Q_i)^T (phi(K)^T V)
    den = torch.einsum("bhnd,bhd->bhn", q, z).unsqueeze(-1) + eps
    return num / den                                   # [B, H, N, M] (no N × N matrix is formed)


def causal_linear_attention(q, k, v, eps=1e-6):
    """Causal linear attention (Eqs. 10–12). Builds S_i, Z_i with cumulative sums.
    For clarity it keeps every S_i, so memory grows as N × D × M (the paper avoids this with a custom CUDA kernel)"""
    q, k = feature_map(q), feature_map(k)
    s = torch.einsum("bhnd,bhnm->bhndm", k, v).cumsum(dim=2)  # S_i  [B, H, N, D, M]
    z = k.cumsum(dim=2)                                         # Z_i  [B, H, N, D]
    num = torch.einsum("bhnd,bhndm->bhnm", q, s)
    den = torch.einsum("bhnd,bhnd->bhn", q, z).unsqueeze(-1) + eps
    return num / den


def recurrent_step(q_i, k_i, v_i, s, z, eps=1e-6):
    """RNN form for generating one step at a time during inference (Eqs. 16–20). q_i, k_i: [B, H, D], v_i: [B, H, M]"""
    q_i, k_i = feature_map(q_i), feature_map(k_i)
    s = s + torch.einsum("bhd,bhm->bhdm", k_i, v_i)   # update the state (its size does not depend on sequence length)
    z = z + k_i
    out = torch.einsum("bhd,bhdm->bhm", q_i, s) / (torch.einsum("bhd,bhd->bh", q_i, z).unsqueeze(-1) + eps)
    return out, s, z


B, H, N, D = 2, 8, 128, 32
q, k, v = torch.randn(B, H, N, D), torch.randn(B, H, N, D), torch.randn(B, H, N, D)
print(linear_attention(q, k, v).shape)  # torch.Size([2, 8, 128, 32])

# parallel computation (training) and step-by-step computation (inference) give the same result
out_parallel = causal_linear_attention(q, k, v)
s, z = torch.zeros(B, H, D, D), torch.zeros(B, H, D)
steps = []
for i in range(N):
    o, s, z = recurrent_step(q[:, :, i], k[:, :, i], v[:, :, i], s, z)
    steps.append(o)
print(torch.allclose(out_parallel, torch.stack(steps, dim=2), atol=1e-4))  # should be True

FAQ

Q. Is linear attention an approximation of softmax attention?
A.

Rather than an approximation, it is attention in which the similarity function is replaced with a different one. The feature map corresponding to softmax's exp⁡(q⊤k/D)\exp(\boldsymbol{q}^\top\boldsymbol{k}/\sqrt{D}) is infinite-dimensional, so it cannot be made linear as is. The paper uses ϕ(x)=elu(x)+1\phi(x) = \mathrm{elu}(x) + 1 and trains it from scratch as a model separate from softmax.

Q. Why can it be said that "Transformers are RNNs"?
A.

In causal linear attention, the next state is determined simply by adding to the previous state, Si=Si−1+ϕ(Ki)Vi⊤S_i = S_{i-1} + \phi(K_i)V_i^\top and Zi=Zi−1+ϕ(Ki)Z_i = Z_{i-1} + \phi(K_i), and the output can be computed from the state and ϕ(Qi)\phi(Q_i) alone. This is the same form as an RNN that produces outputs while updating an internal state.

Q. Does PyTorch have a built-in linear attention?
A.

Not in PyTorch itself. The non-causal case can be written in a few lines with torch.einsum, as in the example implementation. When training the causal case on long sequences, unless you use a dedicated program that computes the cumulative sums memory-efficiently, every SiS_i is stored and memory grows.

References

  1. A. Katharopoulos, A. Vyas, N. Pappas, and F. Fleuret, "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention," ICML, 2020.
  2. A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, Ł. Kaiser, and I. Polosukhin, "Attention Is All You Need," NIPS, 2017.
  3. T. Dao, D. Y. Fu, S. Ermon, A. Rudra, and C. Ré, "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness," NeurIPS, 2022.