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 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 , 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 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 . 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.

