Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Look nearby, plus a few hubs
Full attention compares every word with every other, which becomes too expensive for long documents. Longformer lets each word look only at its neighbours, a sliding window, which is cheap. A few special tokens, such as a question or a summary token, act as hubs that see and are seen by everyone. Information can then travel across the whole document through the hubs. Try the window and Longformer patterns in the demo.
Manuals, logs and contracts run to thousands of tokens. Linear-cost attention lets encoders read them whole on ordinary hardware.
- 1. In a sliding window, a token attends to…
- 2. Global tokens attend to…
- 3. Longformer's cost grows with length…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Sliding window:
- token i attends to j if |i − j| ≤ w, so (2w + 1)L pairs instead of L²;
- L = 4096 with w = 256 gives 2.1 M pairs, 12.5% of full attention;
- for the same number of pairs as full attention over 512 tokens, a ±256 window handles 511 tokens, while over 4096 tokens’ budget it handles 32,704.
- Dilation: attend to |i − j| ≤ w·δ with i − j a multiple of δ. Each layer then reaches w·δ on each side, and higher layers use dilation to reach further.
- Receptive field: stacking windows reaches 2·layers·w·δ + 1; 12 layers with w = 256 reach 6145.
- Global attention:
- chosen tokens (for example [CLS] or the question tokens in QA) attend to all and are attended by all;
- g global tokens add about 2gL pairs;
- they use separate projection matrices for global attention.
- Implementation: banded matrix products (custom kernels) avoid computing the full L × L matrix.
- 1. Pairs for L = 4096, w = 256:
- 2. Reach of 12 layers with w = 256:
- 3. Global tokens in QA are…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Longformer in code
Exercise 1.
- The mask builder combined windows, dilation and a global token correctly.
- Pair and reach formulas gave 2,101,248 and 6145.
Practice.
- Hugging Face
LongformerModeltakesglobal_attention_mask(1 for global tokens). Theallenai/longformer-base-4096checkpoint was initialised from RoBERTa, with position embeddings copied to 4096. - Window sizes are set per layer, and dilation is used in some heads of higher layers for language modelling.
- Longformer-Encoder-Decoder (LED) applies the pattern to long-document summarisation.
- Memory scales linearly, but sparse attention is less efficient per FLOP on GPUs than dense blocks; BigBird and FlashAttention (E12-16, E12-20) are alternatives.
from transformers import LongformerModel, LongformerTokenizerFast
tok = LongformerTokenizerFast.from_pretrained("allenai/longformer-base-4096")
model = LongformerModel.from_pretrained("allenai/longformer-base-4096")
enc = tok(long_text, return_tensors="pt", truncation=True, max_length=4096)
glob = torch.zeros_like(enc.input_ids); glob[:, 0] = 1 # [CLS] is global
out = model(**enc, global_attention_mask=glob)- 1. Hugging Face argument marking global tokens:
- 2. longformer-base-4096 was initialised from…
- 3. Longformer-Encoder-Decoder targets…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Local context through depth. With a window of ±w, one layer connects tokens at most w apart; L layers connect tokens Lw apart. Long-range interactions need many layers, and information passed through many local hops is diluted.
Global tokens as shortcuts.
- A global token attends to every position, and every position attends to it, so any two tokens are at most two attention hops apart through it.
- If the global token itself carries the needed information, as when the task compares a token with the global one, a single hop suffices.
- This is why choosing global tokens by task matters: the question in QA, [CLS] in classification.
Cost and expressiveness. Window plus global attention computes O(L(w + g)) scores, linear in L. Sparse patterns lose some expressiveness compared with full attention, but Zaheer et al. (BigBird, E12-16) showed such patterns with global tokens remain universal approximators of sequence functions.
- 1. With a global token, any two tokens are at most…
- 2. Window-only reach after L layers:
- 3. Window + global cost is…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Can a few global tokens replace full attention?
History.
- I. Beltagy, M. Peters and A. Cohan, “Longformer: the long-document Transformer” (2020).
- Sparse Transformers (Child et al., 2019) earlier used fixed sparse patterns for long sequences.
- BigBird (2020) added random attention and proved universality.
Exercise 2.
- Task: for 32-token sequences (vocabulary 8), decide at the last position whether the last token equals the first. Half the sequences match.
- Model: one attention layer (d = 32) with:
- full attention;
- a sliding window of ±2;
- the same window plus the first token as a global token.
- Training: 400 steps.
| attention | accuracy | pairs computed (of 1024) |
|---|---|---|
| full | 0.925 | 1024 |
| window ±2 | 0.480 | 154 |
| window ±2 + 1 global | 0.940 | 212 |
- The window alone cannot connect the ends: the first token is 31 positions away, out of reach in one layer, so accuracy is chance.
- One global token restores full-attention accuracy with 21% of the pairs, because the last position can attend to it directly.
- The task is tailored to the global token. In real use the global tokens must be chosen to carry the information other tokens need, as Longformer does by making the question global in QA.
Longformer in AI, robotics and aerospace
- Long technical documents: encode whole manuals, incident histories or requirements specifications for search and QA.
- Long telemetry windows: local windows capture fast dynamics while a few summary tokens carry global context.
- Design choice: decide which tokens are global from the task (queries, section headers, summary slots).
References
- I. Beltagy, M. E. Peters, A. Cohan (2020). “Longformer: the long-document Transformer.” arXiv:2004.05150.
- R. Child, S. Gray, A. Radford, I. Sutskever (2019). “Generating long sequences with sparse Transformers.” arXiv:1904.10509.
- M. Zaheer et al. (2020). “Big Bird: Transformers for longer sequences.” Proc. NeurIPS.