AI Logic

Positional Encodings

LongRoPE

Updated:

How LongRoPE works. The left side shows the flow of an attention layer: as in RoPE, queries and keys are rotated, but the rotation angles are shrunk per pair and per position. The upper right shows the per-pair scaling factor λ_i for extending Llama 2 7B from 4k to 32k (s = 8); within the search range 1 to 1.25s it draws the initial candidates of the search: position interpolation (all 8), NTK-aware (a line rising from 1 to 8 across pairs 0 to 63), and YaRN (1 for fast pairs, 8 for slow pairs, smoothly connected in between). The lower right shows the angle factor by position: the first 4 positions stay at 1, and later positions are shrunk by 1/λ per pair

What Is LongRoPE

LongRoPE is a method for extending the context of pretrained language models that use RoPE. It determines, by search, how much to shrink the RoPE rotation angles for each dimension pair and each position. Proposed by Ding et al. at Microsoft Research in 2024, it extended the context of Llama 2 from 4096 tokens to 2048k (about 2.1 million) tokens. Earlier methods had reached only about 128k.

Position interpolation and YaRN compute the per-pair scaling with hand-designed rules. The LongRoPE paper showed that rule-based scaling is not optimal and that exploiting two further "non-uniformities" reduces information loss even more.

  • Differences across dimension pairs: the optimal scaling differs by pair, and there are better combinations than the rule-based ones (position interpolation, NTK, YaRN)
  • Differences across positions: the first few words of a sequence are better left at their original angles without scaling

By determining these two through search, LongRoPE can extend the context 8x even without fine-tuning. It then reaches 2048k through progressive extension, re-running the search on a model fine-tuned up to 256k, and finally re-searches the scaling for short contexts to recover performance at the original length.

The left side of the figure at the top of the article shows where position information is injected. It uses the same layout as the figures in the RoPE, position interpolation, and YaRN articles; only the way the rotation angles are shrunk differs. The upper right shows the search range for extending Llama 2 by 8x and the scaling of the three rules used as starting points for the search (position interpolation, NTK, YaRN). The values LongRoPE actually found are not given in the paper, so they are not drawn. The lower right shows how the first few positions are left unscaled.

Theory (Searching for Per-Pair and Per-Position Scaling)

The explanation follows the equations in Sections 2–3 of the paper. Let LL be the pretraining context length, L′L' the target length, s=L′/Ls = L'/L the extension ratio, and dd the head dimension. RoPE rotates pair ii at position nn by the angle nθin\theta_i.

Expressing the scaling: earlier methods can all be written as shrinking the angle of pair ii to nθi/λin\theta_i / \lambda_i (Eq. (2) in the paper). Position interpolation uses λi=s\lambda_i = s for all pairs, NTK-aware uses smaller λi\lambda_i for faster-rotating pairs, and YaRN divides the pairs into three groups to set λi\lambda_i. LongRoPE adds the condition that "the first n^\hat{n} positions are not scaled" (Eq. (3)).

θin  ⟶  I(λi,n^) θin,I(λi,n^)={1(n<n^)1/λi(n≥n^)\theta_i n \;\longrightarrow\; I(\lambda_i, \hat{n})\, \theta_i n, \qquad I(\lambda_i, \hat{n}) = \begin{cases} 1 & (n < \hat{n}) \\ 1/\lambda_i & (n \ge \hat{n}) \end{cases}

LongRoPE frames the problem as choosing λ1,…,λd/2\lambda_1, \dots, \lambda_{d/2} and n^\hat{n} so that perplexity on documents of length L′L' or more is minimized.

Search procedure (Section 3.2, Algorithm 1):

  1. Define the search space. λi\lambda_i ranges from 1.0 (no scaling) to 1.25s1.25s (stronger scaling than position interpolation) in steps of 0.01, and n^\hat{n} is chosen from 0, 1, 2, 4, 8, 12, …, 32, 64, 128, 256 (Table 4).
  2. Put the three scalings of position interpolation, NTK, and YaRN into the initial population, and create the rest by mutating these three with probability pp.
  3. Apply each candidate to the pretrained model and compute perplexity on long documents (5 documents from the PG19 validation set).
  4. Use the top candidates as parents and create the next candidates by mutation and crossover. At this point, only candidates satisfying λi≤λi+1\lambda_i \le \lambda_{i+1} (slower-rotating pairs are scaled more strongly) are evaluated, avoiding wasted computation.
  5. Repeat steps 3–4 and select the candidate with the lowest perplexity.

For the search up to 256k, the population is 64 candidates, with 16 each from mutation and crossover, a mutation probability of 0.3, 40 iterations, and the top 32 as parents.

Progressive extension to 2048k (Section 3.3):

  1. On the pretrained Llama 2, search for scalings for 128k (32x) and 256k (64x).
  2. Fine-tune for 400 steps with the 128k scaling, then switch that model's scaling to the 256k one and fine-tune for another 600 steps.
  3. On the 256k model, search again to find the scaling for 2048k (a further 8x, 512x in total). No fine-tuning is done at this stage.
  4. On the extended model, re-search for short contexts (4k and 8k) with a smaller upper bound on the scaling. At inference, switch to this scaling when the input is shorter than 8k.

The only thing LongRoPE changes is the angle used when computing the RoPE cos⁡\cos and sin⁡\sin. The model architecture and attention computation remain the same, so existing speedups such as FlashAttention can be used as is.

Why the Searched Scaling Works Better

Position interpolation shrinks all pairs by the same amount, so the angle differences between nearby words become small and adjacent words become hard to distinguish. YaRN mitigated this with the rule "do not scale fast-rotating pairs, scale slow pairs as much as position interpolation," but the grouping of pairs was set by human experience. The paper confirmed the following through search.

  • The optimal per-pair scaling differs from the rules: searching only the per-pair λi\lambda_i reduced the PG19 perplexity at 16k for Llama 2 7B without fine-tuning from 20.49 (position interpolation) and 87.89 (YaRN) to 11.34 (Table 1). The paper explains that this better preserves the important pairs of the original RoPE.
  • The first words are better left unscaled: the first few words of a sequence are known to attract large attention (an observation from StreamingLLM and others). Leaving only the first n^\hat{n} positions unscaled in position interpolation and NTK improved perplexity, and the optimal n^\hat{n} depended on the target length (Table 2).
  • A good scaling is also a better starting point for fine-tuning: for Llama 2 7B extended to 64k, the Proof-pile perplexity without fine-tuning was 72.54 for position interpolation, 4.15 for YaRN, and 3.22 for the LongRoPE search; after fine-tuning it was 2.44, 2.42, and 2.36, respectively (Table 3).

If the search picks a scaling with little information loss from the start, there is less to recover through fine-tuning. This is why the context can be extended greatly with few steps and short training data. Progressive extension follows the same idea: instead of fine-tuning directly on 2048k-long documents, it starts from a model fine-tuned at 256k and covers the remaining 8x by search without fine-tuning.

Experimental Results

Extension without fine-tuning (Table 1 and Figure 3 in the paper): Llama 2 7B (4k context) was extended and perplexity measured on PG19 (5 documents) (lower is better).

Method819216384
Position interpolation10.6520.49
Dynamic NTK10.2123.29
YaRN32.6487.89
Search per-pair λi\lambda_i9.3711.34

In Figure 3, the other methods' perplexity rises sharply beyond 2x, whereas LongRoPE extended to 32k (8x).

Lengths up to 256k (Table 5): perplexity on Proof-pile (10 documents). LongRoPE-2048k is the model extended to 2048k.

Model (Llama 2 7B)Context409632768131072262144
Original model4k3.58>104>10^4>104>10^4>104>10^4
Together (position interpolation)32k3.692.64>104>10^4>104>10^4
Code Llama (NTK)100k3.952.742.7149.33
YaRN (s=32s = 32)128k3.752.702.3799.64
LongRoPE-2048k (fine-tuned at 128k)2048k3.712.602.261.88
LongRoPE-2048k (fine-tuned at 256k)2048k3.852.632.261.87

Even with a 16x longer context, it matched or beat the other methods within 256k.

Lengths up to 2048k (Table 6): measured on 20 books from Books3 longer than 2048k.

Model (Llama 2 7B)8k128k256k1024k2048k
YaRN (s=32s = 32)6.386.12>104>10^4>104>10^4>104>10^4
LongRoPE-2048k (fine-tuned at 128k)6.556.176.176.837.80
LongRoPE-2048k (fine-tuned at 256k)6.816.216.176.357.08

In the passkey task, which retrieves a 5-digit number hidden in a long document, LongRoPE's Llama 2 (fine-tuned at 256k) kept over 90% accuracy from 4k to 2048k. The Mistral 7B model (fine-tuned at 128k) achieved 100% up to 1800k and 60% at 2048k (Figure 4).

Performance at the original length (Table 8): four benchmarks from the Hugging Face Open LLM Leaderboard.

ModelContextARC-cHellaSwagMMLUTruthfulQA
Original Llama 2 7B4k53.178.646.639.0
YaRN (s=32s = 32)128k52.278.541.837.4
LongRoPE-2048k (fine-tuned at 128k)2048k52.976.543.438.8
LongRoPE-2048k (fine-tuned at 256k)2048k51.075.339.637.3

Re-searching for short contexts brought the Proof-pile perplexity at 4k of Llama 2 7B-2048k (fine-tuned at 128k) from 4.16 back to 3.71, and the benchmark average from 49.3 back to 52.9 (Table 10).

Effect of the two ideas (Tables 9 and 11): when the second interpolation, extending the 256k model to 2048k, used position interpolation or YaRN instead, the Books3 perplexity at 2048k was 20.17 and 8.27, respectively, worse than LongRoPE's 7.08. Leaving the first positions unscaled helped at 16k and 32k (13.00 → 11.51 at 32k) but made no difference at 2048k.

Practical Considerations

LongRoPE's scaling must be searched for each model and each target length by computing perplexity many times. In the paper, the search up to 256k took under 3 days on one A100, and 1024k and 2048k took under 5 days on 4 and 8 A100s; at 2048k, a single perplexity evaluation took about 50 minutes. Compared with position interpolation and YaRN, which can be computed by rule, it requires much more preparation.

Other points to keep in mind:

  • Fine-tuning also requires substantial compute: fine-tuning Llama 2 to 128k (400 steps) took one week on 8 A100s, and to 256k (600 steps) took two weeks on 16.
  • Performance drops on short contexts: a model extended to 2048k performs worse at the original length. The paper addresses this by separately searching a scaling for short contexts and switching by input length. Even so, benchmark scores were somewhat lower than the original model (for example, MMLU 46.6 → 43.4).
  • Gains differ by model: with Mistral 7B, perplexity exceeded 7 and degraded beyond 256k. The paper attributes this to fine-tuning on 16k-long data.

Hugging Face Transformers has an implementation in which "longrope" is specified in the config's rope_scaling (rope_parameters in newer versions), along with per-pair factor tables for short contexts (short_factor) and long contexts (long_factor). It switches between the two tables depending on whether the input exceeds the pretraining length, and also multiplies cos⁡\cos and sin⁡\sin by a factor of 1+ln⁡s/ln⁡L\sqrt{1 + \ln s / \ln L}. This implementation does not include leaving the first n^\hat{n} positions unscaled.

Comparison with Other Position Representations

LongRoPE is not a new position representation but a method for extending the context of a pretrained RoPE model. Below it is compared with other position representations in terms of how they handle sequences longer than in training.

MethodWhere position is injectedLearned parametersSequences longer than the training lengthTypical use
RoPEQueries and keys in each layer rotated by an angle proportional to positionNoneOnly slightly longerLLaMA and others
Position interpolationSame as RoPE; positions in all pairs shrunk by 1/s1/s before rotatingNone (short fine-tuning)Fits up to L′L' into the trained rangeExtending the context of a pretrained RoPE model
YaRNSame as RoPE; scaling varied by pair by rule, with the score temperature also adjustedNone (short fine-tuning)Extended Llama 2 to 128kExtending the context of a pretrained RoPE model
LongRoPE (this article)Same as RoPE; per-pair and per-position scaling determined by searchNone (search plus short fine-tuning)Extended Llama 2 to 2048kGreatly extending the context of a pretrained RoPE model
ALiBiA distance-proportional penalty subtracted from the scores in each layerNoneTends to keep accuracyWhen long sequences are expected from pretraining
  • When a context far beyond 128k is needed and compute for search and fine-tuning is available, LongRoPE is a good fit. In the paper's comparison, it achieved lower perplexity than position interpolation and YaRN at the same length, and extended up to 8x even without fine-tuning.
  • To extend by several to tens of times with little effort, rule-based YaRN or position interpolation may suffice. No search time is needed.
  • For a model about to be pretrained, another option is to choose from the start a position representation that handles sequences longer than in training well, such as ALiBi.

PyTorch example

Show code
python
import random
import torch


def longrope_cos_sin(seq_len: int, lam: torch.Tensor, n_hat: int, base: float = 10000.0):
    """LongRoPE rotation (Eq. (3) of the paper). lam: per-pair factors λ_i (d/2 of them), n_hat: number of leading positions left unscaled"""
    d = 2 * lam.numel()
    theta = base ** (-torch.arange(0, d, 2).float() / d)          # θ_i (same as RoPE)
    pos = torch.arange(seq_len).float()[:, None]
    scale = torch.where(pos < n_hat, torch.ones_like(lam), 1.0 / lam)  # I(λ_i, n̂): 1 for leading positions, 1/λ_i afterwards
    angle = pos * theta * scale                                     # [seq_len, d/2]
    return angle.cos().repeat_interleave(2, -1), angle.sin().repeat_interleave(2, -1)


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return x * cos + torch.stack((-x2, x1), dim=-1).flatten(-2) * sin


def mutate(lam: list, s: float, p: float = 0.3) -> list:
    """Mutation in the search. λ_i in 1.0 to 1.25s in steps of 0.01. Discard candidates violating λ_i <= λ_(i+1) (Section 3.2)"""
    while True:
        new = [round(random.uniform(1.0, 1.25 * s), 2) if random.random() < p else v for v in lam]
        if all(a <= b for a, b in zip(new, new[1:])):
            return new


d, L, s = 128, 4096, 8                                              # example: extend Llama 2 7B by 8x (32k)
pi = [float(s)] * (d // 2)                                          # one initial candidate: position interpolation (λ_i = s)
ntk = [s ** (2 * i / (d - 2)) for i in range(d // 2)]              # initial candidate: NTK-aware (λ_i = s^(2i/(d-2)))
cand = mutate(ntk, s)                                               # in practice, measure perplexity for each candidate and use the top ones as parents

cos, sin = longrope_cos_sin(L * s, torch.tensor(cand), n_hat=4)
q = torch.randn(1, 8, L * s, d)
print(apply_rope(q, cos, sin).shape)                                # torch.Size([1, 8, 32768, 128])

FAQ

Q. How does it differ from YaRN?
A.

YaRN computes the per-pair scaling with a rule that "divides pairs into three groups by wavelength." LongRoPE determines the per-pair factors λi\lambda_i by search rather than by rule, and also adds the condition that the first few positions are not scaled. Because the search starts from the YaRN, position interpolation, and NTK scalings, it is designed not to settle on a solution worse than YaRN. In the paper's comparison, the PG19 perplexity of Llama 2 7B extended to 16k without fine-tuning was 11.34, versus 87.89 for YaRN.

Q. Can it be used without fine-tuning?
A.

Yes, up to about 8x. In the paper, the context of Llama 2 was extended from 4k to 32k without fine-tuning (the other methods' perplexity rose sharply beyond 2x). Extending further requires fine-tuning; the 2048k model was obtained by searching again on a model fine-tuned up to 256k and extending it 8x.

Q. Why are the first few positions left unscaled?
A.

Because the first words of a sequence are known to be important positions that attract much attention. The paper showed that simply leaving the first n^\hat{n} positions unscaled lowers perplexity even for position interpolation and NTK, and that the optimal n^\hat{n} depends on the target length. However, no effect was seen when extending to 2048k.

References

  1. Y. Ding, L. L. Zhang, C. Zhang, Y. Xu, N. Shang, J. Xu, F. Yang, and M. Yang, "LongRoPE: Extending LLM Context Window Beyond 2 Million Tokens," arXiv:2402.13753, 2024.
  2. B. Peng, J. Quesnelle, H. Fan, and E. Shippole, "YaRN: Efficient Context Window Extension of Large Language Models," arXiv:2309.00071, 2023.
  3. S. Chen, S. Wong, L. Chen, and Y. Tian, "Extending Context Window of Large Language Models via Position Interpolation," arXiv:2306.15595, 2023.
  4. Hugging Face Transformers, modeling_rope_utils.py(_compute_longrope_parameters)