AI Logic

Attention Mechanisms

BigBird (Sparse Attention)

Updated:

Structure of BigBird. The left shows the computation flow (Q, K, V are produced, the attended positions are chosen by three componentsβ€”window, global tokens, and randomβ€”and attention is computed). The right shows the attention matrix (N Γ— N) with the three components (random, window, global tokens) and the BigBird pattern formed by overlaying them

What is BigBird

BigBird is a sparse attention mechanism that computes only the cells of the NΓ—NN \times N attention matrix selected by three components: a window, global tokens, and random positions. Zaheer et al. at Google Research proposed it in 2020 in the paper "Big Bird: Transformers for Longer Sequences," presented at NeurIPS 2020.

Models such as BERT use standard multi-head attention, so memory grows with the square of the sequence length NN, and inputs were limited to around 512 tokens. BigBird restricts what each token attends to to the following three kinds.

  • Window: the nearby tokens, w/2w/2 on each side
  • Global tokens: gg tokens (such as [CLS]) that attend to all tokens and are attended to by all tokens
  • Random: rr tokens chosen at random for each token

Because the number of tokens attended to is a constant independent of NN, the complexity is O(N)O(N). In the paper, this made it possible to handle sequences about 8 times longer than before on similar hardware.

What sets BigBird apart is that the pattern of attended positions was chosen from graph theory and backed by theory. If attention is viewed as a graph of "which token attends to which token," random connections have the property that any two nodes can be joined by a short path even with few edges. It is like a word-of-mouth contact network: on top of connections between neighbors, just a few connections to distant acquaintances let a message reach anyone through a handful of people (the so-called "small world").

The right side of the figure at the top of the article shows the computed positions. Overlaying the three components on the left gives the shape of BigBird.

Theory

The paper writes attention in a generalized form using a directed graph DD (Eq. (AT) in the paper). With N(i)N(i) the set of tokens that token ii attends to, the ii-th output is:

ATTND(X)i=xi+βˆ‘h=1Hσ ⁣(Qh(xi) Kh(XN(i))⊀)β‹…Vh(XN(i))\mathrm{ATTN}_D(X)_i = \boldsymbol{x}_i + \sum_{h=1}^{H} \sigma\!\left(Q_h(\boldsymbol{x}_i)\, K_h(X_{N(i)})^\top\right) \cdot V_h(X_{N(i)})

Here Qh,Kh,VhQ_h, K_h, V_h are the functions that produce the query, key, and value of head hh, Οƒ\sigma is a function such as softmax, HH is the number of heads, and XN(i)X_{N(i)} is the matrix of only the tokens in N(i)N(i). If DD is the complete graph, this reduces to standard scaled dot-product attention. The attended positions are represented by an NΓ—NN \times N matrix AA, where A(i,j)=1A(i, j) = 1 means "query ii attends to key jj."

BigBird builds AA as follows (Section 2 and Figure 1 of the paper).

  1. Random: each query attends to rr randomly chosen keys (rr entries with A(i,β‹…)=1A(i, \cdot) = 1). In a random graph, even with a number of edges proportional to NN, the shortest path between any two nodes is only logarithmic in NN.
  2. Window: query ii attends to keys from iβˆ’w/2i - w/2 to i+w/2i + w/2 (A(i,iβˆ’w/2:i+w/2)=1A(i, i - w/2 : i + w/2) = 1). This is because, in text, much of the information comes from nearby tokens.
  3. Global tokens: for gg tokens, set their entire rows and columns to 1. There are two ways to construct them.
  4. Overlay the three: compute only the cells that belong to the random, window, or global component.

The two constructions in step 3 are:

ConstructionGlobal tokensFormula
BigBird-ITC (internal transformer construction)Choose gg existing tokens from the inputA(i,:)=1A(i, :) = 1 and A(:,i)=1A(:, i) = 1 for i∈Gi \in G
BigBird-ETC (extended transformer construction)Add gg new tokens such as [CLS]Extend the matrix to (N+g)Γ—(N+g)(N + g) \times (N + g) and set the added gg rows and columns to 1

ETC adds new places to store context, and in the paper's experiments it performed better than ITC.

Why all three components are needed

The paper shows, both experimentally and theoretically, that each of the three components has its own reason and that leaving any of them out falls short.

Random and window alone do not reach BERT: at length 512, combinations of components were compared with BERT-base using standard attention (Table 1 of the paper). MLM is the pretraining score for predicting masked words, and SQuAD and MNLI are fine-tuned task scores; higher is better for all.

Attended positionsMLMSQuADMNLI
BERT-base (all)64.288.583.4
Random only60.183.080.2
Window only58.376.473.1
Random + window62.785.180.5

Combining random and window helps, but a gap to BERT remains. The last component, global tokens, was derived from the following theory.

With global tokens, expressive power is not lost: the paper proves that attention containing a "star graph," in which every token is connected to one central token, can approximate any continuous sequence-to-sequence function to arbitrary precision (universal approximation), just like standard attention (Theorem 1 of the paper). It also shows that an encoder-decoder with sparse attention is Turing complete (able to express any computation), just like a standard Transformer. The global tokens play the role of this center.

The theory does not say that everything comes for free. Using the task "for each vector, find the farthest vector" as an example, the paper shows that standard attention can solve it in one layer, whereas sparse attention with a number of edges proportional to NN (not only BigBird) needs a number of layers roughly proportional to NN (Section 3.4 of the paper). For problems whose answer requires comparing every pair, sparse attention is at a disadvantage.

Blocks are used to compute quickly on GPUs: GPUs are bad at reading scattered positions one by one. The paper therefore groups queries and keys into blocks of bb and defines the three components at the block level (Appendix D and Figure 3 of the paper). For example, random means "each query block attends to rr key blocks," and window means "block jj attends to blocks jβˆ’1,j,j+1j-1, j, j+1." The window and global parts can be computed as matrix multiplications by reshaping the matrices, which reduces scattered reads. Pretraining of BigBird-ITC used block size b=64b = 64, 2b2b global tokens, a window of 3b3b, and 3b3b random tokens (Table 8 of the paper).

Experimental results

Pretraining: starting from the pretrained weights of RoBERTa, the models were pretrained on masked-word prediction at length 4,096. Bits per character (lower is better) are as follows (Table 10 of the paper).

Modelbaselarge
RoBERTa (length 512)1.8461.496
Longformer (length 4,096)1.7051.358
BigBird-ITC (length 4,096)1.6781.456
BigBird-ETC (length 4,096)1.6111.274

Question answering: base-size models were compared on the validation data (Table 2 of the paper; accuracy for WikiHop, F1 for the others).

ModelHotpotQA (Joint)Natural Questions (LA)TriviaQAWikiHop
RoBERTa63.5-74.372.4
Longformer64.4-75.275.0
BigBird-ITC67.770.879.575.9
BigBird-ETC67.873.978.775.9

In tests of the large models, BigBird achieved the then state-of-the-art results on Natural Questions long answer (LA), TriviaQA, and WikiHop (Table 3 of the paper).

Long-document summarization: only the encoder uses BigBird, while the decoder keeps standard attention, because in summarization the output (about 200 tokens at the median) is much shorter than the input (over 3,000 tokens). The ROUGE-1/2/L scores of the large model initialized from Pegasus, which was pretrained for summarization, are as follows (Table 4 of the paper).

DatasetPegasus (values reported in the paper)BigBird-Pegasus
arXiv44.21 / 16.95 / 38.8346.63 / 19.02 / 41.77
PubMed45.97 / 20.15 / 41.3446.32 / 20.65 / 42.33
BigPatent52.29 / 33.08 / 41.7560.64 / 42.46 / 50.01

Genomics: BigBird was also applied to DNA sequences. In promoter region prediction, where long context helps, F1 rose from the previous best of 95.6 to 99.9 (Table 6 of the paper).

Practical considerations

BigBird reduces computation at the cost of leaving some token pairs unattended.

BigBird pays off only for long sequences. With the paper's settings (block 64, window 3b3b, global 2b2b, random 3b3b), each query block attends to about 8b=5128b = 512 key tokens in total, so for sequences of about 512 tokens the cost is almost the same as standard attention that attends to everything. Theory also shows that problems requiring comparison of every pair cannot be solved without greatly increasing the number of layers.

When using it, keep the following in mind.

  • It is faster only with a program that performs block-sparse computation: passing a mask to PyTorch's F.scaled_dot_product_attention still computes the full NΓ—NN \times N. Use the paper's implementation or BigBirdModel in Hugging Face Transformers (attention_type="block_sparse").
  • Make the sequence length a multiple of the block size: since computation is done in blocks, pad the remainder.
  • Choose between ITC and ETC: if new tokens can be added to the input, ETC gave better results in the paper. ETC requires task-specific design, such as adding global tokens for question tokens or for each paragraph or sentence in question answering.

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)Nearby positions and positions at fixed intervalsSome pairs unattendedO(NN)O(N\sqrt{N})
Longformer (Beltagy et al., 2020)Window plus the rows and columns of selected tokensSome pairs unattendedO(N)O(N)
BigBird (Zaheer et al., 2020)Window, global tokens, and random positionsSome pairs unattendedO(N)O(N)
Linformer (Wang et al., 2020)Shrinks the matrix to NΓ—kN \times kApproximateO(N)O(N)
Performer (Choromanski et al., 2020)Does not form the matrix (approximated with random features)ApproximateO(N)O(N)

Longformer and BigBird share the combination of a window and global tokens; BigBird adds random positions. The paper notes that, even in settings without random attention, its use of relative position representations and of training global tokens with an auxiliary loss (CPC) distinguish it from Longformer.

Guidelines for choosing:

  • To read documents of thousands of tokens with a BERT-style model and also have theoretical backing for expressive power: BigBird fits.
  • To decide the global tokens yourself for the task: Longformer has a simpler mechanism.
  • To speed up exact computation at a few thousand tokens: use FlashAttention, which leaves no pairs unattended.

PyTorch example

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


def bigbird_mask(n, w, g, r, generator=None):
    """Positions attended by BigBird-ITC (True = attend) [n, n]. Section 2 / Figure 1 of the paper written at the token level
    w: window width (w // 2 on each side), g: number of global tokens (the first g), r: number of random keys"""
    i = torch.arange(n).view(-1, 1)
    j = torch.arange(n).view(1, -1)
    window = (i - j).abs() <= w // 2                        # window: A(i, i - w/2 : i + w/2) = 1
    glob = (i < g) | (j < g)                                # global: entire rows and columns set to 1
    rand = torch.zeros(n, n, dtype=torch.bool)
    for q in range(n):                                      # random: each query attends to r keys
        rand[q, torch.randperm(n, generator=generator)[:r]] = True
    return window | glob | rand


n, d = 16, 64
gen = torch.Generator().manual_seed(0)
mask = bigbird_mask(n, w=3, g=2, r=2, generator=gen)
print(mask.sum(dim=1))  # number attended per query (n for global-token rows)

q = k = v = torch.randn(2, 4, n, d)            # [batch, heads, seq, d]
out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)  # True = "attend"
print(out.shape)  # torch.Size([2, 4, 16, 64])

# Note: this computes the full N Γ— N and then masks it, so it is neither faster nor lighter on memory.
# In practice, use Hugging Face Transformers, which has block-sparse computation:
#   from transformers import BigBirdModel
#   model = BigBirdModel.from_pretrained("google/bigbird-roberta-base",
#                                        attention_type="block_sparse",  # "original_full" computes everything
#                                        block_size=64, num_random_blocks=3)

FAQ

Q. Why does adding random positions help?
A.

Because a graph with random connections can join any two nodes by a short path even with few edges. With only a window, information needs many layers to reach distant tokens, but random connections let it travel far in few layers. In the paper's length-512 comparison, combining random and window was also better than either alone (MLM: window only 58.3, random only 60.1, both 62.7).

Q. What is the difference between BigBird-ITC and BigBird-ETC?
A.

They differ in how global tokens are created. ITC makes existing tokens in the input (for example, the first few) global, while ETC adds new tokens such as [CLS]. In the paper's pretraining and question answering, ETC generally gave better results.

Q. Can it be used in a decoder that generates text?
A.

The paper proves theoretically that an encoder-decoder with sparse attention is Turing complete, but in the summarization experiments only the encoder uses BigBird and the decoder keeps standard attention. In summarization the output is much shorter than the input, so the decoder's N2N^2 is less of a problem.

References

  1. M. Zaheer, G. Guruganesh, A. Dubey, J. Ainslie, C. Alberti, S. Ontanon, P. Pham, A. Ravula, Q. Wang, L. Yang, and A. Ahmed, "Big Bird: Transformers for Longer Sequences," NeurIPS, 2020.
  2. I. Beltagy, M. E. Peters, and A. Cohan, "Longformer: The Long-Document Transformer," arXiv:2004.05150, 2020.
  3. J. Ainslie et al., "ETC: Encoding Long and Structured Inputs in Transformers," arXiv:2004.08483, 2020.
  4. google-research/bigbird (official implementation of the paper)