AI Logic

Attention Mechanisms

Longformer (Sliding Window Attention)

Updated:

Structure of Longformer. Left: the computation flow (two sets of linear layers, for the window and for global attention, produce Q, K, V; attention is computed within the window and for global tokens). Right: the computed positions in the N Γ— N attention matrix, showing two patterns β€” a sliding window combined with global tokens, and a dilated sliding window

What is Longformer

Longformer is a Transformer that computes only a band around the diagonal (the window) and the rows and columns of a few tokens in the NΓ—NN \times N attention matrix. It was proposed by Beltagy et al. at the Allen Institute for AI in the 2020 paper "Longformer: The Long-Document Transformer".

Pretrained models such as BERT and RoBERTa use standard multi-head attention, so their compute and memory grow with the square of the sequence length NN, and their input is limited to 512 tokens. Handling a long document meant either truncating it or splitting it into 512-token chunks, processing each separately, and stitching the results together afterward, which loses information that spans chunk boundaries.

Longformer replaces attention with a combination of two kinds:

  • Sliding window: each token attends only to the w/2w/2 tokens on each side of it. This builds contextual representations.
  • Global tokens (global attention): a small set of preselected tokens (the classification [CLS] token, or the question tokens in question answering) attend to every token in the document and are attended to by every token. These gather information from the whole document.

As a classroom analogy, each student talks only with a few classmates seated nearby, while the class representative goes around hearing everyone's opinions and relays them to everyone. Information reaches the whole class with far fewer conversations than if everyone talked to everyone.

The right side of the figure at the top of the article shows the positions that are computed. Standard attention computes every cell, but Longformer computes only the colored cells, so the cost is O(N)O(N). Because only the attention pattern changes and the shapes of the model weights stay the same, training on long documents can continue from RoBERTa's pretrained weights.

Theory

The Longformer paper uses the standard scaled dot-product attention formula (Eq. (1) in the paper) and changes only which position pairs are computed (the attention pattern).

Attention(Q,K,V)=softmax ⁣(QK⊀dk)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

The attention pattern is built from the following three components (Section 3.1 and Figure 2 of the paper).

  1. Sliding window: fix a window size ww; each token attends to 12w\frac{1}{2}w tokens on each side. The cost is O(NΓ—w)O(N \times w), linear in the sequence length.
  2. Dilated sliding window (optional): within the window, attend to every dd-th token. Like dilated convolution, this reaches farther without increasing the cost.
  3. Global tokens: a few task-specific tokens are made global. This attention is symmetric: a global token attends to all tokens, and all tokens attend to it.

In addition, global attention has its own weights: two sets of linear layers produce Q, K, V separately β€” Qs,Ks,VsQ_s, K_s, V_s for window attention and Qg,Kg,VgQ_g, K_g, V_g for global attention. Qg,Kg,VgQ_g, K_g, V_g are initialized with the same values as Qs,Ks,VsQ_s, K_s, V_s.

If the window size ww and dilation dd are the same in every layer, the range seen by the top layer (the receptive field) of an β„“\ell-layer Transformer is:

windowΒ only:β„“Γ—w,dilated:β„“Γ—dΓ—w\text{window only}: \ell \times w, \qquad \text{dilated}: \ell \times d \times w

For example, stacking 12 layers with a window size of 512 lets the top layer receive information from a range of 12Γ—512=6,14412 \times 512 = 6{,}144 tokens.

The number of global tokens is a small constant independent of NN, so together with the window the cost stays O(N)O(N).

Why windows alone can handle long documents

Longformer's two kinds of attention have separate roles.

  • Window attention reaches far by stacking layers: as in convolutional neural networks, each layer sees only nearby tokens, but the visible range widens with every layer. Studies of BERT's attention heads found that many heads attend strongly to nearby tokens such as the immediately preceding or following token, suggesting that little is lost by restricting attention to a local window.
  • Global tokens collect task-relevant information in one place: for classification, [CLS] sees the whole document and summarizes it into a single representation; for question answering, the question tokens can be compared directly with the whole document. The paper notes that windows alone are not flexible enough to learn such task-specific representations.

The paper's experiments confirm that both are needed. On the WikiHop question-answering task, removing the global weights (Qg,Kg,VgQ_g, K_g, V_g) lowers accuracy from 73.8% to 72.2%, and additionally removing the global tokens lowers it to 65.5% (Table 10 of the paper).

To actually compute long sequences, the paper also uses the following techniques.

  • Kernels that compute only the band: the "banded matrix multiplication" that computes only a fixed number of diagonals of QK⊀QK^\top is not available in PyTorch or TensorFlow, so the authors wrote three implementations: a slow loop version (for verification), a fast version that supports only non-dilated windows (used for pretraining and fine-tuning), and a CUDA version built with TVM (used for character-level language modeling).
  • Extending position embeddings by copying: RoBERTa's learned position embeddings go only up to position 512. Longformer extends them to 4,096 and initializes the new positions by repeatedly copying the 512 existing embeddings. This lets training start while keeping RoBERTa's tendency to attend to nearby tokens everywhere except at the copy boundaries.

For character-level language modeling, the window size varies by layer: small windows in the lower layers and larger windows toward the top, with dilation used sparingly on only two heads in the upper layers. This lets the lower layers learn local information well and the upper layers aggregate distant information. In the paper's comparison, widening the window toward the top worked best, and narrowing it did worse.

Experimental results

Character-level language modeling: bits per character (BPC, lower is better) was compared on text8 and enwik8 (Tables 2 and 3 of the paper). Evaluation uses sequences of length 32,256.

DatasetModelParametersTest BPC
text8T1244M1.18
Adaptive Span38M1.11
Longformer41M1.10
enwik8Transformer-XL41M1.06
Adaptive Span39M1.02
Longformer41M1.00
enwik8 (large models)Transformer-XL (24 layers)277M0.99
Sparse Transformer~100M0.99
Longformer102M0.99

The small model achieved the state of the art at the time on both text8 and enwik8. The large model matches the similarly sized Sparse Transformer and is roughly on par with a model that has more than twice as many parameters.

The comparison of window-size configurations (text8, 150K steps, validation BPC; Table 4 of the paper) is as follows.

ConfigurationBPC
Decreasing window toward the top (512 β†’ 32)1.24
Fixed window in all layers (230)1.23
Increasing window toward the top (32 β†’ 512)1.21
No dilation1.21
Dilation on two heads1.20

Pretraining and fine-tuning: starting from RoBERTa, masked language model pretraining was continued for 65K steps with a window size of 512 and a sequence length of 4,096. RoBERTa-base (processing 512-token chunks) was then compared with Longformer-base (validation data; Table 7 of the paper).

TaskMetricRoBERTa-baseLongformer-base
WikiHop (QA)Accuracy72.475.0
TriviaQA (QA)F174.375.2
HotpotQA (QA)Joint F163.564.4
OntoNotes (coreference)Avg. F178.478.6
IMDB (classification)Accuracy95.395.7
Hyperpartisan (classification)F187.494.8

Longformer outperforms RoBERTa on every task, with the largest gains on WikiHop and Hyperpartisan, which require reading the whole document. The gains are small on IMDB, where most documents are shorter than 512 tokens, and on OntoNotes, where related words are close together.

Long-document summarization: the paper also proposes an encoder-decoder model initialized from BART that uses Longformer attention in the encoder (Longformer-Encoder-Decoder, LED). On arXiv paper summarization, LED-large with 16,384 input tokens achieves ROUGE-1/2/L of 46.63/19.62/41.83, on par with or slightly above BigBird with 4,096 input tokens (46.63/19.02/41.77) (Table 11 of the paper).

Practical considerations

Longformer is a method in which a person decides, per task, which tokens get global attention.

Global tokens are specified by the user, not chosen automatically by the model. In the paper, [CLS] is used for classification, the question tokens for TriviaQA, and the question and answer-candidate tokens for WikiHop; no global tokens are used for coreference resolution. If you forget to specify them, information beyond the window arrives only through stacked layers; in the WikiHop comparison, removing both the global tokens and the global weights lowered accuracy by 8.3 points.

Keep the following in mind when using it.

  • It is faster only with a kernel that computes just the band: passing a window-shaped mask to PyTorch's F.scaled_dot_product_attention still computes the full NΓ—NN \times N matrix, so it is neither faster nor lighter on memory. Use the paper's implementation or a library that includes it (such as LongformerModel in Hugging Face Transformers).
  • Pad the sequence length to match the window size: the paper's fast implementation (chunks) splits Q and K into blocks of size ww overlapping by 12w\frac{1}{2}w and computes them with a single matrix multiplication, so libraries pad the input to a multiple of the window size. This implementation also computes some unnecessary values and uses about twice the memory of an ideal implementation.
  • Adding dilation to a pretrained model can hurt: in pretraining from RoBERTa, adding dilation to some heads lowered performance. The paper attributes this to dilation being incompatible with RoBERTa's pretrained weights. Using dilation requires training from scratch.
  • Short documents gain nothing: the paper's pretraining uses a window size of 512. For documents of 512 tokens or fewer, the cost is the same as RoBERTa.

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 (Child et al., 2019)Nearby positions and positions at fixed stridesSome pairs skippedO(NN)O(N\sqrt{N})
Longformer (Beltagy et al., 2020)The window (band) plus rows and columns of selected tokensSome pairs skippedO(N)O(N)
BigBird (Zaheer et al., 2020)Window, global tokens, and random positionsSome pairs skippedO(N)O(N)
Linformer (Wang et al., 2020)Shrinks the matrix to NΓ—kN \times k (projects keys and values to kk)ApproximateO(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

Sparse Transformer mainly targeted autoregressive language models, whereas Longformer's main goal is to be built into bidirectional BERT-style models and used for document tasks starting from pretrained weights. BigBird uses windows and global tokens like Longformer and adds random positions.

Rough guidelines for choosing:

  • Classification or question answering on documents of a few thousand tokens with a pretrained BERT-style model: Longformer fits. Assign global attention to the tokens related to the task's answer.
  • Long sequences in an autoregressive model: window attention also works when restricted to past tokens, but linear attention and Sparse Transformer are also candidates.
  • A few thousand tokens, faster but still exact: use FlashAttention, which does not skip any pairs.

PyTorch example

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


def longformer_mask(n, w, global_idx, dilation=1):
    """Positions Longformer attends to (True = attend) [n, n]. Section 3.1 and Figure 2 of the paper
    w: window size (w // 2 on each side), global_idx: positions of global tokens, dilation: dilation d"""
    i = torch.arange(n).view(-1, 1)  # query positions
    j = torch.arange(n).view(1, -1)  # key positions
    dist = (i - j).abs()
    window = (dist <= (w // 2) * dilation) & (dist % dilation == 0)
    g = torch.zeros(n, dtype=torch.bool)
    g[global_idx] = True
    # Global attention is symmetric: attend to all of a global token's row (attending) and column (attended)
    return window | g.view(-1, 1) | g.view(1, -1)


class LongformerSelfAttention(nn.Module):
    """Small implementation for checking shapes (1 head). Has two sets of Q, K, V: window and global (Section 3.1)"""

    def __init__(self, dim, w):
        super().__init__()
        self.w = w
        self.qkv_s = nn.Linear(dim, 3 * dim)   # Q_s, K_s, V_s: for window attention
        self.qkv_g = nn.Linear(dim, 3 * dim)   # Q_g, K_g, V_g: for global attention
        self.qkv_g.load_state_dict(self.qkv_s.state_dict())  # initialize the same as the window weights
        self.out = nn.Linear(dim, dim)

    def forward(self, x, is_global):
        # x: [B, N, dim], is_global: [N] (True = global token, e.g. [CLS] or question tokens)
        n = x.size(1)
        qs, ks, vs = self.qkv_s(x).chunk(3, dim=-1)
        qg, kg, vg = self.qkv_g(x).chunk(3, dim=-1)
        g = is_global.nonzero().flatten()

        # Ordinary tokens: attend within the window and to the global tokens
        mask = longformer_mask(n, self.w, g)
        y = F.scaled_dot_product_attention(qs.unsqueeze(1), ks.unsqueeze(1), vs.unsqueeze(1), attn_mask=mask).squeeze(1)

        # Global tokens: attend to all tokens with Q_g, K_g, V_g (overwrite their rows)
        y_g = F.scaled_dot_product_attention(qg[:, g].unsqueeze(1), kg.unsqueeze(1), vg.unsqueeze(1)).squeeze(1)
        y = y.clone()
        y[:, g] = y_g
        return self.out(y)


n, dim, w = 16, 64, 4
is_global = torch.zeros(n, dtype=torch.bool)
is_global[0] = True                    # e.g. for classification, make only [CLS] global
attn = LongformerSelfAttention(dim, w)
x = torch.randn(2, n, dim)
print(attn(x, is_global).shape)        # torch.Size([2, 16, 64])
print(longformer_mask(n, w, [0]).sum(dim=1))  # number of positions each token attends to

# Note: this computes the full N x N matrix and then masks it, so it is neither faster nor lighter on memory.
# In practice, use Hugging Face Transformers, which has a band-only implementation:
#   from transformers import LongformerModel
#   model = LongformerModel.from_pretrained("allenai/longformer-base-4096")
#   global_attention_mask = torch.zeros_like(input_ids); global_attention_mask[:, 0] = 1  # 1 = global
#   out = model(input_ids, attention_mask=attention_mask, global_attention_mask=global_attention_mask)

FAQ

Q. How should global tokens be chosen?
A.

Choose the tokens whose output needs information from the whole document to produce the task's answer. In the paper, [CLS] is used for document classification, the question tokens for TriviaQA, and the question and answer-candidate tokens for WikiHop. For coreference resolution (OntoNotes), related words are close together, so no global tokens are used.

Q. Is information beyond the window size completely unusable?
A.

No. A single layer sees only its window, but the visible range widens with each layer: β„“\ell layers reach β„“Γ—w\ell \times w tokens, or β„“Γ—dΓ—w\ell \times d \times w tokens with dilation dd. In addition, through a global token, information can travel anywhere in the document in two steps even within a single layer.

Q. How does it differ from BigBird?
A.

Both combine windows and global tokens, but BigBird also adds a part where each token attends to a few randomly chosen tokens. The BigBird paper proves theoretically that this attention pattern keeps the property, shared by standard attention, of being able to approximate any sequence function.

References

  1. I. Beltagy, M. E. Peters, and A. Cohan, "Longformer: The Long-Document Transformer," arXiv:2004.05150, 2020.
  2. R. Child, S. Gray, A. Radford, and I. Sutskever, "Generating Long Sequences with Sparse Transformers," arXiv:1904.10509, 2019.
  3. M. Zaheer et al., "Big Bird: Transformers for Longer Sequences," NeurIPS, 2020.
  4. allenai/longformer (the paper's implementation)