Self-attention lets every token look at every other token. That is what makes Transformers powerful, and also what makes them expensive: for a sequence of $n$ tokens, each layer computes $n^2$ attention scores. For a sentence that is nothing. For a 20-page legal contract or a long scientific article with thousands of tokens, it quickly becomes too slow and too memory-hungry.
Longformer (Beltagy, Peters & Cohan, 2020) is a Transformer designed for long documents. Its idea is simple: most of what a token needs comes from nearby tokens, so let each token attend only to a local window, plus a few special tokens that see everything. This reading explains the cost problem, the sliding-window idea and why stacking layers recovers long-range information, and the dilated and global attention patterns.
1The cost of full attention
In full self-attention, the score matrix $QK^\top$ has one entry for every pair of tokens: $n\times n$ entries per head, per layer. Both the computation and the memory grow with $n^2$:
- Doubling the length makes attention four times as expensive.
- With $n=512$ there are about 262 thousand scores; with $n=4{,}096$ there are about 16.8 million, per head and per layer.
This is why many Transformer models, such as BERT, are limited to 512 tokens. A longer document must be cut into pieces, and information that spans the pieces is lost.
2Sliding window attention
In sliding window attention, each token attends only to the tokens in a fixed-size window around it: itself and $\tfrac{w-1}{2}$ neighbors on each side (for an odd window size $w$). The attention pattern becomes a band along the diagonal of the attention matrix.
- Each token computes $w$ scores instead of $n$, so the total is about $n\cdot w$: linear in the sequence length.
- The softmax is taken over the tokens in the window only.
- The idea is the same as a convolutional layer: each output depends on a small neighborhood of the input.
3Stacking layers: a growing receptive field
If each token only sees its neighbors, how can information travel across a whole document? The answer is the same as in convolutional networks: stack layers. After one layer, token $i$ contains information from its window. In the next layer, its neighbors' vectors already contain information from their windows, so token $i$ indirectly sees farther.
With window size $w$ (that is, $\tfrac{w-1}{2}$ neighbors per side), the receptive field after $L$ layers covers about
$$L\cdot(w-1)+1 \;\approx\; L\times w \text{ tokens}.$$For example, Longformer uses windows of 512 tokens; with 12 layers, the top layer's receptive field covers several thousand tokens.
4Dilated and global attention
Longformer adds two variations to the basic sliding window.
Dilated sliding window
Instead of attending to the $w$ consecutive neighbors, a token attends to every second (or every $d$-th) token in a wider range, leaving gaps. The number of scores stays the same, but the window reaches $d$ times farther. Longformer uses dilation only in some attention heads of the upper layers, so other heads still focus on the immediate neighborhood.
Global attention
Some tasks need a few tokens to see the whole document. Longformer lets the user mark a small number of tokens as global:
- a global token attends to every token in the sequence, and
- every token attends to the global tokens (the pattern is symmetric).
Which tokens are global depends on the task. For classification, the <cls> token is global, so it can summarize the whole document. For question answering, the question tokens are global, so every part of the document can be compared with the question. Since there are only a few global tokens, the total cost stays linear in $n$.
5Longformer in practice
Language modeling
For language modeling, the window only extends to the left (each token sees itself and earlier tokens in its window), combining the sliding window with the causal mask. The paper evaluates on two character-level language modeling benchmarks, text8 and enwik8 (both made of Wikipedia text), using bits per character (BPC): the average number of bits the model needs to encode each next character. Lower is better.
| Model (small models, test BPC) | text8 | enwik8 |
|---|---|---|
| T12 | 1.18 | 1.11 |
| Transformer-XL | – | 1.06 |
| Reformer | – | 1.05 |
| Adaptive span | 1.11 | 1.02 |
| BP-Transformer | 1.11 | 1.02 |
| Longformer | 1.10 | 1.00 |
Numbers from Beltagy et al. (2020), Table 2. All models have roughly 40M parameters.
Long documents
The authors also took a pretrained RoBERTa model (limited to 512 tokens), replaced its attention with Longformer attention, and continued pretraining. The result handles inputs of up to 4,096 tokens and improved results on tasks with long documents, such as question answering over long Wikipedia articles, because the model no longer has to cut the document into short pieces.
Other approaches to long sequences
- BigBird: combines sliding window, global, and random attention.
- Linear attention methods: approximate the softmax attention so that its cost is linear in $n$.
- FlashAttention: computes exact full attention, but reorganizes the computation so the $n\times n$ matrix is never stored at once, saving a lot of memory and time. It is widely used today.
- Sliding windows in large language models: some recent decoder-only models (e.g., Mistral 7B) use sliding window attention in their layers to make long inputs cheaper.
6Summary
- Full self-attention computes $n^2$ scores per head and layer, which limits input length.
- Sliding window attention lets each token attend to $w$ nearby tokens: cost $O(n\cdot w)$, linear in $n$. The savings require computing only the window, not masking a full matrix.
- Stacking $L$ layers grows the receptive field to about $L\times w$, as in CNNs.
- Dilated windows reach farther at the same cost; global tokens (e.g.,
<cls>, question tokens) attend to and are attended by everything. - Longformer matched or beat comparable models on character-level language modeling and extended pretrained models from 512 to 4,096 tokens.
7Practice
Exercise 1: counting scores
For $n=8{,}192$ tokens, how many attention scores does full attention compute per head and layer? How many does sliding window attention with $w=512$ compute? What is the ratio?
Exercise 2: receptive field
With window size $w=3$ (one neighbor on each side), how many layers are needed before token 1 can be influenced by token 9?
Exercise 3: global tokens
A document has $n=4{,}096$ tokens, the window is $w=512$, and a 20-token question is marked as global. Roughly how many scores are computed? Is this closer to $n\cdot w$ or to $n^2$?
Quick quiz
8Further reading
- Beltagy, Peters & Cohan (2020). Longformer: The Long-Document Transformer. (Section 3 describes the attention patterns.)
- Hugging Face. Longformer documentation. (How sliding window and global attention are used in practice.)
- Weng (2023). The Transformer Family Version 2.0. (A survey of efficient attention methods, for further study.)