Extending Context Window of Large Language Models via Positional Interpolation
Shouyuan Chen, Sherman Wong, Liangjian Chen, Yuandong Tian
Introduction
Large language models (LLMs) typically come with a pre-defined context window size. For example, inputs to LLaMA models (Touvron et al., 2023) must be fewer than 2048 tokens. This pre-set context window limit is frequently exceeded in applications such as conducting long conversations, summarizing long documents, or executing long-term planning. For these applications, LLMs with longer context windows are preferred. However, training an LLM from scratch with long context windows requires significant investments. This naturally leads to a question: Can we extend the context window of an existing pre-trained LLM?
One straightforward approach is to fine-tune an existing pre-trained Transformer with a longer context window. However, empirically, we found that models trained this way adapt to long context windows very slowly. After training for more than 10000 batches, the effective context window saw a minimal increase, moving from 2048 to 2560 (Table 4). This suggests that such method is inefficient for extending to substantially longer context windows.
While certain techniques such as ALiBi (Press et al., 2022) and LeX (Sun et al., 2022) enable length extrapolation of Transformers, i.e. train on short context windows and inference on longer ones, many existing pre-trained LLMs, including LLaMA (Touvron et al., 2023), use positional encodings that have weak extrapolation properties (e.g., RoPE (Su et al., 2021)). Therefore, the applicability of these techniques for extending the context window sizes of such LLMs remains limited.
In this work, we introduce Position Interpolation to enable context window extensions for certain existing pre-trained LLMs, including LLaMA. The key idea is, instead of extrapolation, we directly down-scale the position indices so that the maximum position index matches the previous context window limit in the pre-training stage. See Figure 1 for an illustration. In other words, to accommodate more input tokens, we interpolate the position encodings at neighboring integer positions, utilizing the fact that position encodings can be applied on non-integer positions, as opposed to extrapolating outside the trained positions, which may lead to catastrophic values. We verify our approach theoretically, by showing that the interpolated attention score has a much smaller upper bound ( smaller in LLaMA 7B setting) than the extrapolated one, and is thus much more stable. Therefore, interpolated position encodings are easier for the model to adapt.
Empirically, we found that Position Interpolation is highly effective and efficient, requiring only a very short period of fine-tuning for the model to fully adapt to greatly extended context windows. We present experimental results for extending the context window to up to 32768 from the initial 2048 across 7B to 65B LLaMA models using Position Interpolation. Our results show that
Position Interpolation can easily enable very long context windows (e.g. 32768), requiring only fine-tuning for 1000 steps on the Pile (Gao et al., 2020) to achieve a good quality. The cost of fine-tuning is negligible compared to the pre-training costs. This confirms our hypothesis that it is relatively easy for the models to adapt to interpolated position encodings.
Position Interpolation generates strong models that can effectively make use of much extended context window. We show that models extended by Position Interpolation enjoy significant perplexity gains from greatly extended context windows for text modeling, and we show that the perplexity reduces graceful with the enlargement of context windows. We also applied Position Interpolation in a long text summarization task, and demonstrate competitive performances.
Position Interpolation preserves model quality relatively well for tasks within its original context window sizes. We present a variety of evaluation results for the extended LLaMA models on the original LLaMA benchmark. Compared with original LLaMA models, the extended LLaMA models saw a minor degradation on several standard benchmarks within a 2048 token limit.
Our results highlight the innate ability of Transformer models to “extrapolate to sequence lengths longer than the ones encountered during training” as hypothesized in the seminal work of Vaswani et al. (2017). We reaffirm this hypothesis and suggest that the previously known weakness of extrapolating to longer sequences for language modeling (Press et al., 2022) may be due to direct extrapolation of positional encodings and it can be largely mitigated by interpolating position encodings instead.
Concurrent work. Right before our release, we are informed with a concurrent blogpost (SuperHOT kaiokendev (2023)) that also interpolates positional encoding in RoPE to extend the context window from 2K to 8K. Recently, open source community picks it up in Reddit post https://www.reddit.com/r/LocalLLaMA/comments/14fgjqj/a_simple_way_to_extending_context_to_8k/ and Github Issues https://github.com/ggerganov/llama.cpp/discussions/1965, which shows that fine-tuning with LoRA (Hu et al., 2021) also seems to work well. Our paper shows a full fine-tuning with up to 65B model work well with Position Interpolation, and we also give theoretical explanations why interpolation achieves much more stable results than extrapolation, by showing that the upper bound of interplated attention score is much lower than that of extrapolated ones.
Method
Transformer models require explicit positional information to be injected, typically in the form of positional encodings, to represent the order of inputs. We consider Rotary Position Embedding (RoPE) (Su et al., 2021), which is the position encoding used in the LLaMA model (Touvron et al., 2023). Given a position index and an embedding vector , where is the dimension of the attention head, RoPE defines a vector-valued complex function as follows
is only dependent on relative position through trigonometric functions. Here and are the query and key vector for a specific attention head. At each layer, RoPE is applied on both query and key embeddings for computing attention scores.
2 Direct Extrapolation
While the attention score in RoPE only depends on the relative positions, which is what we want, its extrapolation performance is not great . In particular, when directly extending to larger context windows unseen in the training, the perplexity may shoot up to very high numbers (i.e., ), comparable to untrained models.
Ideally, we want to see the model trained on a context window of size to still work reasonably well on longer context window, but may not have the capability to leverage information that appears beyond . For example, to answer a question located at 3000, the model trained on maximal window size of cannot leverage evidences provided at location 0, but still can leverage the evidences provided at location 2900. In contrast, in reality we see catastrophic behaviors, i.e., question at location 3000 cannot be answered correctly, even if the evidences are located at location 2900.
3 Proposed approach: Position Interpolation (PI)
We call this transformation on the position encoding Position Interpolation. In this step, we reduce position indices from to to match the original range of indices before computing RoPE. Consequently, as inputs to RoPE, the maximum relative distance between any two tokens has been reduced from to . Since we align the ranges of position indices and relative distances before and after extension, we mitigate the effect on attention score computation due to context window extensions, which can allow the model easier to adapt. To further demonstrate this is the case, in the following theorem, we show that the interpolated attention score is well-behaved:
Please check Appendix A for the proof. Intuitively, in LLM pre-training, we know that the attention score behaves well on integer grid and . Therefore, for any interpolation , we have . Note that , the bound becomes:
In comparison, Sec. 3.4.3 in RoPE (Su et al., 2021) yields an extrapolation bound (i.e., it works for all positional distance ):
Notably, our method of rescaling of position indices does not introduce extra weight, or modify the model architecture in any way. This makes it attractive in practical applications, since most infrastructure and optimization for the original model can be reused after the extension.
Fine-tuning. We can further fine-tune the interpolated model using the next token prediction task with interpolated position encodings on the extended context window size using a pre-training corpus such as the Pile (Gao et al., 2020). In the next section, we show that our fine-tuning process only needs tens to hundreds thousands of examples. We also find that the result of the fine-tuning is not sensitive to the choice of examples. The reason may be that the model is only adapting to the new context window during the fine-tuning phase, starting from a good initialization, as opposed to acquiring new knowledge.
Other ways to reduce interpolation/extrapolation bound. From the expression of the interpolation (Eqn. 5) and extrapolation bound (Eqn. 8), a common term is , which is the maximal magnitude of query/key products. If we enforce a regularization on during LLM training, it is possible that the catastrophic extrapolation error can be mitigated or even resolved. In fact, if we apply ridge regression with proper regularization to fit a curve in Fig. 2, the magnitude of extrapolated when can be comparable to that within . To our knowledge, we are not aware of existing LLM pre-training techniques that leverage this regularization and will leave it for future work.
Experiments
We show Position Interpolation can effectively extend context window up to 32 times of the original size, and such extension can be done with only several hundreds of training steps. We show the resulting models are strong LLMs with fully effective long context windows. We demonstrate its performance in a number of tasks including language modeling, passkey retrieval, and long document summarization. We also present benchmark results of the extended models on the original LLaMA evaluation benchmarks.
Model Variants. We extended the pre-trained 7B, 13B, 33B and 65B LLaMA models (Touvron et al., 2023) to various context window of sizes up to 32768, using either direct fine-tuning or Position Interpoloation method. Except for rescaling the position indices for models extended with Position Interpolation, we did not modify LLaMA model architectures (Touvron et al., 2023) in any ways.
Training Procedure. We fine-tune all model variants using the next token prediction objective. We use AdamW (Loshchilov & Hutter, 2019) with and . We use a linear learning rate warmup of 20 steps starting from of the maximum learning rate. For 7B and 13B models, we set the learning rate to and for 33B and 65B models we set the learning rate to . We set the weight decay to zero. For extending 7B, 13B and 33B models to the 8192 context window size, we use 32 A100 GPUs and 64 global batch size. For all other cases we use 128 A100 GPUs and 128 global batch size. We note that the main need of using more GPUs is memory limitation during fine-tuning, and it is possible to use fewer GPUs in certain cases. We train all models using PyTorch (Paszke et al., 2019) with Fully Sharded Data Parallel (Zhao et al., 2023) and Flash Attention (Dao et al., 2022).
If not specified otherwise, for the Position Interpolation method, we fine-tune the models for 1000 steps. For the direct fine-tuning method, we use 10000 steps. We primarily fine-tune using the Pile training dataset (Gao et al., 2020). In Section 3.4 we also compared fine-tuning performance on the RedPajama dataset (Computer, 2023).
2 Long Sequence Language Modeling
We evaluate the long sequence language modeling performance of our extended models and baselines on two datasets: book corpus (PG-19) (Rae et al., 2020) and cleaned Arxiv Math proof-pile dataset (Azerbayev et al., 2022).
We use the test splits of PG19 (Rae et al., 2020) and proof-pile (Azerbayev et al., 2022). For PG19, we use the whole test split consisting of 100 documents. For the proof-pile dataset, we use a random subsample of 128 documents with at least 32768 SentencePiece (Kudo & Richardson, 2018) tokens and truncate to the first 32768 tokens for each test document. We evaluate perplexity at various context window size by using a sliding window approach following Press et al. (2022) with stride .
In Table 1 and Table 2, we report the perplexity results for our models and baselines on the datasets. From the results, we found that models extended with our method enjoy a significantly improved perplexity from longer context window sizes. By increasing the context window size from 2048 to 16384, we observed -0.28 and -0.5 reductions of perplexity for extending LLaMA 7B models on both datasets, -0.27 and -0.48 reductions for extending LLaMA 13B models, and -0.14 and -0.42 reductions for extending LLaMA 33B models. For LLaMA 65B models, we observed -0.12 and -0.3 reductions of perplexity by extending to the 8192 context window size.
In general, we observed a consistent trend of our models achieving better perplexity with longer context windows. This indicates our models can effectively make use of the longer context windows to better predict next tokens in language modeling tasks. Moreover, we found this trend extends to 32768 window size without diminishing on the PG19 dataset for LLaMA 7B and 13B models. This indicates that our method may enable extension to even longer context windows.
In contrast, we observed that models extended via the direct fine-tuning method has shown regression (up to +0.48) or minor improvement (up to -0.12) on the perplexity at longer context windows. This indicates that models extended this way have limited capability of making use of context windows longer than their pre-trained settings.
We saw a minor degradation of the perplexity on the original context window of 2048 for our extended models in some cases. For example, on the Proof-pile dataset, we saw a degradation ranging from 0.01 to 0.05 across all models with extended with Position Interpolation. A small degradation of performance within original evaluation context window is expected since Position Interpolation forces position encodings in original context window to reside in a much narrower region, which may negatively affect the language model’s performance. We present more benchmark results on the original context window size in Section 3.4.
In Table 3 we report the relationship between perplexity and the number of fine-tuning steps for LLaMA 7B model extending to 8192 and 16384 context window sizes using Position Interpolation evaluated on the PG19 dataset. We can see without fine-tuning (at step 0) the model can exhibit certain language modeling capability, as indicated by perplexity for extending to 8192 context window (in contrast, the direct extrapolation method leads to perplexity). With fine-tuning, we observed that the perplexity improves quickly. At 200 steps the models surpassed the original model’s perplexity on 2048 context window size, indicating the models gaining ability of effectively using sequences longer than the pre-training settings for language modeling. At 1000 steps, we can see the models have improved steadily and achieve a significantly better perplexity.
3 Measuring Effective Context Window Size through Passkey Retrieval
We study the effective context window size, i.e. the maximum distance of a token can effectively attend to during inference, of our models after extension. To measure this, we follow a synthetic evaluation task of passkey retrieval proposed by Mohtashami & Jaggi (2023). In this task, the models are asked to recover a random passkey hidden in a long document. See Figure 3 for the format of the document.
Given a language model, we estimate the upper and lower bounds of effective context windows as follows. Suppose the random passkey is tokens away from the end of the input. When a model persistently fails to retrieve the correct passkey value across several independent attempts, it suggests that the effective context window size of the model is less than . Conversely, if a model consistently succeeds in retrieving the correct passkey value, we deduce that the effective context window size of the model is at least .
We evaluate the 7B and 33B LLaMA model variants that are extended via Position Interpolation or direct fine-tuning. For each model, we use 32 different uniformly spaced in the targeted context window and run the above tests for 10 times for each , where each time a random passkey of 5 random digits is used. In Table 4, we report as a function of the number of fine-tuning steps, where is defined as the maximum such that, for all , the model has a success rate of at least 20% on .
We can see that models extended via Position Interpolation all successfully attain their desired extension objectives in terms of effective context window sizes, indicating by the effective context window size reaching maximum , after merely fine-tuning for 200 steps, consistently across both 7B and 33B model sizes and up to 32768 context windows. In contrast, LLaMA models that are extended via direct fine-tuning only saw a minimal increase of the effective context window size from 2048 to 2560, even after fine-tuning for more than 10000 steps, with no clear indication of an acceleration in the increase of window size.
4 Benchmarks on Original Context Window Size
We evaluate the models extended by Position Interpolation on several standard benchmark tasks within the original context window size of 2048. The evaluation results are listed in Table 5. From the results, we saw that models extended to 8192 produce comparable results on the original benchmark which is designed for a much smaller context window, with a degradation of up to 2% on the benchmark tasks, for both 7B and 33B model sizes. Models extended to longer context windows regressed more on the benchmarks, but still in reasonable ranges for most tasks. We also note that the choice of fine-tuning datasets does not seem to lead significant difference in the benchmark performances, which may be due to the limited number of fine-tuning steps used in our method. The regression on benchmark tasks is consistent with our observation on perplexity regression in Section 3.2.
5 Long Document Summarization
In this task, we evaluate our models’ performance on the long document summarization task. In particular, we consider the GovReport (Huang et al., 2021) dataset, which contains 17457 documents for training and 972 documents for evaluation. Each document comes with a human generated summary. We truncate all input documents to their first 15000 tokens.
We fine-tune the LLaMA models extended with Position Interpolation with a context window of 16384. Note the rescaling of position indices are still required during this fine-tuning step. We first format the raw document using the prompt template in Figure 4, and then concatenate the prompt with the ground-truth summary (truncate to 1000 tokens) associated with each document. We fine-tune the model using the next token prediction task with the above setup for 10 epochs. The losses from the input prompt proportion of training examples are excluded during our fine-tuning.
We use a generation temperature of 0.5 and as our inference parameter to generate a summarization of each document in the test set. The final output is truncated at 1000 tokens. We used the ROUGE-1/ROUGE-2/ROUGE-L scores (Lin, 2004) as the evaluation metrics to evaluate the models’ outputs vs the ground-truth summaries.
In Table 6 we report our evaluation results. We have also included results from two baselines in existing SCROLLS Leaderboard (Shaham et al., 2022; Ainslie et al., 2023). In general, we have obtained competitive R1 score among other models with minimal tuning of hyper-parameters. This result suggests our models with 16384 context window can effectively handle the long document summarization task.
Related Work
Retrieval-augmented LLM. One line of work extends LLMs by augmenting it with retrieval modules which fetch related documents and include the retrieval results into the input context of an LLM (Karpukhin et al., 2020; Guu et al., 2020; Izacard et al., 2022; Jiang et al., 2022; Khattab et al., 2021; Santhanam et al., 2022). Our work is complementary to these works as our extended context window allows more documents being included in the input. In addition, with an unmodified attention mechanism and model architecture, our method may be more versatile as it can natively handle tasks beyond retrieval oriented ones, such as long document summarization, few-shots learning, etc.
Recurrent Transformers and Memory Transformers. Several works add memory capabilities to Transformers through recurrence, which increase the models’ capability of handling very long sequences (Bulatov et al., 2022; Wu et al., 2020; Dai et al., 2019; Wu et al., 2022; Martins et al., 2021; Mu et al., 2023). One limitation of these works is that they only allow attending to a lossy compressed version of past inputs. Mu et al. (2023) suggested that this may prevent models from remembering specific details in the past inputs. In contrast, our work allows attending to all previous tokens, preserving all details without compression, albeit with higher inference costs. Mohtashami & Jaggi (2023) proposed landmark attention which allows full random access to any chunk of the input through introducing landmark tokens. Our work allows full access of the entire input through unmodified attention, which may be useful for tasks such as summarization.
Approximated Multi-head Attention. There is a large body of research that focuses on decreasing the memory and computational complexity of the multi-head attention (MHA) mechanism through approximation or sparsification (Child et al., 2019; Zaheer et al., 2020; Beltagy et al., 2020; Wang et al., 2020; Choromanski et al., 2021; Kitaev et al., 2020; Ren et al., 2021). Although not the focus of this work, as these methods are not used in LLaMA (Touvron et al., 2023), we note that our method is compatible with most of them since our changes are restricted to position encodings, and not attention mechanisms.
Length Extrapolation. A recent line of research aims to train Transformers models on short sequences and inference on longer (Press et al., 2022; Sun et al., 2022; Haviv et al., 2022). However, these methods have not been applied in some of the largest language models such as LLaMA (Touvron et al., 2023), or OPT (Zhang et al., 2022). This has prevented them from enabling length extrapolation of many pre-existing pre-trained language models. Our work focuses on extending existing LLMs, which can save substantial pre-training costs. In addition, our method preserves the quality of the original models, even for small context window tasks, since it does not deviate far from existing definitions of position encoding or attention mechanisms.
Interpolation. The most related technique to ours is proposed by Dosovitskiy et al. (2021) in their work on Vision Transformers, where the authors proposed to linearly interpolate learnt position embeddings to support higher resolution, which translates to an increased number of input embeddings, in the fine-tuning stage. The interpolated position embedding weights are used as initialization in the fine-tuning process for the newly added positions. Our work differs from their work in several ways (1) Instead of interpolating position embeddings, our method interpolates position indices, which is more suitable for RoPE like position encodings and may require less training since no trainable parameters are added. (2) We report successful results of extending the context window to 32 times while Dosovitskiy et al. (2021) explored up to 4 times. Our results extend theirs in exploring the upper limit of context window extension via interpolation. (3) We evaluated and confirmed the effectiveness of Position Interpolation for extending context windows for language models.
We believe our results, in conjunction with (Dosovitskiy et al., 2021), provide empirical evidence on Transformer’s remarkable ability of handling significantly longer sequences beyond training. Further, we conjecture that a method similar to theirs is directly applicable in LLMs with learnable position embeddings such as OPT (Zhang et al., 2022) and we plan to investigate this in the future.
Conclusions
Position Interpolation can effectively extend LLaMA models’ context window to be significantly larger, using minimal fine-tuning. The extended models are fully capable to perform a variety of tasks on the extended context windows, and preserve its original ability relatively well for tasks within the original extended models, making them good choices of generic language models for both long and short input prompts. Further, models extended by Position Interpolation can reuse most pre-existing infrastructure and optimization, making this method attractive in many practical applications. We believe that Position Interpolation is a general method that could be apply to other types of position encodings, which can allow extension for more types of LLMs, and we plan to investigate in such directions in the near future.
Acknowledgements
We thank Mike Lewis for his input on evaluation.
References
Appendix A Proof
where and . Multiplying Eqn. 9 with and Eqn. 10 with and subtract, we get:
Note that when and , , therefore and we have: