Paper commentary
Longformer: The Long-Document Transformer
- Problem Full self-attention scales quadratically with input length, so standard Transformers cap long inputs and long documents must be split, truncated or retrieved in pieces.
- Method Replaces full self-attention with windowed, dilated and task-chosen global attention whose cost grows linearly with input length, then continues pretraining from RoBERTa and finetunes on document tasks.
- Results Reached 75.0 accuracy on the WikiHop development set for Longformer-base, against 72.4 for RoBERTa-base.
Why full self-attention blocks long documents
Full self-attention costs time and memory that grow with the square of the input length, so a standard Transformer cannot take a long document in one pass. BERT-style pretrained models are typically limited to 512 tokens, so practitioners split a document into pieces, truncate it, or first retrieve passages and then read them. Splitting can cut across information that spans pieces, and the workarounds that recover it often depend on task-specific architectures.
The study asks whether a sparse attention pattern with linear cost can instead cover the whole input in a single pass, and it tests this as a drop-in replacement for the self-attention of a pretrained Transformer in a transfer learning setting that earlier long-sequence work had left largely unexplored.
Windowed, dilated and global attention
Each token attends to a fixed-size window of neighbouring tokens, with \(w/2\) tokens on each side, so the cost is \(O(n \times w)\) and grows linearly with the input length \(n\). Stacking \(\ell\) such layers gives a top-layer receptive field of about \(\ell \times w\) when \(w\) is the same in every layer, and different layers may use different window sizes to trade efficiency against representational capacity.
Dilation leaves gaps of size \(d\) inside the window, which enlarges the receptive field to \(\ell \times d \times w\) without increasing the computation. Different heads can use different dilation settings, so some heads keep a local view while others reach over longer spans; the authors found this per-head choice improves performance.
A small set of positions chosen per task receives global attention: each such token attends to every token, and every token attends to it. For classification the global position is the classification token, and for QA it is placed on the question tokens. Because the number of global positions is small and does not depend on \(n\), the combined local and global pattern keeps a cost of \(O(n)\).
The authors present this task-specific global attention as a simpler way to add inductive bias than architectures that merge information across smaller chunks.
Longformer keeps two sets of projections, \(Q_s, K_s, V_s\) for sliding window attention and \(Q_g, K_g, V_g\) for global attention, and the global set is initialized with values matching the sliding window set. The underlying operation is the standard scaled dot-product form \[ \mathrm{Attention}(Q,K,V)=\mathrm{softmax}\left(\frac{QK^{T}}{\sqrt{d_k}}\right)V \] and the separate global projections let the model treat the two kinds of attention differently.
Three ways to compute banded attention
The dilated sliding window computes only a fixed number of diagonals of \(QK^{T}\), which makes memory grow linearly with length, but common deep learning libraries have no banded matrix product for this. The implementation therefore needs a custom approach, and the choice determines whether dilation is supported and how much memory is spent.
Longformer-chunks splits Q and K into overlapping blocks of size \(w\) with overlap \(w/2\), multiplies the blocks in one matrix product and masks the diagonals, which is fast but supports only the non-dilated case. Because it also computes some zero values, Longformer-chunks uses twice the memory of an ideally optimized implementation, which the authors judged acceptable for pretraining and finetuning.
Longformer-cuda is a custom CUDA kernel written with the Tensor Virtual Machine, supports dilation and is the most memory-efficient variant, which is why it was used for the character-level language modeling experiments. The authors report that this kernel runs about as fast as highly optimized full self-attention, and they note that a perfectly optimized kernel could be faster than the quadratic computation.
Figure 1 compares runtime and memory of full self-attention with the three Longformer implementations, which underlies the statements about linear memory growth and differences in speed.
Character-level language modeling results
Training uses five phases in which the window size and sequence length double and the learning rate halves, starting at sequence length 2,048 and ending at 23,040 in the last phase. Lower layers use no dilation, and only two heads in the higher layers use a small amount of increasing dilation. Evaluation uses overlapping sequences of 32,256 with a step of 512, and the score is taken on the last 512 tokens of each sequence.
On enwik8 the same small size reaches 1.00 test BPC, against 1.06 for Transformer-XL and 1.02 for Adaptive.
Adaptive at 0.98 and Compressive at 0.97 remain lower, and the authors note these models have more parameters. Only enwik8 was evaluated for the large models, because these experiments are expensive.
Window and dilation choices on text8
Each variant was trained for 150K steps with the phase 1 configuration on a small model trained on text8, and development BPC was compared. Increasing the window from 32 at the bottom layer to 512 at the top gave 1.21 BPC, while decreasing it from 512 to 32 gave 1.24, and a fixed window gave 1.23. Dilation on two heads gave 1.20 BPC, against 1.21 with no dilation.
The authors note that the ordering at 150K steps may not match the ordering at completion, a shortcut they accepted to avoid the cost of running every configuration to the end.
Extending RoBERTa to 4,096 positions
Longformer starts from the released RoBERTa checkpoint and continues masked language modeling, changing only what the attention mechanism requires. The sliding window has size 512, so each token's attention computation matches that of RoBERTa.
RoBERTa's learned position embeddings cover only 512 positions, so the model needs extended embeddings up to 4,096. Instead of random values, the 512 pretrained embeddings are copied several times to fill the longer range. The copy is motivated by analysis of BERT attention heads that attend strongly to the previous or next token, and copying keeps this local structure except at the partition boundaries.
The pretraining corpus includes the Books corpus and English Wikipedia, as in RoBERTa, plus one third of a Realnews subset with documents longer than 1,200 tokens and one third of the Stories corpus. The base and large models are each trained for 65K gradient updates at sequence length 4,096 with batch size 64, maximum learning rate 3e-5, 500 warmup steps and a power 3 polynomial decay, and otherwise follow RoBERTa's hyperparameters.
Masked language modeling measurements
On the authors' development corpus, RoBERTa-base reaches 1.846 BPC, against 1.880 reported for RoBERTa on its own corpus, which the authors read as evidence that their corpus is close to RoBERTa's training distribution. With randomly initialized extra position embeddings, the base Longformer scores 10.299 BPC, and copy initialization brings it to 1.957.
The large model moves from 8.738 to 1.597 under the same change, against 1.496 for RoBERTa-large.
For the base model, 2K gradient updates lower BPC from 1.957 to 1.753, and 65K updates lower it to 1.705. The large model goes from 1.597 at initialization to 1.414 after 2K updates and 1.358 after 65K.
Freezing all RoBERTa weights and training only the new position embeddings gives 1.850 BPC for the base model, against 1.957 at initialization and 1.705 when all weights are trainable. This frozen setting applies only to pretraining; it fixes the RoBERTa parameters and trains the position embeddings, and no task head is involved.
How long inputs reach the task models
The RoBERTa baseline breaks the context into the longest segments it accepts, passes each through the model, and concatenates the activations for further processing. The Longformer variant replaces RoBERTa self-attention with the windowed attention used in pretraining, plus task-motivated global attention with its own projections.
For WikiHop and TriviaQA the question and documents form one sequence, followed by a dataset-specific prediction layer; WikiHop scores candidates with a classification layer, while TriviaQA uses the span loss of Clark and Gardner. Global attention goes to the question tokens and answer candidates for WikiHop, and to the question tokens for TriviaQA.
HotpotQA uses two stages: the first keeps up to 5 paragraphs whose raw score exceeds -3.0, and the second extracts answer spans and evidence sentences from the shortened context. Both stages train with the answer, evidence, paragraph and question-type losses combined in a multitask setup.
Question answering results
The best Longformer-base configuration used a learning rate of 3e-5 and 15 epochs.
The WikiHop gain is largest because that dataset gives only distant supervision over long reasoning chains, which the full context helps with. The TriviaQA gain is smaller because local context is often enough, and HotpotQA gains less because its supporting-fact supervision lets models focus on nearby text.
On the HotpotQA distractor test set, Longformer-large reaches 73.2 joint F1, below HGN-large at 74.2. Longformer places second on the published HotpotQA leaderboard, ahead of all other published entries except HGN.
What WikiHop ablations remove
All ablation runs use Longformer-base fine-tuned for five epochs with identical hyperparameters unless noted, so the reference point is 73.8 rather than the 75.0 of the 15-epoch model.
Other rows show 73.1 for sequence length 2,048 and 73.2 without MLM pretraining, while pretraining only the extra position embeddings gives 73.5. Training for 15 epochs gives 75.0, 1.2 above the reference. In the RoBERTa-like configuration with sequence length 512 and full attention, the model reaches 71.7, which is slightly below RoBERTa-base at 72.4; the authors conclude the gains are not due to extra pretraining alone.
Classification and coreference results
On the IMDB development set, Longformer-base reaches 95.7 accuracy against 95.3 for RoBERTa-base. Only about 13.6% of IMDB documents exceed 512 wordpieces, so smaller gains are expected there, while Hyperpartisan has 645 documents and is relatively long.
On OntoNotes, Longformer-base reaches 78.6 average F1 against 78.4 for RoBERTa-base. The authors found that mentions are typically close together, so a baseline that processes smaller chunks can still link them without cross-chunk interaction. The coreference model replaces RoBERTa with Longformer, extends the sequence length to 4,096, and does not use global attention for this task.
LED architecture and initialization
LED keeps an encoder and a decoder, but the encoder uses the local plus global attention pattern of Longformer, while the decoder uses full attention over all encoded tokens and over previously decoded positions. The encoder applies a local window of 1,024 tokens and global attention on the first <s> token.
LED's parameters are initialized from BART, and its layers and hidden sizes follow BART's architecture, with LED-base at 6 layers and LED-large at 12 layers in each stack. The position embeddings are extended from BART's 1K to 16K tokens by repeatedly copying BART's 1K embeddings, as in the RoBERTa extension.
LED is trained with teacher forcing on gold summaries and decodes with beam search. The arXiv dataset is long-document summarization in the scientific domain, with a 90th percentile document length of 14.5K tokens.
arXiv summarization results
BigBird with 4,096 tokens reaches 46.63, 19.02 and 41.77 on the same metrics.
At 16,384 tokens LED ties BigBird on ROUGE-1 and scores higher on ROUGE-2 and ROUGE-L, which is the comparison the authors describe as a slight outperformance. BigBird starts from and continues pretraining Pegasus, a model designed for summarization, while LED has no pretraining beyond BART.
On the arXiv validation set, ROUGE-1 and ROUGE-2 rise as the input grows from 1K to 4K to 16K, and the authors report that the longer input significantly improves the results.
Limitations
The BigBird comparison is confounded, since the authors note BigBird's pretraining used about 16 times more compute than Longformer's. Longformer-large on WikiHop used only the first 4,096 tokens of context, and TriviaQA documents were truncated at 4,096 wordpieces.
Adding dilation on a few heads hurt the RoBERTa-initialized model, which the authors attribute to incompatibility with the pretrained weights, and they say retraining from scratch might be needed. LED has no pretraining beyond BART, and its 4,096-token result trails BigBird's 4,096-token result.
Hyperparameter searches were minimal, and the Hyperpartisan split was made randomly into 80/10/10 train, dev and test sets. Large character-level models were evaluated only on enwik8. The authors name other pretraining objectives, longer sequences and additional tasks as future work.
Paper info
- Authors
- Iz Beltagy, Matthew E. Peters, Arman Cohan
- Venue
- arXiv · Preprint
- First published
- 2020-4-10
- Added
- 2026-10-20
- Updated
- 2020-12-2
- Version
- v2
- arXiv
- 2004.05150
- Category
- cs.CL
- Original paper terms
- arXiv non-exclusive 1.0
- What we show
- Paper info and commentary
AI commentary is a separate explanation from the original paper and may contain errors. The original paper and figures follow each source's terms of use and any rights noted separately.
Quote from the paper
Iz Beltagy, Matthew E. Peters, Arman Cohan (2020). Longformer: The Long-Document Transformer. arXiv:2004.05150v2. https://arxiv.org/abs/2004.05150v2
BibTeX
@misc{beltagy2020longformer,
title = {{Longformer: The Long-Document Transformer}},
author = {Iz Beltagy and Matthew E. Peters and Arman Cohan},
year = {2020},
eprint = {2004.05150},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/2004.05150v2}
}