YaRN: Efficient Context Window Extension of Large Language Models

Bowen Peng, Jeffrey Quesnelle, Honglu Fan, Enrico Shippole

Introduction

Transformer-based Large Language Models (LLMs) have become the near-ubiquitous choice for many natural language processing (NLP) tasks where long-range abilities such as in-context learning (ICL) has been crucial. In performing the NLP tasks, the maximal length of the sequences (the context window) determined by its training processes has been one of the major limits of a pretrained LLM. Being able to dynamically extend the context window via a small amount of fine-tuning (or without fine-tuning) has become more and more desirable. To this end, the position encodings of transformers are the center of the discussions.

The original Transformer architecture used an absolute sinusoidal position encoding, which was later improved to a learnable absolute position encoding . Since then, relative positional encoding schemes have further increased the performance of Transformers. Currently, the most popular relative positional encodings are T5 Relative Bias , RoPE , XPos , and ALiBi .

One reoccurring limitation with positional encodings is the inability to generalize past the context window seen during training. While some methods such as ALiBi are able to do limited generalization, none are able to generalize to sequences significantly longer than their pre-trained length .

Some works have been done to overcome such limitation. and concurrently proposed to extend the context length by slightly modifying RoPE via Position Interpolation (PI) and fine-tuning on a small amount of data. As an alternative, proposed the "NTK-aware" interpolation by taking the loss of high frequency into account. Since then, two improvements of the "NTK-aware" interpolation have been proposed, with different emphasis:

the "Dynamic NTK" interpolation method for pre-trained models without fine-tuning.

the "NTK-by-parts" interpolation method which performs the best when fine-tuned on a small amount of longer-context data.

The "NTK-aware" interpolation and the "Dynamic NTK" interpolation have already seen their presence in the open-source models such as Code Llama (using "NTK-aware" interpolation) and Qwen 7B (using "Dynamic NTK").

In this paper, in addition to making a complete account of the previous unpublished works on the "NTK-aware", the "Dynamic NTK" and the "NTK-by-part" interpolations, we present YaRN (Yet another RoPE extensioN method), an improved method to efficiently extend the context window of models trained with Rotary Position Embeddings (RoPE) including the LLaMA , the GPT-NeoX , and the PaLM families of models.

YaRN reaches state-of-the-art performances in context window extensions after fine-tuning on less than \sim0.1% of the original pre-training data. In the meantime, by combining with the inference-time technique called Dynamic Scaling, the Dynamic-YaRN allows for more than 2x context window extension without any fine-tuning.

Background and Related Work

The basis of our work is the Rotary Position Embedding (RoPE) introduced in . We work on a hidden layer where the set of hidden neurons are denoted by DD. Given a sequence of vectors x1,,xLRD\mathbf{x}_{1},\cdots,\mathbf{x}_{L}\in\mathbb{R}^{|D|}, following the notation of , the attention layer first converts the vectors into the query vectors and the key vectors:

Next, the attention weights are calculated as

where qm,kn\mathbf{q}_{m},\mathbf{k}_{n} are considered as column vectors so that qmTkn\mathbf{q}_{m}^{T}\mathbf{k}_{n} is simply the Euclidean inner product. In RoPE, we first assume that D|D| is even and identify the embedding space and the hidden states as complex vector spaces:

where the inner product qTk\mathbf{q}^{T}\mathbf{k} becomes the real part of the standard Hermitian inner product Re(qk)\text{Re}(\mathbf{q}^{*}\mathbf{k}). More specifically, the isomorphisms interleave the real part and the complex part

subscriptsubscript𝐱𝑚1𝑖subscriptsubscript𝐱𝑚2⋯subscriptsubscript𝐱𝑚𝐷1𝑖subscriptsubscript𝐱𝑚𝐷\displaystyle\big{(}(\mathbf{x}_{m})_{1},\cdots,(\mathbf{x}_{m})_{|D|}\big{)}\mapsto\big{(}(\mathbf{x}_{m})_{1}+i(\mathbf{x}_{m})_{2},\cdots,((\mathbf{x}_{m})_{|D|-1}+i(\mathbf{x}_{m})_{|D|})\big{)}, (3) \displaystyle\big{(}(\textbf{q}_{m})_{1},\cdots,(\textbf{q}_{m})_{|D|}\big{)}\mapsto\big{(}(\textbf{q}_{m})_{1}+i(\textbf{q}_{m})_{2},\cdots,((\textbf{q}_{m})_{|D|-1}+i(\textbf{q}_{m})_{|D|})\big{)}. (4) To convert embeddings xm,xn\mathbf{x}_{m},\mathbf{x}_{n} into query and key vectors, we are first given R\mathbb{R}-linear operators

In complex coordinates, the functions fq,fkf_{q},f_{k} are given by

where θ=diag(θ1,,θD/2)\mathbb{\theta}=\text{diag}(\theta_{1},\cdots,\theta_{|D|/2}) is the diagonal matrix with θd=b2d/D\theta_{d}=b^{-2d/|D|} and b=10000b=10000. This way, RoPE associates each (complex-valued) hidden neuron with a separate frequency θd\theta_{d}. The benefit of doing so is that the dot product between the query vector and the key vector only depends on the relative distance mnm-n as follows

In real coordinates, the RoPE can be written using the following function

2 Position Interpolation

As language models are usually pre-trained with a fixed context length, it is natural to ask how to extend the context length by fine-tuning on relatively less amount of data. For language models using RoPE as the position embedding, Chen et al. , and concurrently kaiokendev proposed the Position Interpolation (PI) to extend the context length beyond the pre-trained limit. While a direct extrapolation does not perform well on sequences w1,,wLw_{1},\cdots,w_{L} with LL larger than the pre-trained limit, they discovered that interpolating the position indicies within the pre-trained limit works well with the help of a small amount of fine-tuning. Specifically, given a pre-trained language model with RoPE, they modify the RoPE by

where L>LL^{\prime}>L is a new context window beyond the pre-trained limit. With the original pre-trained model plus the modified RoPE formula, they fine-tuned the language model further on several orders of magnitude fewer tokens (a few billion in Chen et al. ) and successfully acheived context window extension.

3 Additional Notation

The ratio between the extended context length and the original context length has been of special importance, and we introduce the notation ss defined by

We also rewrite and simplify Eq. 10 into the following general form:

where g(m),h(θd)g(m),h(\theta_{d}) are method-dependent functions. For PI, we have g(m)=m/s,h(θd)=θd.g(m)=m/s,h(\theta_{d})=\theta_{d}. In the subsequent sections, when we introduce a new interpolation method, we sometimes only specify the functions g(m)g(m) and h(θd)h(\theta_{d}).

Additionally, we define λd\lambda_{d} as the wavelength of the RoPE embedding at dd-th hidden dimension:

The wavelength describes the length of tokens needed in order for the RoPE embedding at dimension dd to perform a full rotation (2π2\pi).

Given that some interpolation methods (eg. PI) do not care about the wavelength of the dimensions, we will refer to those methods as "blind" interpolation methods, while others do (eg. YaRN), which we will classify as "targeted" interpolation methods.

4 Related work

ReRoPE also aims to extend the context size of existing models pre-trained with RoPE, and claims "infinite" context length without needing any fine-tuning. This claim is backed by a monotonically decreasing loss with increasing context length up to 16k on the Llama 2 13B model. It achieves context extension by modifying the attention mechanism and thus is not purely an embedding interpolation method. Since it is currently not compatible with Flash Attention 2 and requires two attention passes during inference, we do not consider it for comparison.

Concurrently with our work, LM-Infinite proposes similar ideas to YaRN, but focuses on "on-the-fly" length generalization for non-fine-tuned models. Since they also modify the attention mechanism of the models, it is not an embedding interpolation method and is not immediately compatible with Flash Attention 2.

Methodology

Whereas PI stretches all RoPE dimensions equally, we find that the theoretical interpolation bound described by PI is insufficient at predicting the complex dynamics between RoPE and the LLM’s internal embeddings. In the following subsections, we describe the main issues with PI we have individually identified and solved, so as to give the readers the context, origin and justifications of each method which we use in concert to obtain the full YaRN method.

If we look at RoPE only from an information encoding perspective, it was shown in , using Neural Tangent Kernel (NTK) theory, that deep neural networks have trouble learning high frequency information if the input dimension is low and the corresponding embeddings lack high frequency components. Here we can see the similarities: a token’s positional information is one-dimensional, and RoPE expands it to an n-dimensional complex vector embedding.

RoPE closely resembles Fourier Features in many aspects, as it is possible to define RoPE as a special 1D case of a Fourier Feature. Stretching the RoPE embeddings indiscriminately results in the loss of important high frequency details which the network needs in order to resolve tokens that are both very similar and very close together (the rotation describing the smallest distance needs to not be too small for the network to be able to detect it).

We hypothesise that the slight increase of perplexity for short context sizes after fine-tuning on larger context sizes seen in PI might be related to this problem. Under ideal circumstances, there is no reason that fine-tuning on larger context sizes should degrade the performance of smaller context sizes.

In order to resolve the problem of losing high frequency information when interpolating the RoPE embeddings, the "NTK-aware" interpolation was developed in . Instead of scaling every dimension of RoPE equally by a factor ss, we spread out the interpolation pressure across multiple dimensions by scaling high frequencies less and low frequencies more. One can obtain such a transformation in many ways, but the simplest would be to perform a base change on the value of θ\theta.

More precisely, following the notations set out in Section 2.3, we define the "NTK-aware" interpolation scheme as follows (see the Appendix A.1 for the details of the deduction).

The "NTK-aware" interpolation is a modification of RoPE by using Eq. 12 with the following functions.

Given the results from , this method performs much better at extending the context size of non-fine-tuned models compared to PI . However, one major disadvantage of this method is that given it is not just an interpolation scheme, some dimensions are slightly extrapolated to "out-of-bound" values, thus fine-tuning with "NTK-aware" interpolation yields inferior results to PI . Furthermore, due to the "out-of-bound" values, the theoretical scale factor ss does not accurately describe the true context extension scale. In practice, the scale value ss has to be set higher than the expected scale for a given context length extension.

We note that shortly before the release of this article, Code Llama was released and uses "NTK-aware" scaling by manually scaling the base bb to 1M.

2 Loss of Relative Local Distances - "NTK-by-parts" interpolation

In the case of blind interpolation methods like PI and "NTK-aware" interpolation, we treat all the RoPE hidden dimensions equally (as in they have the same effect on the network). However, there are strong clues that point us towards the need for targeted interpolation methods.

In this section, we think heavily in terms of the wavelengths λd\lambda_{d} defined in Eq. 13 in the formula of RoPE. For simplicity, we omit the subscript dd in λd\lambda_{d} and the reader is encouraged to think about λ\lambda as the wavelength of an arbitrary periodic function.

One interesting observation of RoPE embeddings is that given a context size LL, there are some dimensions dd where the wavelength is longer than the maximum context length seen during pretraining (λ>L\lambda>L), this suggests that some dimensions’ embeddings might not be distributed evenly in the rotational domain. In such cases, we presume having all unique position pairs implies that the absolute positional information remains intact. On the contrary, when the wavelength is short, only relative positional information is accessible to the network.

Moreover, when we stretch all the RoPE dimensions either by a scale ss or using a base change bb^{\prime}, all tokens become closer to each other, as the dot product of two vectors rotated by a lesser amount is bigger. This scaling severely impairs a LLM’s ability to understand small and local relationships between its internal embeddings. We hypothesize that such compression leads to the model being confused on the positional order of close-by tokens, and consequently harming the model’s abilities.

In order to remedy this issue, given the two previous observations that we have found, we choose not to interpolate the higher frequency dimensions at all while always interpolating the lower frequency dimensions. In particular,

if the wavelength λ\lambda is much smaller than the context size LL, we do not interpolate;

if the wavelength λ\lambda is equal to or bigger than the context size LL, we want to only interpolate and avoid any extrapolation (unlike the previous "NTK-aware" method);

dimensions in-between can have a bit of both, similar to the "NTK-aware" interpolation.

As a result, it is more convenient to introduce the ratio r=Lλr=\frac{L}{\lambda} between the original context size LL and the wavelength λ\lambda. In the dd-th hidden state, the ratio rr depends on dd in the following way:

In order to define the boundary of the different interpolation strategies as above, we introduce two extra parameters α,β\alpha,\beta. All hidden dimensions dd where r(d)<αr(d)<\alpha are those where we linearly interpolate by a scale ss (exactly like PI, avoiding any extrapolation), and the dd where r(d)>βr(d)>\beta are those where we do not interpolate at all. Define the ramp function γ\gamma to be

With the help of the ramp function, the "NTK-by-parts" method can be described as follows.

The "NTK-by-parts" interpolation is a modification of RoPE by using Eq. 12 with the following functions111The interpolation by linear ramp on hh may have alternatives, such as a harmonic mean over θd/s\theta_{d}/s and θd\theta_{d} converted from a linear interpolation on wavelengths. The choice of hh here was for the simplicity of implementation, but both would work..

1𝛾𝑟𝑑subscript𝜃𝑑𝑠𝛾𝑟𝑑subscript𝜃𝑑\displaystyle=\Big{(}1-\gamma\big{(}r(d)\big{)}\Big{)}\frac{\theta_{d}}{s}+\gamma\big{(}r(d)\big{)}\theta_{d}. (20) The values of α\alpha and β\beta should be tuned on a case-by-case basis. For example, we have found experimentally that for the Llama family of models, good values for α\alpha and β\beta are α=1\alpha=1 and β=32\beta=32.

Using the techniques described in this section, a variant of the resulting method was released under the name "NTK-by-parts" interpolation . This improved method performs better than the previous PI and "NTK-aware" 3.1 interpolation methods, both with non-fine-tuned models and with fine-tuned models, as shown in .

3 Dynamic Scaling - "Dynamic NTK" interpolation

In a lot of use cases, multiple forward-passes are performed with varying sequence lengths from 11 to the maximal context size. A typical example is the autoregressive generation where the sequence lengths increment by 11 after each step. There are two ways of applying an interpolation method that uses a scale factor ss (including PI, "NTK-aware" and "NTK-by-parts"):

Throughout the whole inference cycle, the embedding layer is fixed including the scale factor s=L/Ls=L^{\prime}/L where LL^{\prime} is the fixed number of extended context size.

In each forward-pass, the position embedding updates the scale factor s=max(1,l/L)s=\text{max}(1,l^{\prime}/L) where ll^{\prime} is the sequence length of the current sequence.

The problem of (1) is that the model may experience a performance discount at a length less than LL and an abrupt degradation when the sequence length is longer than LL^{\prime}. But by doing Dynamic Scaling as (2), it allows the model to gracefully degrade instead of immediately breaking when hitting the trained context limit LL^{\prime}. We call this inference-time method the Dynamic Scaling method. When it is combined with "NTK-awared" interpolation, we call it "Dynamic NTK" interpolation. It first appeared in public as a reddit post in .

One notable fact is that the "Dynamic NTK" interpolation works exceptionally well on models pretrained on LL without any finetuning (L=LL^{\prime}=L). This is supported by the experiment in Appendix B.3.

Often in the repeated forward-passes, the kv-caching is applied so that we can reuse the previous key-value vectors and improve the overall efficiency. We point out that in some implementations when the RoPE embeddings are cached, some care has to be taken in order to modify it for Dynamic Scaling with kv-caching. The correct implementation should cache the kv-embeddings before applying RoPE, as the RoPE embedding of every token changes when ss changes.

4 YaRN

In addition to the previous interpolation techniques, we also observe that introducing a temperature tt on the logits before the attention softmax has a uniform impact on perplexity regardless of the data sample and the token position over the extended context window (See Appendix A.2). More precisely, instead of Eq. 2, we modify the computation of attention weights into

The reparametrization of RoPE as a set of 2D matrices has a clear benefit on the implementation of this attention scaling: we can instead use a "length scaling" trick which scales both qm\mathbf{q}_{m} and kn\mathbf{k}_{n} by a constant factor 1/t\sqrt{1/t} by simply scaling the complex RoPE embeddings by the same amount. With this, YaRN can effectively alter the attention mechanism without modifying its code. Furthermore, it has zero overhead during both inference and training, as RoPE embeddings are generated in advance and are reused for all forward passes. Combining it with the "NTK-by-parts" interpolation, we have the YaRN method.

By the "YaRN method", we refer to a combination of the attention scaling in Eq. 21 and the "NTK-by-parts" interpolation introduced in Section 3.2.

For LLaMA and Llama 2 models, we recommend the following values:

0.1𝑠1\displaystyle\sqrt{\frac{1}{t}}=0.1\ln({s})+1. (22) The equation above is found by fitting 1/t\sqrt{1/t} at the lowest perplexity against the scale extension by various factors ss using the "NTK-by-parts" method (Section 3.2) on LLaMA 7b, 13b, 33b and 65b models without fine-tuning. We note that the same values of tt also apply fairly well to Llama 2 models (7b, 13b and 70b). It suggests that the property of increased entropy and the temperature constant tt may have certain degree of "universality" and may be generalizable across some models and training data.

The YaRN method combines all our findings and surpasses all previous methods in both fine-tuned and non-fine-tuned scenarios. Thanks to its low footprint, YaRN allows for direct compatibility with libraries that modify the attention mechanism such as Flash Attention 2 .

Experiments

We show that YaRN successfully achieves context window extension of language models using RoPE as its position embedding. Moreover, this result is achieved with only 400 training steps, representing approximately 0.1% of the model’s original pre-training corpus, a 10x reduction from Rozière et al. and 2.5x reduction in training steps from Chen et al. , making it highly compute-efficient for training with no additional inference costs. We calculate the perplexity of long documents and score on established benchmarks to evaluate the resulting models, finding that they surpass all other context window extension methods.

We broadly followed the training and evaluation procedures as outlined in .

For training, we extended the Llama 2 7B and 13B parameter models. No changes were made to the LLaMA model architecture other than the calculation of the embedding frequencies as described in 3.4 with s=16s=16 and s=32s=32.

We used a learning rate of 2×1052\times 10^{-5} with no weight decay and a linear warmup of 20 steps along with AdamW β1=0.9\beta_{1}=0.9 and β2=0.95\beta_{2}=0.95. For s=16s=16 we fine-tuned for 400 steps with global batch size 6464 using PyTorch Fully Sharded Data Parallelism and Flash Attention 2 on the PG19 dataset chunked into 64k segments bookended with the BOS and EOS token. For s=32s=32 we followed the same procedure, but started from the finished s=16s=16 checkpoint and trained for an additional 200 steps.

2 Extrapolation and Transfer Learning

In Code Llama , a dataset with 16k context was used with a scale factor set to s88.6s\approx 88.6, which corresponds to a context size of 355k. They show that the network extrapolates up to 100k context without ever seeing those context sizes during training. Similar to 3.1 and Rozière et al. , YaRN also supports training with a higher scale factor ss than the length of the dataset. Due to compute constraints, we test only s=32s=32 by further fine-tuning the s=16s=16 model for 200 steps using the same dataset with 64k context.

We show in 4.3.1 that the s=32s=32 model successfully extrapolates up to 128k context using only 64k context during training. Unlike previous "blind" interpolation methods, YaRN is much more efficient at transfer learning when increasing the scale ss. This demonstrates successful transfer learning from s=16s=16 to s=32s=32 without the network needing to relearn the interpolated embeddings, as the s=32s=32 model is equivalent to the s=16s=16 model across the entire context size, despite only being trained on s=32s=32 for 200 steps.

3 Evaluation

the perplexity scores of fine-tuned models with extended context window,

the passkey retrieval task on fine-tuned models,

the common LLM benchmark results of fine-tuned models,

To evaluate the long sequence language modeling performances, we use the GovReport and Proof-pile datasets both of which contain many long sequence samples. For all evaluations, the test splits of both datasets were used exclusively. All perplexity evaluations were calculated using the sliding window method from Press et al. with S=256S=256.

Firstly, we evaluated how the model performed as the context window increased. We selected 10 random samples from Proof-pile with at least 128k tokens each and evaluated the perplexity of each of these samples when truncated at 2k steps from a sequence length of 2k tokens through 128k tokens.

Table 1 shows a side-by-side comparison of Llama-2 model extended from 40964096 to 81928192 context length via PI (LLongMA-2 7b222LLongMA-2 7b is fine-tuned from Llama-2 7b, trained at 8k context length with PI using the RedPajama dataset . ), "NTK-aware" and YaRN. Note that PI and "NTK-aware" models were trained using the methodology in Chen et al. , while YaRN used the same methodology but 2.5x less training steps and data, as described in 4.

We further evaluated YaRN at the scale factor s=16,32s=16,32 and compared them against a few open-source models fine-tuned from Llama-2 and extended to more than 32k context window such as Together.ai and "NTK-aware" Code Llama . The results are summarized in Table 2 (with a more detailed plot in Figure 1).

We observe that the model exhibits strong performance across the entire targeted context size, with YaRN interpolation being the first method to successfully extend the effective context size of Llama 2 to 128k. Of particular note are the YaRN (s=32s=32) models, which show continued declining perplexity through 128k, despite the fine-tuning data being limited to 64k tokens in length, demonstrating that the model is able to generalize to unseen context lengths.

Furthermore, in Appendix B.1, we show the results of the average perplexity on 50 untruncated GovReport documents with at least 16k tokens per sample evaluated on the setting of 32k maximal context window without Dynamic Scaling in Table 4. Similar to the Proof-pile results, the GovReport results show that fine-tuning with YaRN achieves good performance on long sequences.

3.2 Passkey Retrieval

The passkey retrieval task as defined in measures a model’s ability to retrieve a simple passkey (i.e., a five-digit number) from amongst a large amount of otherwise meaningless text. For our evaluation of the models, we performed 10 iterations of the passkey retrieval task with the passkey placed at a random location uniformly distributed across the evaluation context window on different context window sizes ranging from 8k to 128k. Both 7b and 13b models fine-tuned using YaRN at 128k context size passes the passkey retrieval task with very high accuracy (>99%>99\%) within the entire context window size. We show detailed results in Appendix B.2.

3.3 Standardized Benchmarks

The Hugging Face Open LLM Leaderboard compares a multitude of LLMs across a standardized set of four public benchmarks. Specifically, we use 25-shot ARC-Challenge , 10-shot HellaSwag , 5-shot MMLU , and 0-shot TruthfulQA .

To test the degradation of model performance under context extension, we evaluated our models using this suite and compared it to established scores for the Llama 2 baselines as well as publicly available PI and "NTK-aware" models. The results are summarized in Table 3.

We observe that there is minimal performance degradation between the YaRN models and their respective Llama 2 baselines. We also observe that there was on average a 0.49% drop in scores between the YaRN s=16s=16 and s=32s=32 models. From this we conclude that the the iterative extension from 64k to 128k results in negligible performance loss.

Conclusion

In conclusion, we have shown that YaRN improves upon all existing RoPE interpolation methods and can act as a drop-in replacement to PI, with no downsides and minimal implementation effort. The fine-tuned models preserve their original abilities on multiple benchmarks while being able to attend to a very large context size. Furthermore, YaRN allows efficient extrapolation with fine-tuning on shorter datasets and can take advantage of transfer learning for faster convergence, both of which are crucial under compute-constrained scenarios. Finally, we have shown the effectiveness of extrapolation with YaRN where it is able to "train short, and test long".

Reproducibility

To aid in reproducibility, we provide, as supplementary material, the entirety of of the code used to train the YaRN models in Table 2, as well as the evaluation code that produced Figure 1 and Tables 1, 2, 3, 4, and 5. The code also contains implementations of various extension methods referenced throughout the paper. For training YaRN, we used the publicly available PG19 dataset tokenized to 64k tokens.

References

Appendix A Additional details on interpolation methods

In Section 3.1, we introduce a change of basis from bb to bb^{\prime} in the definition of "NTK-aware" interpolation method. Here is a short note on its mathematical deduction.

Recall that our goal is to spread out the interpolation pressure across the hidden dimensions using a base-change instead of scaling the frequencies by a fixed factor ss. The property we want to guarantee is that: The lowest frequency needs to be scaled as much as linear positional scaling and the highest frequency to stay constant.

We introduce a new base bb^{\prime} such that the last dimension matches the wavelength of linear interpolation with a scale factor ss. Since the original RoPE method skips odd dimensions in order to concatenate both cos(2πxλ)\cos(\frac{2\pi x}{\lambda}) and sin(2πxλ)\sin(\frac{2\pi x}{\lambda}) components into a single embedding, the last dimension dDd\in D is D2|D|-2.

The new base bb^{\prime} can be chosen so that

A.2 The impact of pre-softmax scaling of YaRN on perplexity

In Section 3.4, we mention the impact of the factor tt inside the softmax computation of attention weights. Here we fix 896896 1616k-token documents from RedPajama 333We choose RedPajama because it is the open-source dataset closest to the training dataset of LLaMA as far as we are aware of., and calculate their perplexity scores with different scaling 1/t1/\sqrt{t}. The result is in Figure 2. For comparison, recall that our recommended factor in this case (s=8s=8) is given by the following.

0.1𝑠11.208\sqrt{\frac{1}{t}}=0.1\ln({s})+1\approx 1.208. (25) Figure 2: Fix s=8s=8, compare the LLaMA 7b perplexity on 896896 1616k-token documents over different scaling 1/t1/\sqrt{t}. The shaded area represents 11 standard deviation (68%68\%). To show the impact of the factor 1/t1/\sqrt{t} on different token positions, we cut each 1616k-token document into chunks of 20482048 tokens, and further plot the mean perplexity change comparing to t=1t=1 in percentages

of each chunk. The plot is shown in Figure 3.

To further demonstrate the best values of tt across all samples over different token positions, we plot the sample counts with minimal perplexity at a given 1/t1/\sqrt{t} for each of the 88 position segments over the 1616k-token range in Figure 4.

for a suitable tt, a sample may obtain better perplexity scores across the extended context window;

the best value of tt is mostly consistent across different samples and different positions.

We remark that this finding is consistent for different values of ss and the best value of tt follows our recommended formula (Eq. 22) closely.

Appendix B Additional tables and charts

In Section 4.3.1, we mention the evaluation on GovReport documents. The evaluation results are detailed in Table 4 below.

B.2 Passkey Retrieval

Here we can observe that the lowest perplexity point alone does not provide a comprehensive depiction on the "effective context size" that an LLM can attend to. While the Code Llama 13b model exhibits increasing perplexity above 100k context lengths, it was still able to accurately retrieve the passkey at a context length of 128k. This suggest that while the output of Code Llama might start to degrade in quality above 100k context size, it is still able to maintain strong retrieval capabilities.

In addition, as YaRN with s=32s=32 was trained for 200 more steps than YaRN with s=16s=16 while having a higher passkey accuracy with similar perplexity, we hypothesize that perplexity may not be a great indicator of whether an LLM is able to attend to all tokens and does not exhaustively determine long context performance. This also suggests that the YaRN models with s=16s=16 might be relatively undertrained for the passkey retrieval task.

B.3 Dynamic scaling on models without any fine-tuning

We first recall from Section 3.3 that the Dynamic Scaling technique is an inference-time technique that dynamically update the factor ss in interpolation methods such as PI, "NTK-by-parts" and YaRN. We choose the original Llama 2, fix a sample in GovReport and calculate its perplexity on a sliding window of 256256 tokens using RoPE, Dynamic-PI and Dynamic-YaRN.

Since the original maximal context length of Llama 2 is 40964096, we observe that Dynamic Scaling effectively extend the inference length and Dynamic-YaRN achieves better performance than Dynamic-PI. The resulting chart is in Figure 5.

Dynamic Scaling effectively prevents the blow-up of perplexity score beyond pretrained context window;

Dynamic-YaRN outperforms Dynamic-PI in terms of long-range perplexity on pretrained Llama-2 without any finetuning.

B.4 Mistral

We additionally extended the Mistral 7B v0.1 model , which broadly follows the Llama architecture. For Mistral we trained a 64k context window model (s=8s=8) for 1000 steps using 16k sequence lengths with a constant learning rate of 1×1061\times 10^{-6}. The model’s sliding window attention size was set to the context window size, effectively disabling sliding window attention. We then trained for an additional 500 steps at s=16s=16 to arrive at a 128k context window model. The training data was a mix of the pre-train and fine-tune splits of Together Computer’s Long-Data Collections .

We evaluated the models following the same procedure as described in 4.3.1, comparing against the base v0.1 model and MistralLite , an NTK-aware (θ=1\theta=1M) version of v0.1. The results (Figure 6 and Table 6) were consistent with those of the Llama family of models.