{"notes":[{"id":"transformers/transformer-xl","category":"transformers","legacyPath":"transformers/1901-transformer-xl","legacySlug":"1901-transformer-xl","legacyPaths":[],"title":"Transformer-XL","subtitle":"Longer Contexts","author":"Z. Yuan","paperDate":"2019-01-09","publishedOn":"2024-06-04","paperTitle":"Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context","paperUrl":"https://arxiv.org/abs/1901.02860","bibliography":{"title":"Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context","authors":["Zihang Dai","Zhilin Yang","Yiming Yang","Jaime Carbonell","Quoc V. Le","Ruslan Salakhutdinov"],"url":"https://arxiv.org/abs/1901.02860","pdfUrl":"https://arxiv.org/pdf/1901.02860","codeUrl":null,"preprint":{"id":"1901.02860","submittedOn":"2019-01-09","url":"https://arxiv.org/abs/1901.02860"},"publication":{"venue":"ACL","year":2019,"kind":"conference","url":"https://arxiv.org/abs/1901.02860"},"citation":"@misc{transformerstransformerxl2019,\n  title = {{Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context}},\n  author = {Zihang Dai and Zhilin Yang and Yiming Yang and Jaime Carbonell and Quoc V. Le and Ruslan Salakhutdinov},\n  year = {2019},\n  eprint = {1901.02860},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1901.02860}\n}\n","citationPath":"/content/papers/citations/transformers/transformer-xl.453b0401a19f.bib"},"thumbnail":{"src":"/content/papers/assets/7529f09b2441c7c7c7cb309fb85cdb425af2ac800f6d2a5b5c6266f000b1e21f.jpg","width":1380,"height":320},"locale":"en","path":"/content/papers/en/transformers/transformer-xl.e8b9d2a001a4.md","headings":[{"id":"defining-the-problem","text":"Defining the Problem","depth":2},{"id":"computational-resource-constraints","text":"Computational Resource Constraints","depth":3},{"id":"context-fragmentation-problem","text":"Context Fragmentation Problem","depth":3},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"new-challenges","text":"New Challenges","depth":3},{"id":"relative-position-encoding","text":"Relative Position Encoding","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"model-performance","text":"Model Performance","depth":3},{"id":"ablation-studies","text":"Ablation Studies","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/roformer","relation":"comparison","topic":"Position and memory in language models"},{"id":"transformers/transformer","relation":"comparison","topic":"Position and memory in language models"}]},{"id":"transformers/roformer","category":"transformers","legacyPath":"transformers/2104-roformer","legacySlug":"2104-roformer","legacyPaths":[],"title":"RoFormer","subtitle":"Rotary Position Embedding","author":"Z. Yuan","paperDate":"2021-04-20","publishedOn":"2024-07-10","paperTitle":"RoFormer: Enhanced Transformer with Rotary Position Embedding","paperUrl":"https://arxiv.org/abs/2104.09864","bibliography":{"title":"RoFormer: Enhanced Transformer with Rotary Position Embedding","authors":["Jianlin Su","Yu Lu","Shengfeng Pan","Ahmed Murtadha","Bo Wen","Yunfeng Liu"],"url":"https://arxiv.org/abs/2104.09864","pdfUrl":"https://arxiv.org/pdf/2104.09864","codeUrl":null,"preprint":{"id":"2104.09864","submittedOn":"2021-04-20","url":"https://arxiv.org/abs/2104.09864"},"publication":{"venue":"Neurocomputing","year":2024,"kind":"journal","url":"https://doi.org/10.1016/j.neucom.2023.127063"},"citation":"@misc{transformersroformer2021,\n  title = {{RoFormer: Enhanced Transformer with Rotary Position Embedding}},\n  author = {Jianlin Su and Yu Lu and Shengfeng Pan and Ahmed Murtadha and Bo Wen and Yunfeng Liu},\n  year = {2021},\n  eprint = {2104.09864},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/2104.09864}\n}\n","citationPath":"/content/papers/citations/transformers/roformer.0fde02c094b2.bib"},"thumbnail":{"src":"/content/papers/assets/ab8dd73daebeab63a89297d61b075d625fc33e9231546a72571b700a37a38cd1.jpg","width":1224,"height":692},"locale":"en","path":"/content/papers/en/transformers/roformer.984d66baebc6.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"absolute-position-sinusoidal","text":"Absolute Position: Sinusoidal","depth":3},{"id":"absolute-position-learned","text":"Absolute Position: Learned","depth":3},{"id":"relative-position-xl-style","text":"Relative Position: XL Style","depth":3},{"id":"relative-position-t5-style","text":"Relative Position: T5 Style","depth":3},{"id":"more-methods","text":"More Methods","depth":3},{"id":"solution","text":"Solution","depth":2},{"id":"model-architecture","text":"Model Architecture","depth":3},{"id":"higher-dimensional-extension","text":"Higher-Dimensional Extension","depth":3},{"id":"long-range-decay","text":"Long-Range Decay","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"comparison-with-other-positional-encodings","text":"Comparison with Other Positional Encodings","depth":3},{"id":"glue-benchmark","text":"GLUE Benchmark","depth":3},{"id":"limitations","text":"Limitations","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/transformer-xl","relation":"comparison","topic":"Position and memory in language models"},{"id":"transformers/transformer","relation":"comparison","topic":"Position and memory in language models"}]},{"id":"transformers/transformer","category":"transformers","legacyPath":"transformers/1706-transformer","legacySlug":"1706-transformer","legacyPaths":[],"title":"Transformer","subtitle":"The Dawn of a New Era","author":"Z. Yuan","paperDate":"2017-06-12","publishedOn":"2024-05-05","paperTitle":"Attention Is All You Need","paperUrl":"https://arxiv.org/abs/1706.03762","bibliography":{"title":"Attention Is All You Need","authors":["Ashish Vaswani","Noam Shazeer","Niki Parmar","Jakob Uszkoreit","Llion Jones","Aidan N. Gomez","Lukasz Kaiser","Illia Polosukhin"],"url":"https://arxiv.org/abs/1706.03762","pdfUrl":"https://arxiv.org/pdf/1706.03762","codeUrl":null,"preprint":{"id":"1706.03762","submittedOn":"2017-06-12","url":"https://arxiv.org/abs/1706.03762"},"publication":{"venue":"NeurIPS (NIPS)","year":2017,"kind":"conference","url":"https://proceedings.neurips.cc/paper_files/paper/2017/hash/3f5ee243547dee91fbd053c1c4a845aa-Abstract.html"},"citation":"@misc{transformerstransformer2017,\n  title = {{Attention Is All You Need}},\n  author = {Ashish Vaswani and Noam Shazeer and Niki Parmar and Jakob Uszkoreit and Llion Jones and Aidan N. Gomez and Lukasz Kaiser and Illia Polosukhin},\n  year = {2017},\n  eprint = {1706.03762},\n  archivePrefix = {arXiv},\n  url = {https://arxiv.org/abs/1706.03762}\n}\n","citationPath":"/content/papers/citations/transformers/transformer.86c0068d96fd.bib"},"thumbnail":{"src":"/content/papers/assets/29a55cb05497bdd9bbb3f3a96b7ed6656fda3552fa6a0fa5eb29e8e899c1acc1.jpg","width":756,"height":1080},"locale":"en","path":"/content/papers/en/transformers/transformer.420ab06f9af4.md","headings":[{"id":"problem-definition","text":"Problem Definition","depth":2},{"id":"solving-the-problem","text":"Solving the Problem","depth":2},{"id":"model-design","text":"Model Design","depth":3},{"id":"input-layer","text":"Input Layer","depth":3},{"id":"positional-encoding","text":"Positional Encoding","depth":3},{"id":"self-attention-mechanism","text":"Self-Attention Mechanism","depth":3},{"id":"multi-head-attention-mechanism","text":"Multi-Head Attention Mechanism","depth":3},{"id":"cross-attention-mechanism","text":"Cross-Attention Mechanism","depth":3},{"id":"feed-forward-network","text":"Feed-Forward Network","depth":3},{"id":"layer-normalization","text":"Layer Normalization","depth":3},{"id":"discussion","text":"Discussion","depth":2},{"id":"why-use-self-attention","text":"Why Use Self-Attention?","depth":3},{"id":"experimental-results-machine-translation","text":"Experimental Results: Machine Translation","depth":3},{"id":"conclusion","text":"Conclusion","depth":2}],"anchorAliases":{},"guide":null,"relatedReading":[{"id":"transformers/flashattention","relation":"next","topic":"Attention memory and computation"},{"id":"transformers/bert","relation":"next","topic":"Pretraining bidirectional language representations"},{"id":"transformers/gpt_1","relation":"next","topic":"From language pretraining to in-context learning"}]}],"text":"[**BERT**](/blog/papers/transformers/bert) has a maximum supported sequence length, not a requirement that every input have exactly the same length. Transformer-XL studies autoregressive language modeling; BERT is an example of a context limit, not the model being directly extended here. But if we could ignore that limit, how would we ideally feed a text to the model?\n\n- **Input the entire text at once, however long it is. Perfect!**\n\n## Defining the Problem\n\nBut that's not feasible.\n\nReality is harsh, with limited computing power and memory. We can't input all the text at once. The authors identify several specific issues:\n\n### Computational Resource Constraints\n\nTraining large models requires substantial computational resources, including high-performance GPUs or TPUs. Memory limits the text length that can be processed at once; too long texts cause memory overflow or excessive computation time. The attention mechanism of Transformers uses memory that grows quadratically with the context length, making it difficult to handle long texts.\n\n### Context Fragmentation Problem\n\n![Paper Figure 1: separate-segment training and a recomputed sliding window at evaluation](/content/papers/assets/cc2dd2b3fce47c4ae0f4ec2848ab01a4c63a03f038675c2621f3eb6deb514c28.jpg)\n\n*Figure 1 shows the vanilla Transformer: training does not pass state across segments, while the evaluation window shifts one token and is recomputed for each prediction.*\n\nTo fit within computational limits, texts are usually segmented into fixed-length chunks. This approach results in the loss of contextual information, hindering the model's ability to make accurate predictions. Fixed-length contexts restrict the model's predictive capacity, leading to suboptimal performance. The lack of cross-segment context information decreases the model's optimization efficiency, failing to capture long-term dependencies in the text.\n\n\n> [!NOTE]\n> \n> Original BERT supports up to 512 tokens. Preprocessing must choose how to split or truncate longer inputs; the model does not automatically preserve an entire long document.\n\n\n## Solving the Problem\n\n### Model Architecture\n\n![Paper Figure 2: Transformer-XL caches prior hidden states during training and reuses extended context during evaluation](/content/papers/assets/7529f09b2441c7c7c7cb309fb85cdb425af2ac800f6d2a5b5c6266f000b1e21f.jpg)\n\n*The dashed box holds old states with gradients stopped. Queries from the new segment can attend to keys and values from both the old and current segments.*\n\nThe authors first address the context fragmentation problem by introducing a recurrence mechanism similar to those used in RNN models. In training, the hidden states from the previous segment are stored and reused when processing the next segment. This allows the model to leverage information from previous segments, effectively capturing long-term dependencies and avoiding context fragmentation.\n\nWhen processing A then B, B can attend to cached hidden states from A and, if memory permits, earlier segments. These are past segments, not future text. Cached states use stop-gradient: forward information crosses segment boundaries, while gradients do not backpropagate through the entire document.\n\nState reuse also speeds evaluation. At the longest tested attention length of 3,800, the paper reports a 1,874× per-token speedup on enwik8 against a sliding-window baseline that recomputes the full window for each prediction. This is neither a universal speedup over every Transformer implementation nor a training-speed result.\n\n### New Challenges\n\nIn a standard Transformer model, sequence order information is provided by position encodings, which indicate each token’s position in the sequence and are input along with the token embeddings.\n\nIf we use the same position encodings in the recurrence mechanism, the model cannot differentiate between identical positions in different segments, leading to performance degradation.\n\nFor example, consider the sentence: **\"The cat sat on the mat.\"** split into two segments:\n\n- Segment A: \"The cat sat\"\n- Segment B: \"on the mat.\"\n\nIn a standard Transformer, each word's position is determined by its absolute position in the sentence. If we use the same position encodings for both segments, the model cannot distinguish the relative positions. \"on\" and \"The\" would both be encoded as position 1, \"the\" and \"cat\" as position 2, etc., confusing the model about their actual positions in the sequence.\n\nAcross the complete sentence, the positions would instead be \"The\" at 1, \"cat\" at 2, \"sat\" at 3, \"on\" at 4, \"the\" at 5, and \"mat\" at 6. Relative positions describe the distances between words: \"cat\" is one position after \"The\"; \"sat\" is two after \"The\" and one after \"cat\"; \"on\" is one after \"sat\" and three after \"The\". Those distances still make sense across the segment boundary.\n\n### Relative Position Encoding\n\nThe authors start by expanding the $QK^T$ attention score. In the article's row-vector notation, $Q_i=(x_i+pos_i)W_Q$ and $K_j=(x_j+pos_j)W_K$, so\n\n$$\nQ_iK_j^T=x_iW_QW_K^Tx_j^T+x_iW_QW_K^Tpos_j^T+pos_iW_QW_K^Tx_j^T+pos_iW_QW_K^Tpos_j^T.\n$$\n\nThe paper writes these four terms in column-vector notation:\n\n![Paper absolute-position formula: four terms of an absolute-position attention score](/content/papers/assets/041f37f68b4507a8d02243f1ee90a52c52eb696dead72012646bdd0b43cb4e3d.jpg)\n\nThese terms represent:\n\n- $E_{x_i}^T W_q^T W_k E_{x_j}$: Content-based attention.\n- $E_{x_i}^T W_q^T W_k U_j$: Attention related to the absolute position encoding of the key vector.\n- $U_i^T W_q^T W_k E_{x_j}$: Attention related to the absolute position encoding of the query vector.\n- $U_i^T W_q^T W_k U_j$: Attention related to the absolute position encoding of both query and key vectors.\n\nThis method has issues when reusing hidden states, as position encodings from different segments mix.\n\nTo resolve this, the authors replace the key's absolute $pos_j$ with the relative vector $R_{i-j}$, and replace the query's $pos_i$ with two learned vectors $u$ and $v$:\n\n$$\nQ_iK_j^T=x_iW_QW_K^Tx_j^T+x_iW_QW_K^TR_{i-j}^T+uW_QW_K^Tx_j^T+vW_QW_K^TR_{i-j}^T.\n$$\n\nThe products $uW_Q$ and $vW_Q$ can be absorbed separately into two learned vectors, still called $u$ and $v$. The position vector has its own key projection, $W_{K,R}$, rather than sharing the content-key projection $W_K$. The resulting four terms are shown in the paper's notation:\n\n![Paper relative-position formula: four terms using relative distance and two learned biases](/content/papers/assets/d740069fbfa93e986c6fb1d6f2c1c76bcfc7b2cbeba89d6ad84d257a996ed81c.jpg)\n\nEach term now has an intuitive meaning:\n\n- $E_{x_i}^T W_q^T W_{k,E} E_{x_j}$: Content-based attention.\n- $E_{x_i}^T W_q^T W_{k,R} R_{i-j}$: Relative position bias related to content.\n- $u^T W_{k,E} E_{x_j}$: Trainable parameter $u$ controlling global content bias.\n- $v^T W_{k,R} R_{i-j}$: Trainable parameter $v$ controlling global position bias.\n\nImprovements include:\n\n- **Replacing Absolute Position Encoding**: Replacing the absolute position encoding $U_j$ used in terms (b) and (d) with their relative counterparts $R_{i-j}$. This indicates that only relative distance matters for determining attention priors. $R$ is a sinusoidal encoding matrix without learnable parameters.\n- **Introducing Trainable Parameters**: Introducing trainable parameters $u$ and $v$ to replace the absolute position encoding of the query vector $U_i$ in terms (c) and (d). This suggests that attention bias for different tokens should remain the same regardless of the query position.\n\nContent and relative-position keys use separate projections, $W_{k,E}$ and $W_{k,R}$. The vectors $u$ and $v$ are independent learned biases. Values do not receive this added relative-position term.\n\nWith these improvements, the authors developed the Transformer-XL architecture.\n\n## Discussion\n\n### Model Performance\n\n![Paper Tables 1 to 4: language-model comparisons on WikiText-103, enwik8, text8 and One Billion Word](/content/papers/assets/a8c660281c95c7f3b46c1a093cc355ad7352aea6ea222f242fda77cdbefba79f.jpg)\n\n*The imported image combines Tables 1–4. WikiText-103 and One Billion Word use perplexity (PPL); enwik8 and text8 use bits per character (BPC). These are different metrics.*\n\nTransformer-XL was applied to word-level and character-level language modeling datasets, including WikiText-103, enwik8, text8, the One Billion Word Benchmark, and Penn Treebank.\n\n- **Table 1: WikiText-103**:\n\n  - A major contemporary word-level benchmark with long-document context.\n  - Contains 103M training tokens from 28K articles.\n  - Attention length is 384 during training and 1600 during evaluation.\n  - Uses adaptive softmax and input representations.\n  - The previous best listed result is **20.5 PPL with 247M parameters**; Transformer-XL Large reaches **18.3 with 257M**. The Standard model has **24.0 with 151M**, so model sizes should not be treated as one controlled ablation.\n\n- **Table 2: enwik8**:\n\n  - Contains 100M bytes of unprocessed Wikipedia text.\n  - Transformer-XL showed significant advantages over RNN-based models.\n  - The 12-layer Transformer-XL gets **1.06 BPC with 41M parameters**, matching the prior 64-layer Transformer at **1.06 with 235M**—about **17%** as many parameters.\n  - The 18-layer model gets **1.03 with 88M**; the 24-layer model gets **0.99 with 277M**. Capacity changes too, so the full gap cannot be attributed to recurrence alone.\n\n- **Table 3: text8**:\n\n  - Contains 100M processed Wikipedia characters with only 26 letters and spaces.\n  - The best enwik8 model and hyperparameters are reused without further tuning; 24-layer Transformer-XL gets **1.08 BPC**, versus **1.13** for the previous 64-layer Transformer in the table.\n\n- **Table 4: One Billion Word Benchmark**:\n  - Tests short-term dependency modeling ability since sentences are shuffled.\n  - Transformer-XL Large gets **21.8 PPL with 0.8B parameters**, versus **23.7 with 1.0B** for Adaptive Input; their model sizes and training setups are not identical.\n\n\n> [!TIP]\n> \n> Perplexity (PPL) is the reciprocal geometric mean of the probabilities assigned to the correct next tokens, or equivalently the exponential of average negative log likelihood. Compare it under the same corpus, tokenization and evaluation protocol; it is not classification accuracy.\n> \n> - **Calculation Formula**\n> \n>   Given a language model's probability $P(W)$ for a sentence $W = w_1, w_2, ..., w_N$, perplexity is calculated as:\n> \n>   $\\text{PPL}(W) = P(W)^{-\\frac{1}{N}} = \\left( \\prod_{i=1}^N P(w_i | w_1, w_2, ..., w_{i-1}) \\right)^{-\\frac{1}{N}}$\n> \n>   For a dataset $D$:\n> \n>   $\\text{PPL}(D) = 2^{-\\frac{1}{N} \\sum_{i=1}^N \\log_2 P(w_i | w_1, w_2, ..., w_{i-1})}$\n> \n>   Here, $N$ is the total number of words in the dataset, and $P(w_i | w_1, w_2, ..., w_{i-1})$ is the conditional probability of word $w_i$. Lower perplexity indicates the model assigns higher probability to the correct word sequence.\n\n\n### Ablation Studies\n\nThe authors examined the effectiveness of the recurrence mechanism and the new position encoding scheme:\n\n1. **Effectiveness of Relative Position Encoding**:\n\n   ![Paper Table 6: WikiText-103 ablations of recurrence, position encoding and full versus half loss](/content/papers/assets/6644b6fe566c026d24e4d6725a6a23b9be807b074eca5ea01a81436406d57189.jpg)\n\n   *`PPL init` uses the training attention length; `PPL best` adjusts evaluation length. The first two blocks use 128M parameters, while the last uses 151M.*\n\n   Shaw et al. is another **relative** position scheme; Vaswani et al. and Al-Rfou et al. use absolute positions. `Full` scores every position in a segment and `Half` scores its later half. The paper says absolute schemes train better with half losses, but this table has no full-loss row for the same absolute scheme; the size of that effect cannot be read directly from it.\n\n   Within the 128M rows using this paper's encoding and full losses, removing recurrence changes best PPL from **26.77 to 29.02**. With recurrence kept, replacing the encoding with Shaw et al.'s changes **26.77 to 27.94**, although evaluation attention lengths also differ. Keeping the encoding and recurrence but switching from full to half losses changes **26.77 to 28.33**. The best row is recurrence plus this encoding plus **full** losses.\n\n   For the 151M model, backpropagation still spans **128** positions. Evaluation attention lengths of **300 / 450 / 640** yield best PPL values **23.35 / 23.16 / 23.09**. That is evidence about a longer evaluation context, not gradients flowing through 640 training positions.\n\n\n> [!TIP]\n> \n> **Full losses** score every position; **half losses** score only the latter half. In a 100-token segment, only the final 50 positions contribute loss, but they can still attend to the earlier half. This avoids scoring positions with too little left context; it does not remove distant information or limit the model to understanding only recent text.\n\n\n\n2. **Effectiveness of the Recurrence Mechanism**:\n\n   ![Paper Table 7: One Billion Word ablations of recurrence and relative position encoding](/content/papers/assets/42e60ccbecbbefeeee25331e2e8c1268227403219048e1ce25f628a2f0b8b1be.jpg)\n\n   The authors use One Billion Word, whose sentence order is shuffled, to focus on shorter dependencies. They train a **20-layer, roughly 0.3B-parameter** model for **400K steps**. Table 7 gives PPL **25.2** for their setup, **25.7** with Shaw et al.'s encoding and **27.1** without recurrence. Reusing state helps even here, consistent with reducing lost context at segment starts.\n\n## Conclusion\n\nTransformer-XL shows strong language-modeling results. It handles longer dependencies more effectively than the RNN and vanilla Transformer baselines studied in the paper, while keeping past segments available as context.\n\nIt also evaluates much faster against the paper's recomputed-window baseline and can generate reasonably coherent long passages. To us, these strengths suggest room for applications in text generation, unsupervised feature learning, and perhaps image and speech modeling. The paper leaves plenty to explore in both improving existing tools and building new ones.\n","imageSizes":{"/content/papers/assets/cc2dd2b3fce47c4ae0f4ec2848ab01a4c63a03f038675c2621f3eb6deb514c28.jpg":{"width":1380,"height":356},"/content/papers/assets/7529f09b2441c7c7c7cb309fb85cdb425af2ac800f6d2a5b5c6266f000b1e21f.jpg":{"width":1380,"height":320},"/content/papers/assets/041f37f68b4507a8d02243f1ee90a52c52eb696dead72012646bdd0b43cb4e3d.jpg":{"width":1282,"height":354},"/content/papers/assets/d740069fbfa93e986c6fb1d6f2c1c76bcfc7b2cbeba89d6ad84d257a996ed81c.jpg":{"width":1210,"height":344},"/content/papers/assets/a8c660281c95c7f3b46c1a093cc355ad7352aea6ea222f242fda77cdbefba79f.jpg":{"width":1390,"height":1018},"/content/papers/assets/6644b6fe566c026d24e4d6725a6a23b9be807b074eca5ea01a81436406d57189.jpg":{"width":1374,"height":536},"/content/papers/assets/42e60ccbecbbefeeee25331e2e8c1268227403219048e1ce25f628a2f0b8b1be.jpg":{"width":968,"height":276}}}
