AI Logic

Attention Mechanisms

Performer (FAVOR+)

Updated:

Structure of Performer. Left: the computation flow (positive orthogonal random features Ο† are applied to Q and K, keys and values are first aggregated into an r Γ— d matrix, and each query reads from it). Right: no N Γ— N attention matrix is built; it is approximated by the random-feature product Qβ€²Kβ€²α΅€, and an r Γ— d matrix whose size does not depend on N is built instead

What is Performer

Performer is a Transformer that approximates softmax attention weights with dot products of randomly generated feature vectors and computes attention without building the NΓ—NN \times N matrix. It was proposed by Choromanski et al. at Google and elsewhere in the 2020 paper "Rethinking Attention with Performers" and presented at ICLR 2021. The approximation mechanism is called FAVOR+ (Fast Attention Via positive Orthogonal Random features).

Linear attention replaced softmax with a different function, Ο•(q)βŠ€Ο•(k)\phi(\boldsymbol{q})^\top \phi(\boldsymbol{k}), and reordered the computation to reach O(N)O(N). However, the replacement function is not softmax, so it does not give the same values as a pretrained model's attention.

Performer also reorders the computation, but it generates Ο•\phi randomly so that the expected value of its dot product exactly equals the softmax weight exp⁑(q⊀k)\exp(\boldsymbol{q}^\top \boldsymbol{k}). In other words, it approximates softmax attention itself without bias.

As an analogy, instead of comparing everyone's preferences pair by pair (NΓ—NN \times N times), you randomly create a fixed set of mm questions, record each person's answers, and estimate how similar two people's preferences are from how well their answers match. The more questions, the more accurate the estimate, and the number of questions does not depend on the number of people NN.

The right side of the figure at the top of the article shows this difference. Softmax attention builds an NΓ—NN \times N matrix, whereas Performer approximates it with dot products of random features and builds only an rΓ—dr \times d matrix instead.

Theory

Standard (bidirectional) attention can be written as Eq. (1) of the paper. Q,K,VQ, K, V are LΓ—dL \times d (LL is the sequence length), and exp⁑\exp is applied element-wise.

Att(Q,K,V)=Dβˆ’1AV,A=exp⁑ ⁣(QK⊀d),D=diag(A1L)\mathrm{Att}(Q, K, V) = D^{-1} A V, \qquad A = \exp\!\left(\frac{QK^\top}{\sqrt{d}}\right), \qquad D = \mathrm{diag}(A \mathbf{1}_L)

Since AA is LΓ—LL \times L, the compute is O(L2d)O(L^2 d) and the memory is O(L2+Ld)O(L^2 + Ld).

Performer writes each element of AA as the expected value of a dot product under a random feature map Ο•\phi (Eq. (3) of the paper).

A(i,j)=K(qi,kj)=E[Ο•(qi)βŠ€Ο•(kj)]A(i, j) = \mathrm{K}(\boldsymbol{q}_i, \boldsymbol{k}_j) = \mathbb{E}\left[\phi(\boldsymbol{q}_i)^\top \phi(\boldsymbol{k}_j)\right]

Using Qβ€²,Kβ€²Q', K' (LΓ—rL \times r) obtained by applying Ο•\phi, the approximate attention is as follows (Eq. (4) of the paper; parentheses indicate the order of computation).

Att^(Q,K,V)=D^βˆ’1(Qβ€²((Kβ€²)⊀V)),D^=diag(Qβ€²((Kβ€²)⊀1L))\widehat{\mathrm{Att}}(Q, K, V) = \hat{D}^{-1}\left(Q'\left((K')^\top V\right)\right), \qquad \hat{D} = \mathrm{diag}\left(Q'\left((K')^\top \mathbf{1}_L\right)\right)

Because (Kβ€²)⊀V(K')^\top V (rΓ—dr \times d) is computed first, no LΓ—LL \times L matrix is built. The compute is O(Lrd)O(Lrd) and the memory is O(Lr+Ld+rd)O(Lr + Ld + rd).

FAVOR+ builds Ο•\phi with the following steps.

  1. Draw mm random directions: sample Ο‰1,…,Ο‰m\boldsymbol{\omega}_1, \dots, \boldsymbol{\omega}_m from the standard normal distribution N(0,Id)\mathcal{N}(0, I_d).
  2. Make the directions mutually orthogonal (O): orthogonalize the Ο‰i\boldsymbol{\omega}_i with Gram–Schmidt. The expected value stays the same; only the variance of the estimate decreases.
  3. Build positive random features (R+): map the input x\boldsymbol{x} (a query or key divided by d4\sqrt[4]{d}) to a length-mm vector with the formula below. The values are always positive.
  4. Compute attention with the reordered computation (FA): compute with Eq. (4) above.

The feature map in step 3 is the following (Lemma 1 of the paper).

Ο•(x)=1mexp⁑ ⁣(βˆ’βˆ₯xβˆ₯22)(exp⁑(Ο‰1⊀x),…,exp⁑(Ο‰m⊀x))\phi(\boldsymbol{x}) = \frac{1}{\sqrt{m}} \exp\!\left(-\frac{\|\boldsymbol{x}\|^2}{2}\right)\left(\exp(\boldsymbol{\omega}_1^\top \boldsymbol{x}), \dots, \exp(\boldsymbol{\omega}_m^\top \boldsymbol{x})\right)

This Ο•\phi satisfies the following identity for the softmax weight SM(x,y)=exp⁑(x⊀y)\mathrm{SM}(\boldsymbol{x}, \boldsymbol{y}) = \exp(\boldsymbol{x}^\top \boldsymbol{y}).

SM(x,y)=EΟ‰βˆΌN(0,Id)[exp⁑ ⁣(Ο‰βŠ€xβˆ’βˆ₯xβˆ₯22)exp⁑ ⁣(Ο‰βŠ€yβˆ’βˆ₯yβˆ₯22)]\mathrm{SM}(\boldsymbol{x}, \boldsymbol{y}) = \mathbb{E}_{\boldsymbol{\omega} \sim \mathcal{N}(0, I_d)}\left[\exp\!\left(\boldsymbol{\omega}^\top \boldsymbol{x} - \frac{\|\boldsymbol{x}\|^2}{2}\right)\exp\!\left(\boldsymbol{\omega}^\top \boldsymbol{y} - \frac{\|\boldsymbol{y}\|^2}{2}\right)\right]

Ο•(x)βŠ€Ο•(y)\phi(\boldsymbol{x})^\top \phi(\boldsymbol{y}), averaged over mm samples of Ο‰\boldsymbol{\omega}, is an unbiased estimate of the softmax weight.

For autoregressive models (which do not look at future positions), as with linear attention, attention can be computed without building an LΓ—LL \times L matrix by using prefix sums of Kjβ€²Vj⊀K'_j V_j^\top (Appendix B.1 of the paper).

Why "positive" and "orthogonal" are needed

Approximating kernels with random features is not new, and trigonometric features using sin⁑\sin and cos⁑\cos can also estimate softmax weights without bias. Here is why they had not been used for attention, and how FAVOR+ addresses it.

  • Trigonometric features produce negative values: most attention weights are near-zero values between weakly related tokens. With trigonometric features, the estimates of these near-zero values have high variance and can even be negative. This can make the diagonal of the normalizer D^βˆ’1\hat{D}^{-1} negative, causing training to stall or become unstable. The paper's appendix even shows examples of NaNs appearing during training.
  • Positive features are most accurate for values near zero: according to Lemma 2 of the paper, as the weight approaches zero, the mean squared error of trigonometric features diverges to infinity, while that of positive features approaches zero. Features built with exp⁑\exp are always positive, so normalization is also stable.
  • Orthogonalization reduces variance further: Theorem 2 of the paper shows that making Ο‰\boldsymbol{\omega} orthogonal always reduces the mean squared error of positive features, for any dimension dd. The same accuracy can be reached with fewer features mm.

Theorem 4 of the paper shows, for orthogonalized trigonometric features, that the number of features mm needed to approximate the attention matrix within error ϡ\epsilon is determined by the vector size dd, the magnitudes of the queries and keys, and the accuracy ϡ\epsilon, and does not depend on the sequence length LL (roughly m=Θ(dlog⁑d)m = \Theta(d \log d)).

The feature map Ο•\phi can be chosen freely and need not approximate softmax. The paper also tries Performer-ReLU, which uses ReLU for Ο•\phi (generalized attention that does not approximate softmax), and it achieved the best accuracy on protein sequence modeling. In this case, as with linear attention, the model learns a function different from softmax.

Experimental results

Most of the paper's experiments are shown as learning-curve plots. The main results that can be checked numerically are as follows.

Speed and memory: forward and backward pass times were measured on a V100 (16GB) for varying sequence lengths (Figure 3 of the paper). Performer's time grows almost linearly with sequence length and nearly reaches the ideal speed of an attention that "just returns VV". It runs even at lengths where a standard Transformer does not fit in memory.

Compatibility with pretrained Transformers: transferring a pretrained Transformer's weights directly to a Performer initially drops accuracy to 0.07, but it recovers with far fewer fine-tuning steps than the original training (Figure 5 of the paper). However, on the large PG-19 dataset, trigonometric features were very unstable, and even positive features did not reach standard Transformer performance unless the features were redrawn. Periodically redrawing the positive features brought performance up to that of the standard Transformer.

Protein sequence modeling (TrEMBL, length 1,024, 36 layers; test data; Table 2 in the paper's appendix)

DirectionModelAccuracy (%)Perplexity
UnidirectionalTransformer30.809.37
Performer (generalized, ReLU)31.589.17
BidirectionalTransformer33.329.22
Performer (softmax approximation)33.009.24
Performer (generalized, ReLU)36.098.36

The Performer that approximates softmax gives almost the same values as the standard Transformer, showing that the approximation is accurate enough. Reformer and Linformer, compared under the same conditions, lost a lot of accuracy (Figure 6 of the paper).

Long sequences:

  • ImageNet 64Γ—64 image generation (length 12,288): a 6-layer Performer matched a 12-layer Reformer, and a 12-layer Performer matched a 24-layer Reformer (Figure 7 of the paper).
  • Concatenated protein sequences of length 8,192: the standard Transformer did not fit in memory even with batch size 1, and smaller models reduced to 1–3 layers plateaued at about 19% accuracy. Performer could be trained at the regular size (6 layers) and reached about 24%.

Long-Range Arena: on this long-sequence benchmark (lengths 1,024–4,096), compared under identical conditions in the FlashAttention paper, Performer's average accuracy over the five tasks was 58.9%, close to the standard Transformer (59.3%), and it was 1.8 times faster (Table 3 of the FlashAttention paper).

Practical considerations

Performer is a method that estimates softmax attention randomly.

Because the result is a random estimate, it does not exactly match standard attention, and the error grows as the number of features mm shrinks. The paper notes that even small errors can grow as layers and heads are stacked. Also, if the same random directions are used throughout training, performance can plateau when unlucky directions happen to be drawn, so the paper redraws them periodically.

Keep the following in mind when using it.

  • Choose the number of features mm: the default in the paper's experiments is m=256m = 256. mm does not depend on the sequence length; it is determined by the vector size dd and the required accuracy.
  • Watch the magnitudes of queries and keys: since the features are exp⁑(Ο‰βŠ€xβˆ’βˆ₯xβˆ₯2/2)\exp(\boldsymbol{\omega}^\top \boldsymbol{x} - \|\boldsymbol{x}\|^2/2), large values overflow easily. Implementations subtract the per-row maximum before taking exp⁑\exp (constant factors cancel out in normalization).
  • Be careful with half-precision training: in the FlashAttention paper's comparison, Performer alone was unstable with mixed-precision training, so it was trained without mixed precision (appendix of the FlashAttention paper). If you use mixed-precision training, check that it is stable.
  • Short sequences rarely get faster: the cost O(Lrd)O(Lrd) is smaller than the standard O(L2d)O(L^2 d) only when LL is sufficiently larger than the number of features rr.

Comparison with other methods

Methods that make attention cheaper for long sequences are compared here by "which part of the attention matrix is computed".

MethodWhich part of the NΓ—NN \times N matrix is computedResultCost (in sequence length NN)
Multi-head attentionAll pairsExactO(N2)O(N^2)
Sparse attention, Longformer, BigBirdOnly a predefined subset of pairsSome pairs skippedO(NN)O(N\sqrt{N}) to O(N)O(N)
Linformer (Wang et al., 2020)Shrinks the matrix to NΓ—kN \times kApproximate (bidirectional only)O(Nk)O(Nk)
Linear attention (Katharopoulos et al., 2020)No matrix is built (dot products of Ο•=elu+1\phi = \mathrm{elu} + 1)A function different from softmaxO(N)O(N)
Performer (Choromanski et al., 2020)No matrix is built (dot products of positive orthogonal random features)Unbiased approximation of softmaxO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs, without storing the full matrix in memoryExact (same values)O(N2)O(N^2) compute, O(N)O(N) extra memory

Performer and linear attention share the same form: "apply a feature map, then reorder the computation". The difference is Ο•\phi: linear attention uses a fixed function (elu+1\mathrm{elu} + 1), while Performer generates it randomly so that it matches softmax. This is why Performer can be transferred from a pretrained Transformer's weights with a little fine-tuning.

Rough guidelines for choosing:

  • Lighten a pretrained Transformer for long sequences: Performer, which approximates softmax, fits.
  • Speed up an autoregressive model without worrying about approximation error: the simpler linear attention is also a candidate.
  • A few thousand tokens, faster but still exact: use FlashAttention, which does not approximate.

PyTorch example

Show code
python
import math
import torch


def orthogonal_gaussian(m, d):
    """Mutually orthogonal random directions Ο‰ (m Γ— d). Orthogonalize d at a time with QR, and set lengths to match Gaussian samples"""
    blocks = []
    for _ in range(math.ceil(m / d)):
        q, _ = torch.linalg.qr(torch.randn(d, d))
        blocks.append(q.T)
    w = torch.cat(blocks)[:m]
    return w * torch.randn(m, d).norm(dim=1, keepdim=True)   # set each row's length to that of a sample from N(0, I)


def positive_features(x, w, is_query):
    """Positive random features (Lemma 1 of the paper): phi(x) = exp(w^T x - |x|^2 / 2) / sqrt(m). x: [..., L, d]"""
    x = x / x.shape[-1] ** 0.25                    # to match QK^T / sqrt(d), divide q and k each by d^(1/4)
    proj = x @ w.T                                 # [..., L, m]
    sq = (x ** 2).sum(dim=-1, keepdim=True) / 2
    # Prevent overflow: subtract the maximum before exp (constant factors cancel in normalization)
    stab = proj.amax(dim=-1, keepdim=True) if is_query else proj.amax(dim=(-2, -1), keepdim=True)
    return torch.exp(proj - sq - stab) / w.shape[0] ** 0.5


def favor_attention(q, k, v, w, causal=False, eps=1e-6):
    """FAVOR+ (Eq. (4) of the paper). q, k: [B, H, L, d], v: [B, H, L, dv], w: [m, d]"""
    qp, kp = positive_features(q, w, True), positive_features(k, w, False)   # Q', K': [B, H, L, m]
    if not causal:
        kv = torch.einsum("bhlm,bhld->bhmd", kp, v)                # (K')^T V first: [B, H, m, dv]
        num = torch.einsum("bhlm,bhmd->bhld", qp, kv)
        den = torch.einsum("bhlm,bhm->bhl", qp, kp.sum(dim=2))
    else:
        # Unidirectional case: prefix sums (Appendix B.1). Holds L Γ— m Γ— dv for clarity
        kv = torch.einsum("bhlm,bhld->bhlmd", kp, v).cumsum(dim=2)
        num = torch.einsum("bhlm,bhlmd->bhld", qp, kv)
        den = torch.einsum("bhlm,bhlm->bhl", qp, kp.cumsum(dim=2))
    return num / (den.unsqueeze(-1) + eps)                          # no L Γ— L matrix is built


B, H, L, d, m = 2, 4, 1024, 64, 256
q, k, v = torch.randn(B, H, L, d), torch.randn(B, H, L, d), torch.randn(B, H, L, d)
w = orthogonal_gaussian(m, d)          # during training, redraw e.g. every few hundred steps
out = favor_attention(q, k, v, w)
print(out.shape)  # torch.Size([2, 4, 1024, 64])

# Check: difference from standard softmax attention (shrinks as m increases)
exact = torch.softmax(q @ k.transpose(-1, -2) / d ** 0.5, dim=-1) @ v
print((out - exact).abs().mean())

FAQ

Q. How does it differ from linear attention?
A.

Both reorder the computation so that no NΓ—NN \times N matrix is built. The difference is the feature map Ο•\phi: linear attention uses the fixed function elu(x)+1\mathrm{elu}(x) + 1 and learns a function different from softmax. Performer generates Ο•\phi randomly so that the expected dot product matches the softmax weight exp⁑(q⊀k)\exp(\boldsymbol{q}^\top \boldsymbol{k}), making it an approximation of softmax attention.

Q. Can the random directions stay the same throughout training?
A.

The paper recommends redrawing them periodically. On the large PG-19 dataset, even positive features plateaued without redrawing, and with redrawing they matched the standard Transformer. Redrawing is cheap to compute.

Q. Can a pretrained Transformer's attention be swapped for Performer?
A.

Yes, with a little fine-tuning. In the paper, transferring pretrained weights directly first dropped accuracy to 0.07, and it recovered with far fewer fine-tuning steps than the original training. Because it approximates softmax, it is easier to transfer than linear attention, which replaces softmax with a different function.

References

  1. K. Choromanski, V. Likhosherstov, D. Dohan, X. Song, A. Gane, T. Sarlos, P. Hawkins, J. Davis, A. Mohiuddin, L. Kaiser, D. Belanger, L. Colwell, and A. Weller, "Rethinking Attention with Performers," ICLR, 2021.
  2. A. Katharopoulos, A. Vyas, N. Pappas, and F. Fleuret, "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention," ICML, 2020.
  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.
  4. google-research/performer (the paper's implementation)