AI Logic

Attention Mechanisms

Sparse Attention

Updated:

Structure of sparse attention. The left shows the computation flow (select positions to attend to, compute attention only over those positions, combine the heads); the right shows which entries of the N × N attention matrix are computed for the strided and fixed patterns, color-coded by the two heads

What is sparse attention?

Sparse attention is a method that computes only a predefined subset of the N×NN \times N attention matrix. It was proposed in 2019 by Child et al. at OpenAI in the paper "Generating Long Sequences with Sparse Transformers", and the model built on it is called the Sparse Transformer.

Standard multi-head attention computes a weight for every pair of positions in the sequence, so its computation and memory grow with the square of the sequence length NN. When sequences reach tens of thousands of elements, as with an image flattened pixel by pixel (12,288 for a 64×6464 \times 64 image with 3 color channels) or a raw audio waveform, this N2N^2 exceeds what can be computed.

Sparse attention limits the positions each position attends to to roughly N\sqrt{N} of the whole sequence.

  • Head 1: attends to nearby positions (the few preceding positions, or the same block).
  • Head 2: attends to distant positions, skipping through them at a fixed interval.

The patterns are designed so that any position a single head cannot see is reachable by passing through the two heads in turn, which lets information flow even between positions far apart. It works like combining a local train (which stops at every nearby station) with an express (which stops only at certain stations): any station can be reached with few transfers.

The right side of the figure at the top of the article shows the positions that are computed. Multi-head attention computes every cell, whereas sparse attention computes only the colored cells.

Theory

The paper rewrites attention in terms of the set SiS_i of positions that position ii attends to (Eqs. (2)–(4) of the paper).

a(xi,Si)=softmax ⁣((Wqxi) KSi⊤d)VSia(\boldsymbol{x}_i, S_i) = \mathrm{softmax}\!\left(\frac{(W_q \boldsymbol{x}_i)\, K_{S_i}^\top}{\sqrt{d}}\right) V_{S_i} KSi=(Wkxj)j∈Si,VSi=(Wvxj)j∈SiK_{S_i} = (W_k \boldsymbol{x}_j)_{j \in S_i}, \qquad V_{S_i} = (W_v \boldsymbol{x}_j)_{j \in S_i}

Here Wq,Wk,WvW_q, W_k, W_v are the weights that produce the queries, keys and values, and dd is the length of the queries and keys. The formula is the same as scaled dot-product attention, except that the keys and values are restricted to the positions in the set SiS_i.

In a model that generates one element at a time from left to right (an autoregressive model), standard attention uses Si={j:j≤i}S_i = \{j : j \le i\} (the position itself and all earlier positions). Sparse attention narrows this down as follows.

  1. Choose the number of heads pp: the paper uses p=2p = 2.
  2. Choose a set of attended positions Ai(m)A_i^{(m)} for each head: Ai(m)⊂{j:j≤i}A_i^{(m)} \subset \{j : j \le i\}, with a size proportional to Np\sqrt[p]{N}.
  3. Make sure every position is reachable: shape the sets so that for every pair j≤ij \le i, information can flow from jj to ii along a path of at most p+1p + 1 steps.
  4. Compute attention in each head only within its own set.

The paper proposes two patterns that use a stride ll (chosen close to N\sqrt{N}).

PatternHead 1: Ai(1)A_i^{(1)}Head 2: Ai(2)A_i^{(2)}Suited to
strided{t,t+1,…,i}\{t, t+1, \dots, i\}, t=max⁡(0,i−l)t = \max(0, i - l): itself and the preceding ll positions{j:(i−j) mod l=0}\{j : (i - j) \bmod l = 0\}: every ll-th positionData with periodicity matching the stride, such as images and music
fixed{j:⌊j/l⌋=⌊i/l⌋}\{j : \lfloor j / l \rfloor = \lfloor i / l \rfloor\}: positions in the same block{j:j mod l∈{t,…,l}}\{j : j \bmod l \in \{t, \dots, l\}\}, t=l−ct = l - c: the last cc positions of each blockData without periodicity, such as text

The cc in fixed is a hyperparameter. With a stride of 128 and c=8c = 8, every position after 128 can attend to positions 120–128. The last cc positions of each block act as summaries that carry the block's content forward.

There are three ways to combine the results of the two heads (Eqs. (6)–(8) of the paper).

  • Alternating by layer: each residual block rr uses A(r mod p)A^{(r \bmod p)}.
  • Union: a single head attends to the union of the two sets, ⋃mA(m)\bigcup_m A^{(m)} (merged head).
  • Parallel: as in multi-head attention, several heads are computed in parallel and concatenated.

Why performance holds up despite less computation

With strided, each position attends to l+1l + 1 positions in head 1 and about N/lN / l positions in head 2. Setting l≈Nl \approx \sqrt{N} makes both about N\sqrt{N}, so the total cost is O(NN)O(N\sqrt{N}). For N=16,384N = 16{,}384, this is about 2.1 million pairs (NNN\sqrt{N}) versus about 270 million pairs (N2N^2) for standard attention, roughly a 128-fold reduction.

The paper gives two reasons why performance still holds up.

  • Many learned attention patterns are already sparse: when a 128-layer standard Transformer was trained on images (CIFAR-10) and its attention weights were visualized, most layers placed weight on only a few positions (Figure 2 of the paper). Early layers attended to nearby positions like a convolution, while layers 19 and 20 attended to positions split along rows and columns.
  • The whole sequence is reachable in two steps: head 1 gathers information from nearby positions and head 2 carries it far, so stacking layers lets information from any position propagate.

Choose the attention pattern to match the structure of the data. In strided, "every ll-th position" corresponds to "the same column one row down" in an image, so using the image width as the stride naturally captures vertical and horizontal relationships. In text, positions every ll steps apart carry no special meaning, so fixed, which routes information through block representatives, is the better fit.

Beyond reducing the number of computed positions, the paper combines several techniques for training on long sequences.

  • GPU kernels that compute only the needed blocks: positions that are not attended to are never computed, and neither is the upper-right triangle of the matrix (future positions).
  • Recomputing attention weights: the weights are recomputed during backpropagation to save memory (gradient checkpointing).
  • Residual blocks for deep networks: layer normalization is placed at the entrance of the residual branch (the same idea as Pre-LN), and the initial output-side weights are scaled by 1/2N1/\sqrt{2N} (where NN is the number of layers).
  • Mixed precision training: weights are kept in single precision while everything else is computed in half precision.

Experimental results

The paper compares standard attention (Dense Attention) with the two sparse attention patterns under identical conditions (Table 2 of the paper). Values are bits per byte (lower is better), and Time/Iter is the time per update in seconds.

Dataset (sequence length)Methodbits per byteTime/Iter
Enwik8 (12,288)Dense Attention1.001.31
fixed0.990.55
strided1.130.35
CIFAR-10 (3,072)Dense Attention2.820.54
fixed2.850.47
strided2.800.38
  • Speed: both patterns were faster than standard attention. On Enwik8 (Wikipedia text), fixed was about 2.4 times faster and strided about 3.7 times faster.
  • Performance: when the pattern matched the data, results were on par with or better than standard attention. strided was best on CIFAR-10 images and fixed was best on Enwik8 text, while applying strided to text degraded the result considerably, to 1.13.

In comparisons with other models, it also set new state-of-the-art results at the time (Table 1 of the paper).

DatasetSparse TransformerBest prior result
CIFAR-10 (bits per dim)2.80 (strided, 59M)2.85 (PixelSNAIL)
Enwik8 (bits per byte)0.99 (fixed, 95M)0.99 (Transformer-XL 277M), 1.03 (Transformer-XL 88M)
ImageNet 64×64 (bits per dim)3.44 (strided, 152M)3.52 (SPN 150M)

On Enwik8 it matches Transformer-XL, which has more than twice as many parameters. For raw audio waveforms (12 kHz), a 152M model could be trained on sequences of length 65,536, and reducing the parameters to 3M allowed lengths of 1,048,576 (about one million) (Table 4 of the paper).

Practical considerations

Sparse attention fixes the attention pattern before seeing the data.

Pairs of positions outside the chosen pattern cannot attend to each other directly, no matter how strongly they are related. The paper also notes that some learned attention patterns depend on the data or attend globally, and a fixed sparse pattern cannot reproduce them. If the pattern does not match the data, performance drops sharply, as when strided is applied to text.

Keep the following points in mind when using it.

  • It is only faster with kernels that support sparse computation: passing a mask that hides non-attended positions to PyTorch's F.scaled_dot_product_attention still computes the entire N×NN \times N matrix, so it neither speeds things up nor saves memory. The paper uses dedicated GPU kernels that compute sparsely at the block level.
  • Set the stride ll close to N\sqrt{N}: for images, matching the image width represents vertical relationships directly.
  • Do not make cc too small in fixed: according to the paper, c=1c = 1 greatly reduces expressiveness, while c∈{8,16,32}c \in \{8, 16, 32\} worked well for l∈{128,256}l \in \{128, 256\}. However, the cost increases by a factor of cc relative to strided.
  • Give each head a different part of the block ends: when using multiple heads with fixed, assigning each head a different segment of length cc was reported to work better than having all heads attend to the same segment.

Comparison with other methods

Methods that make attention cheaper for long sequences are easiest to compare by asking which parts of the attention matrix they compute.

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 (Child et al., 2019)Only a predefined subset of pairsSome pairs are not attended toO(NN)O(N\sqrt{N})
Linear attention (Katharopoulos et al., 2020)No matrix is formed (the order of computation changes)Softmax is replaced with another functionO(N)O(N)
FlashAttention (Dao et al., 2022)All pairs, split into small tiles without storing the full matrix in memoryExact (identical values)O(N2)O(N^2) compute, O(N)O(N) extra memory

Sparse attention and FlashAttention can be combined. The FlashAttention paper proposes block-sparse FlashAttention, which computes only predefined blocks, and trains on sequences up to 64K in length.

Other methods that fix the attention pattern in advance include Longformer and BigBird. A rough guide to choosing among them:

  • Data with periodic or grid structure, such as images and audio: strided sparse attention is a good fit.
  • Data without periodicity, such as text: use a pattern like fixed that routes through block representatives.
  • Sequences that are not very long, when exact computation is wanted: use FlashAttention, which leaves no pairs unattended.

PyTorch example

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


def strided_masks(n, l):
    """Attended positions of the two strided heads (True = attend). [n, n], following the equations in Section 4.3 of the paper"""
    i = torch.arange(n).view(-1, 1)  # query positions
    j = torch.arange(n).view(1, -1)  # key positions
    causal = j <= i                   # autoregressive, so no peeking at the future
    a1 = causal & (j >= (i - l).clamp(min=0))    # itself and the preceding l positions
    a2 = causal & ((i - j) % l == 0)             # every l-th position
    return a1, a2


def fixed_masks(n, l, c):
    """Attended positions of the two fixed heads (True = attend)"""
    i = torch.arange(n).view(-1, 1)
    j = torch.arange(n).view(1, -1)
    causal = j <= i
    a1 = causal & (j // l == i // l)             # same block
    a2 = causal & (j % l >= l - c)               # last c positions of each block
    return a1, a2


n, l, c, d = 16, 4, 1, 64
a1, a2 = strided_masks(n, l)
print(a1.sum(dim=1))  # number of positions each position attends to (at most l + 1 = 5)

# Combining by "union" (merged head): a single head attends to both a1 and a2
q = k = v = torch.randn(2, 1, n, d)  # [batch, heads, sequence, d]
merged = a1 | a2
# In the boolean mask of F.scaled_dot_product_attention, True means "attend"
out = F.scaled_dot_product_attention(q, k, v, attn_mask=merged)
print(out.shape)  # torch.Size([2, 1, 16, 64])

# Combining "in parallel": head 1 uses a1, head 2 uses a2
q2 = k2 = v2 = torch.randn(2, 2, n, d)
masks = torch.stack([a1, a2])  # [heads, n, n]
out2 = F.scaled_dot_product_attention(q2, k2, v2, attn_mask=masks)
print(out2.shape)  # torch.Size([2, 2, 16, 64])

# Note: this code only illustrates the patterns; it computes the full N × N matrix and then masks it.
# Actually reducing computation and memory requires dedicated kernels that compute sparsely at the block level.

FAQ

Q. Why doesn't masking alone make it faster?
A.

A mask merely sets some of the already computed N×NN \times N values to −∞-\infty so that their weights become 0; the amount of computation and memory does not change. To gain speed, a dedicated kernel must skip the uncomputed blocks from the start. The paper built GPU kernels that compute sparsely at the block level, and block-sparse FlashAttention in the FlashAttention paper follows the same idea.

Q. How should strided and fixed be chosen?
A.

strided suits data in which related positions occur at regular intervals, such as images and music. Use fixed for data without periodicity, such as text. In the paper, strided degraded considerably to 1.13 bits per byte on Enwik8 text, while fixed reached 0.99, better than standard attention (1.00).

Q. Why is the cost $O(N\sqrt{N})$?
A.

With the stride ll set to about N\sqrt{N}, each position attends to about ll nearby positions and about N/lN / l strided positions, both roughly N\sqrt{N}. Since this holds for each of the NN positions, the total is proportional to NNN\sqrt{N}.

References

  1. R. Child, S. Gray, A. Radford, and I. Sutskever, "Generating Long Sequences with Sparse Transformers," arXiv:1904.10509, 2019.
  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.
  4. PyTorch Documentation, "torch.nn.functional.scaled_dot_product_attention."