{"notes":[{"id":"transformers/longformer","category":"transformers","legacyPath":"transformers/2004-longformer","legacySlug":"2004-longformer","legacyPaths":[],"title":"Longformer","subtitle":"Long Attention Mechanism","author":"Z. Yuan","paperDate":"2020-04-10","publishedOn":"2024-06-13","paperTitle":"Longformer: The Long-Document Transformer","paperUrl":"https://arxiv.org/abs/2004.05150","bibliography":{"title":"Longformer: The Long-Document Transformer","authors":["Iz Beltagy","Matthew E. Peters","Arman Cohan"],"url":"https://arxiv.org/abs/2004.05150","pdfUrl":"https://arxiv.org/pdf/2004.05150","codeUrl":null,"preprint":{"id":"2004.05150","submittedOn":"2020-04-10","url":"https://arxiv.org/abs/2004.05150"},"publication":null,"citation":"@misc{transformerslongformer2020,\n  title = {{Longformer: The Long-Document Transformer}},\n  author = {Iz Beltagy and Matthew E. Peters and Arman Cohan},\n  year = {2020},\n  eprint = {2004.05150},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2004.05150}\n}\n","citationPath":"/content/papers/citations/transformers/longformer.6161015ad149.bib"},"thumbnail":{"src":"/content/papers/assets/220e8ffad580b18d52b08e147bb2f25d6c8de5d7ec8ea111c8d841b0860bc1f5.jpg","width":1584,"height":338},"locale":"en","path":"/content/papers/en/transformers/longformer.5c4d7bd4c148.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solution","text":"Solution","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"autoregressive-modeling","text":"Autoregressive Modeling","depth":3},{"id":"autoencoding-modeling","text":"Autoencoding Modeling","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"autoregressive-experiment-results","text":"Autoregressive Experiment Results","depth":3},{"id":"autoencoding-experiment-results","text":"Autoencoding Experiment Results","depth":3},{"id":"autoregressive-ablation-experiments","text":"Autoregressive Ablation Experiments","depth":3},{"id":"autoencoding-ablation-experiments","text":"Autoencoding Ablation Experiments","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/sparse-transformer","relation":"comparison","topic":"Reducing attention cost on long sequences"},{"id":"transformers/bigbird","relation":"comparison","topic":"Reducing attention cost on long sequences"}]},{"id":"transformers/sparse-transformer","category":"transformers","legacyPath":"transformers/1904-sparse-transformer","legacySlug":"1904-sparse-transformer","legacyPaths":[],"title":"Sparse Transformer","subtitle":"Sparse Attention Mechanism","author":"Z. Yuan","paperDate":"2019-04-23","publishedOn":"2024-06-09","paperTitle":"Generating Long Sequences with Sparse Transformers","paperUrl":"https://arxiv.org/abs/1904.10509","bibliography":{"title":"Generating Long Sequences with Sparse Transformers","authors":["Rewon Child","Scott Gray","Alec Radford","Ilya Sutskever"],"url":"https://arxiv.org/abs/1904.10509","pdfUrl":"https://arxiv.org/pdf/1904.10509","codeUrl":null,"preprint":{"id":"1904.10509","submittedOn":"2019-04-23","url":"https://arxiv.org/abs/1904.10509"},"publication":null,"citation":"@misc{transformerssparsetransformer2019,\n  title = {{Generating Long Sequences with Sparse Transformers}},\n  author = {Rewon Child and Scott Gray and Alec Radford and Ilya Sutskever},\n  year = {2019},\n  eprint = {1904.10509},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1904.10509}\n}\n","citationPath":"/content/papers/citations/transformers/sparse-transformer.961330a17a72.bib"},"thumbnail":{"src":"/content/papers/assets/847fd8e03beeb4395ae629700c5daaf1fa75dd302949008b9c248f7d77a8f9bc.jpg","width":1392,"height":694},"locale":"en","path":"/content/papers/en/transformers/sparse-transformer.0a8593e9aca3.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"the-initial-layers","text":"The Initial Layers","depth":3},{"id":"layers-19-20","text":"Layers 19-20","depth":3},{"id":"various-layers","text":"Various Layers","depth":3},{"id":"layers-64-128","text":"Layers 64-128","depth":3},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"solution-1-fixed-stride","text":"Solution 1: Fixed Stride","depth":3},{"id":"solution-2-fixed-specific-index-tokens","text":"Solution 2: Fixed Specific Index Tokens","depth":3},{"id":"modified-attention-mechanism","text":"Modified Attention Mechanism","depth":3},{"id":"other-optimizations","text":"Other Optimizations","depth":3},{"id":"training-setup","text":"Training Setup","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"cifar-10","text":"CIFAR-10","depth":3},{"id":"enwik8","text":"EnWik8","depth":3},{"id":"imagenet-64x64","text":"ImageNet 64x64","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/longformer","relation":"comparison","topic":"Reducing attention cost on long sequences"},{"id":"transformers/bigbird","relation":"comparison","topic":"Reducing attention cost on long sequences"}]},{"id":"transformers/bigbird","category":"transformers","legacyPath":"transformers/2007-bigbird","legacySlug":"2007-bigbird","legacyPaths":[],"title":"BigBird","subtitle":"BigBird Attention Mechanism","author":"Z. Yuan","paperDate":"2020-07-28","publishedOn":"2024-06-14","paperTitle":"Big Bird: Transformers for Longer Sequences","paperUrl":"https://arxiv.org/abs/2007.14062","bibliography":{"title":"Big Bird: Transformers for Longer Sequences","authors":["Manzil Zaheer","Guru Guruganesh","Avinava Dubey","Joshua Ainslie","Chris Alberti","Santiago Ontanon","Philip Pham","Anirudh Ravula","Qifan Wang","Li Yang","Amr Ahmed"],"url":"https://arxiv.org/abs/2007.14062","pdfUrl":"https://arxiv.org/pdf/2007.14062","codeUrl":null,"preprint":{"id":"2007.14062","submittedOn":"2020-07-28","url":"https://arxiv.org/abs/2007.14062"},"publication":{"venue":"NeurIPS","year":2020,"kind":"conference","url":"https://arxiv.org/abs/2007.14062"},"citation":"@misc{transformersbigbird2020,\n  title = {{Big Bird: Transformers for Longer Sequences}},\n  author = {Manzil Zaheer and Guru Guruganesh and Avinava Dubey and Joshua Ainslie and Chris Alberti and Santiago Ontanon and Philip Pham and Anirudh Ravula and Qifan Wang and Li Yang and Amr Ahmed},\n  year = {2020},\n  eprint = {2007.14062},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2007.14062}\n}\n","citationPath":"/content/papers/citations/transformers/bigbird.ce813f0f87e9.bib"},"thumbnail":{"src":"/content/papers/assets/754a9cb923f6b343d84fb5dd07cf267216fdaf2d7fc8533525701ecf106c6f72.jpg","width":1584,"height":434},"locale":"en","path":"/content/papers/en/transformers/bigbird.cf9d96a854ff.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"lack-of-fundamental-theory","text":"Lack of Fundamental Theory","depth":3},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"architecture-design","text":"Architecture Design","depth":3},{"id":"proof-beforehand","text":"Proof Beforehand","depth":3},{"id":"start-proof","text":"Start Proof","depth":3},{"id":"turing-completeness","text":"Turing Completeness","depth":3},{"id":"limitations-of-sparse-attention","text":"Limitations of Sparse Attention","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"qa-dev","text":"QA-dev","depth":3},{"id":"qa-test-finetune","text":"QA Test finetune","depth":3},{"id":"long-document-summarization-ability","text":"Long Document Summarization Ability","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/sparse-transformer","relation":"comparison","topic":"Reducing attention cost on long sequences"},{"id":"transformers/longformer","relation":"comparison","topic":"Reducing attention cost on long sequences"}]}],"text":"The computational complexity of the Transformer’s self-attention mechanism is $O(n^2)$.\n\nWhen an algorithm has this kind of complexity, it feels as if there is plenty of room to optimize it.\n\nWait, does this introduction sound familiar?\n\n## Problem Definition\n\n![Earlier long-document Transformers by attention pattern, tasks and pre-training; original paper Table 1](/content/papers/assets/6cc4cdd02b1ff33611931ba38cea7013a6b291f292224a3e4f0513091f56317d.jpg)\n\n*Original paper [Table 1](https://arxiv.org/pdf/2004.05150v2): `ltr` means left-to-right; `char-LM`, `other tasks` and `pretrain` are separate columns.*\n\nTo address the computational complexity issue of the original Transformer, researchers have continuously sought optimization methods.\n\nOne approach follows **Transformer-XL**, processing long text in segments and passing memory from earlier segments to later ones.\n\n- [**Transformer-XL: Attentive to Longer Contexts**](/blog/papers/transformers/transformer-xl)\n\nThe limitation concerns Transformer-XL’s directional segment memory and its adaptation to BERT-style bidirectional context. Sliding windows themselves can be bidirectional, as in Longformer.\n\nAnother approach is sparse attention mechanisms, such as the **Sparse Transformer** proposed a year before this paper.\n\n- [**Sparse Transformer: Sparse Attention Mechanism**](/blog/papers/transformers/sparse-transformer)\n\nTable 1 also shows that Blockwise already combined pre-training with QA, while BP-Transformer evaluated machine translation. The gap is a **joint evaluation of long-document language modeling, pre-training followed by fine-tuning, and multiple downstream tasks**, not an absence of all earlier pre-training.\n\nThe motivation for this paper becomes clear:\n\n1. Using “sparse attention mechanisms” for long contexts is a promising approach.\n2. However, the design of the attention pattern needs optimization.\n3. Moreover, pre-training frameworks should be introduced, and generalization across more downstream tasks should be tested.\n\n## Solution\n\n### Model Architecture\n\n![Full, sliding, dilated and local-plus-global attention patterns; original paper Figure 2](/content/papers/assets/220e8ffad580b18d52b08e147bb2f25d6c8de5d7ec8ea111c8d841b0860bc1f5.jpg)\n\n*Original paper [Figure 2](https://arxiv.org/pdf/2004.05150v2) diagrams attention connections, not the entire network architecture.*\n\nThis paper is relatively straightforward to understand because the image above summarizes the core ideas.\n\nFull attention is the reference in the figure; the other three panels show sparse **connection patterns** for long documents:\n\n- The figure (a) shows the original attention mechanism, where each token attends to all other tokens.\n- The figure (b) depicts Sliding Window Attention, where each token attends to a fixed range of tokens before and after it.\n- The figure (c) illustrates Dilated Sliding Window Attention, where each token attends to tokens at fixed intervals before and after it.\n- The figure (d) demonstrates Global+Sliding Window Attention, where, in addition to each token attending to a fixed range of tokens, a few “specific” tokens attend to all other tokens mutually.\n  - The marked positions near the beginning and middle are illustrative. The downstream task determines which tokens receive global attention.\n\nAttention connections scale as $O(n(w+g))$ for window width $w$ and $g$ global tokens. They are linear in length $n$ only while those settings stay bounded.\n\n### Autoregressive Modeling\n\nThe autoregressive experiments use sliding windows with dilation on some heads and a causal mask, so each position reads only the past. The bidirectional diagram cannot be used unchanged for next-token prediction.\n\nSpecifically, smaller dilation rates are used in the lower layers, while larger dilation rates are used in the higher layers, allowing the model to have different receptive fields at different levels.\n\nSome training techniques are also employed. Instead of directly using ultra-long contexts from the beginning, the context length is gradually increased, making it easier for the model to converge.\n\nStarting from shorter sequence lengths and window sizes in the initial stage helps the model quickly learn local details. In each subsequent stage, the authors double both the window size and sequence length, and halve the learning rate, leaving the costly long inputs to the end. This speeds up training and prepares the model to handle longer sequences.\n\nThe model is trained in five stages. In these five stages, the model gradually adapts to processing increasingly long sequences.\n\nThe five-stage schedule starts at 2,048 and ends at 23,040, constrained by GPU memory. It is not the final stage alone that starts at 2,048.\n\n### Autoencoding Modeling\n\nIn addition to comparing autoregressive models, the authors also compare with autoencoding models like BERT.\n\nDue to the high cost of training BERT, the authors choose to continue MLM pretraining from RoBERTa while modifying the original attention mechanism to the Longformer design.\n\nHere, the Sliding Window Attention mechanism is used, as shown in figure (b).\n\nThis training and downstream setup extends the context from RoBERTa's 512 to 4,096 tokens. The authors copy RoBERTa's learned position embeddings to initialize additional positions, then continue MLM pre-training; replacing attention alone would leave the position range too short.\n\nSome tasks need global attention: classification assigns it to `[CLS]`, QA to question tokens, and WikiHop also to answer candidates. A global token attends to every token **and receives attention back**; global attention uses separate Q/K/V projections. This is Figure 2(d). Adding arbitrarily many global tokens would change the cost.\n\n## Discussion\n\n### Autoregressive Experiment Results\n\n![Longformer character-language-model results for small and large models; original paper Tables 2 and 3](/content/papers/assets/f581a8e6b9852ce2fe3b19040d9fe270557fb56b860aad9d4cda134693c93b6e.jpg)\n\n*Original paper [Tables 2 and 3](https://arxiv.org/pdf/2004.05150v2) appear in one imported crop. Lower BPC is better; small models test text8 and enwik8, large models only enwik8.*\n\nFor the small models in Table 2, Longformer reaches **1.10** test BPC on text8 and **1.00** on enwik8, the lowest in those comparison groups.\n\nTable 3 tests only enwik8: Longformer has **102M parameters and 0.99 BPC**, matching the roughly 100M-parameter Sparse Transformer at **0.99**. The 209M-parameter Adaptive Span reaches **0.98**, and the 277M-parameter Compressive Transformer reaches **0.97**. Longformer is not the best large-model BPC in the table.\n\n### Autoencoding Experiment Results\n\n![Longformer-base versus RoBERTa-base across six downstream development sets; original paper Table 7](/content/papers/assets/452e875e0d16e46ccbe05f99c5ad42f3f97835d4e5d540f68608b97b6ab6994f.jpg)\n\n*Original paper [Table 7](https://arxiv.org/pdf/2004.05150v2) mixes metrics: WikiHop/IMDB accuracy, TriviaQA/Hyperpartisan F1, HotpotQA joint F1 and OntoNotes average F1.*\n\nThe table above summarizes the results of all fine-tuning experiments.\n\nLongformer-base beats RoBERTa-base on all six **development sets**. WikiHop rises **72.4→75.0** and Hyperpartisan **87.4→94.8**, while OntoNotes **78.4→78.6** and IMDB **95.3→95.7** change less. Their metrics differ, so these gains should not be added or all called accuracy gains.\n\n- For tasks requiring long contexts (e.g., WikiHop and Hyperpartisan), the performance improvement is particularly significant.\n- For TriviaQA, the improvement is smaller because local context is usually sufficient to answer the questions.\n- For HotpotQA, supporting fact supervision allows the model to easily find relevant context and then focus on the local context, resulting in smaller gains.\n- WikiHop only includes distant supervision for intermediate reasoning chains, and Longformer excels by reasoning over the entire context.\n- IMDB is sentiment classification, where mostly short documents limit long-context gains. OntoNotes is coreference resolution: nearby mentions can often be linked by the chunked baseline. The coreference explanation does not describe IMDB.\n\n### Autoregressive Ablation Experiments\n\n![Window and dilation ablations for character language modeling; original paper Table 4](/content/papers/assets/9bc86f123972d299cbfec0dcb51568030b906e26ea863271ecd7d2c8335121fb.jpg)\n\n*Original paper [Table 4](https://arxiv.org/pdf/2004.05150v2) reports text8 **development BPC** after 150K steps in phase one; this partial-training ordering need not match a full run.*\n\nThe authors conducted two sets of ablation experiments on autoregressive models.\n\nThe first set tests the sliding window design:\n\n- Decreasing w (from 512 to 32), meaning gradually reducing the sliding window size from the bottom layer.\n- Fixed w (=230), meaning using the same sliding window size from start to finish.\n- Increasing w (from 32 to 512), meaning gradually increasing the sliding window size from the bottom layer.\n\nWithin this partial run, increasing $w$ gives **1.21 BPC**, below fixed $w$ at **1.23** and decreasing $w$ at **1.24**.\n\nWith dilation on two attention heads, development BPC falls from **1.21 to 1.20**. The gain is small and belongs to this 150K-step ablation.\n\n\n> [!TIP]\n> \n> These are heads within multi-head attention. The appendix specifies dilation on two heads only, extending their reach without increasing the number of heads.\n> \n\n\n### Autoencoding Ablation Experiments\n\n![Longformer-base WikiHop development ablations; original paper Table 10](/content/papers/assets/e2c0096fcd81b679b4ba4d66194004154ad2173f8c40b1364b546b2124f8d443.jpg)\n\n*Original paper [Table 10](https://arxiv.org/pdf/2004.05150v2) uses **73.8 accuracy** as the reference; rows are separate changes, not a cumulative sequence.*\n\nThe authors conducted a series of ablation experiments on the autoencoding model.\n\nFirst, all experiments were conducted using the Longformer-base model. Unless otherwise specified, all experiments use the same hyperparameters and fine-tune for five epochs.\n\n1. **Longer input**: reducing the limit to 2,048 tokens lowers WikiHop from **73.8 to 73.1** in this setting.\n2. **Global attention and projections**: removing separate global projections lowers **73.8→72.2**; removing global attention as well yields **65.5**. The latter row changes two factors, so all 8.3 points cannot be attributed to just one.\n3. **MLM continuation**: omitting it lowers **73.8→73.2** under this initialization and task setup.\n4. **Fine-tuning time**: extending five epochs to fifteen raises **73.8→75.0**; this row changes the schedule.\n5. **RoBERTa-base control**: at length 512 with full $n^2$ attention, Longformer scores **71.7** versus RoBERTa-base **72.4**. This supports the longer-context explanation without eliminating every training difference.\n6. **Only new position embeddings trained**: freezing RoBERTa during continued MLM and training just the new positions yields **73.5** after normal task fine-tuning, slightly below **73.8** with full continuation.\n\n## Conclusion\n\nWe believe the focus of this paper is on the design of sparse attention mechanisms.\n\nLongformer lets the downstream task decide **which** tokens get a global view; the earlier Sparse Transformer uses fixed sparse connections to achieve something like global reach.\n\nSo which design is better? Longformer does better than several earlier sparse architectures in the reported tables, though some differences are small. These comparisons span different tasks and model sizes: it has the lowest BPC in the small text8/enwik8 groups, while on large enwik8 it matches Sparse Transformer and trails some larger models.\n\nTherefore, the choice depends on the user’s needs (or trying out each architecture could also be considered).\n","imageSizes":{"/content/papers/assets/6cc4cdd02b1ff33611931ba38cea7013a6b291f292224a3e4f0513091f56317d.jpg":{"width":996,"height":572},"/content/papers/assets/220e8ffad580b18d52b08e147bb2f25d6c8de5d7ec8ea111c8d841b0860bc1f5.jpg":{"width":1584,"height":338},"/content/papers/assets/f581a8e6b9852ce2fe3b19040d9fe270557fb56b860aad9d4cda134693c93b6e.jpg":{"width":3116,"height":2475},"/content/papers/assets/452e875e0d16e46ccbe05f99c5ad42f3f97835d4e5d540f68608b97b6ab6994f.jpg":{"width":1224,"height":212},"/content/papers/assets/9bc86f123972d299cbfec0dcb51568030b906e26ea863271ecd7d2c8335121fb.jpg":{"width":916,"height":348},"/content/papers/assets/e2c0096fcd81b679b4ba4d66194004154ad2173f8c40b1364b546b2124f8d443.jpg":{"width":1224,"height":636}}}
