AI Logic

Positional Encodings

Position Interpolation

Updated:

How position interpolation works. The left side shows the flow of an attention layer: as in RoPE, queries and keys are rotated, but by angles computed from positions m and n shrunk by a factor of L/Lβ€². The upper right shows an example of extending from L = 2048 to Lβ€² = 4096: direct extrapolation produces unseen positions beyond 2048, whereas position interpolation halves the positions so that all of them fall within the trained range. The lower right shows the rotation speed factor for each dimension pair j: position interpolation gives 1/2 for every pair

What Is Position Interpolation

Position interpolation (PI) extends the usable context length of a pretrained language model that uses RoPE from LL to Lβ€²L' by shrinking the position indices by a factor of L/Lβ€²L/L' before rotating. It was proposed by Chen et al. at Meta in 2023. Without changing the model architecture and with only brief fine-tuning (about 1000 steps), it extended the context length of LLaMA from 2048 to as much as 32768.

Large language models are pretrained on inputs up to a fixed length (2048 tokens for LLaMA). Feeding a longer input directly into a RoPE model produces large rotation angles never seen in training, and perplexity breaks down to over 1000. Fine-tuning directly on long inputs barely extends the context that is actually usable (in the paper, from 2048 to only 2560 after 10,000 steps).

Position interpolation squeezes the positions 0,1,…,Lβ€²βˆ’10, 1, \dots, L'-1 of a long input into the range [0,L)[0, L) seen in training before passing them to RoPE. Rather than going beyond that range (extrapolating), it places positions between the integer positions seen in training (interpolating), so values unfamiliar to the model are less likely to appear. Think of compressing a rubber ruler so that a long text fits within the same range of tick marks used in training.

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 figure in the RoPE article; the only difference is that the rotation angles are shrunk. The upper right shows how the position indices are shrunk, and the lower right shows the rotation speed for each dimension pair, both computed from the formulas.

Theory (Passing Positions Scaled by L/Lβ€² to RoPE)

The explanation follows the equations in Section 2 of the paper. Let LL be the pretraining context length, Lβ€²L' the target length, and dd the head dimension.

  1. Prepare a pretrained RoPE model. Its weights and architecture are used as is.
  2. When rotating the query and key of the word at position mm, use mL/Lβ€²m L / L' instead of mm. With Lβ€²=2LL' = 2L, positions are halved, and the intermediate positions become fractions such as 0.5,1.5,…0.5, 1.5, \dots.
  3. Briefly fine-tune on inputs of the extended length Lβ€²L' with next-word prediction (the same task as pretraining). The paper trained for 1000 steps on The Pile.
  4. At inference, likewise scale positions by L/Lβ€²L/L'.

RoPE rotates the vector xx at position mm by the angle mΞΈjm\theta_j for each two-dimensional pair jj (Eq. (1) in the paper).

f(x,m)=[(x0+ix1)eimΞΈ0,Β (x2+ix3)eimΞΈ1, …,Β (xdβˆ’2+ixdβˆ’1)eimΞΈd/2βˆ’1]⊀,ΞΈj=10000βˆ’2j/df(x, m) = \Bigl[(x_0 + i x_1)e^{im\theta_0},\ (x_2 + i x_3)e^{im\theta_1},\ \dots,\ (x_{d-2} + i x_{d-1})e^{im\theta_{d/2-1}}\Bigr]^\top, \qquad \theta_j = 10000^{-2j/d}

Position interpolation simply replaces this ff with the following fβ€²f' (Eq. (4) in the paper).

fβ€²(x,m)=f ⁣(x,mLLβ€²)f'(x, m) = f\!\left(x, \frac{mL}{L'}\right)

Since mΞΈjβ‹…L/Lβ€²=mβ‹…(ΞΈjL/Lβ€²)m\theta_j \cdot L/L' = m \cdot (\theta_j L/L'), this is equivalent to uniformly scaling the rotation speed ΞΈj\theta_j of every pair by L/Lβ€²L/L'. The lower right of the figure at the top of the article shows that with L=2048L = 2048 and Lβ€²=4096L' = 4096, the speed is scaled by 1/21/2 for every pair. The distance between two words is likewise scaled by L/Lβ€²L/L', so the maximum distance passed to RoPE shrinks from Lβ€²L' to LL.

RoPE computes angles as continuous values, so fractional positions can be handled as is. No parameters are added and the architecture is unchanged, so the speedups used in pretraining (such as FlashAttention) can be used as is. The paper contrasts this with earlier work that raised the resolution of ViT, which has learned positional embeddings, by interpolating the embeddings themselves: position interpolation differs in that it interpolates the position indices rather than the embeddings.

Why Interpolation Is More Stable Than Extrapolation

The RoPE score can be written as a superposition of trigonometric functions of the query–key distance s=mβˆ’ns = m - n (Eq. (3) in the paper).

a(s)=Re[βˆ‘j=0d/2βˆ’1hjeisΞΈj],hj=(q2j+iq2j+1)(k2jβˆ’ik2j+1)a(s) = \mathrm{Re}\left[\sum_{j=0}^{d/2-1} h_j e^{is\theta_j}\right], \qquad h_j = (q_{2j} + i q_{2j+1})(k_{2j} - i k_{2j+1})

A superposition of trigonometric functions is flexible enough to represent functions of almost any shape, so even if it stays small within the trained range [0,L][0, L], it can become very large outside that range. Figure 2 of the paper shows that, with d=128d = 128 as in LLaMA 7B, a function that stays within roughly βˆ’1-1 to 11 inside the range exceeds 8000 outside it. When scores become this large, attention weights concentrate extremely on particular words, and the self-attention mechanism breaks down.

Between integer positions (interpolation), on the other hand, trigonometric functions are smooth, so values do not blow up. The paper gives an upper bound on the difference between the interpolated score and the straight line connecting the values at the neighboring integer positions (Theorem 2.1).

∣a(s)βˆ’alinear(s)βˆ£β‰€d(max⁑j∣hj∣)(sβˆ’s1)(s2βˆ’s)8ln⁑c\bigl|a(s) - a_{\mathrm{linear}}(s)\bigr| \le d \left(\max_j |h_j|\right) \frac{(s - s_1)(s_2 - s)}{8 \ln c}

Here s1,s2s_1, s_2 are adjacent integer positions and c=10000c = 10000. Because integer positions are spaced 1 apart, (sβˆ’s1)(s2βˆ’s)≀1/4(s - s_1)(s_2 - s) \le 1/4, and the bound is about dmax⁑j∣hj∣/294.73d \max_j |h_j| / 294.73. Compared with the extrapolation bound in the RoPE paper, this is at least about 600 times smaller. The idea of position interpolation is that scores at the integer positions seen in training are well behaved after pretraining, so the values in between stay well behaved too.

Experimental Results

Language modeling on long documents (Table 1 in the paper): perplexity on the PG-19 book test set at various evaluation context lengths (lower is better). LLaMA 7B (pretraining length 2048) is compared between direct fine-tuning on long inputs (10,000 steps) and position interpolation (1000 steps).

ModelExtended lengthMethod2048409681921638432768
7B2048Original7.20> 1000> 1000> 1000> 1000
7B8192Direct fine-tuning7.217.347.69β€”β€”
7B8192Position interpolation7.136.966.95β€”β€”
7B32768Position interpolation7.237.046.916.806.77

Models extended with position interpolation achieved lower perplexity the longer the context they used, showing that they actually make use of long contexts in prediction. The directly fine-tuned model got worse as the length grew.

Amount of fine-tuning (Table 3): on PG-19, the 7B model extended to 8192 had a perplexity of 16.10 even without fine-tuning (0 steps), far better than the over-1000 of extrapolation. After 200 steps it reached 7.12, beating the original model's value at length 2048 (7.20).

Effective usable context length (Table 4): in a task asking the model to report a 5-digit passkey hidden in a long text, the maximum distance at which it could be retrieved correctly was measured.

ModelExtended lengthMethod200 steps1000 steps10000 steps
7B8192Direct fine-tuning179223042560
7B8192Position interpolation81928192β€”
7B32768Position interpolation3276832768β€”

Position interpolation could use the full target length after 200 steps, whereas direct fine-tuning stayed at 2560 even after 10,000 steps.

Performance at the original length (Table 5): on standard benchmarks within length 2048 (zero-shot), the drop for models extended to 8192 was at most about 2%. However, for the 7B model extended to 32768, BoolQ dropped from 76.1 to 64.7, and in general the larger the extension factor, the larger the drop.

Long-document summarization (Table 6): LLaMA 7B extended to 16384 and fine-tuned for summarization on GovReport reached a ROUGE-1 of 60.0 (versus 58.7 for CoLT5 Base).

Practical Considerations

Position interpolation uniformly slows the rotation of every dimension pair, so performance on inputs of the original length also drops slightly. In the paper, perplexity on math proof data (Proof-pile) evaluated at length 2048 rose by 0.01–0.05, and the 7B model extended to 32768 dropped substantially on some benchmarks. It is important not to raise the factor more than necessary and to check performance on short inputs after extending.

Other points to keep in mind:

  • Fine-tuning is assumed: even without fine-tuning it is better than extrapolation, but the paper's results are after about 1000 steps of training. Training uses the same next-word prediction as pretraining, with inputs of the extended length.
  • Use the same factor at inference: use the L/Lβ€²L/L' from training at inference as well. When further fine-tuning the extended model, for example for summarization, keep the same position scaling.
  • Targets RoPE models: the method assumes RoPE, which can compute position indices as continuous values. It cannot be applied as is to models with learned positional embeddings.

In Hugging Face Transformers models such as LLaMA, passing {"type": "linear", "factor": L'/L} to rope_scaling in the config gives position interpolation. Instead of dividing the positions, the implementation divides the rotation speed ΞΈj\theta_j by factor (the same computation).

Comparison with Other Position Representations

Position interpolation 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
Learned positional embeddingAdded to the input embeddings (once)Yes (Lmax⁑×dL_{\max} \times d)Cannot be representedBERT, GPT
Sinusoidal positional encodingAdded to the input embeddings (once)NoneValues can be computed, but accuracy drops sharplyOriginal Transformer
RoPEQueries and keys in each layer rotated by an angle proportional to positionNoneOnly slightly longerLLaMA and others
Position interpolation (this article)Same as RoPE; positions shrunk by L/Lβ€²L/L' before rotatingNone (short fine-tuning)Fits up to Lβ€²L' into the trained range (up to 32x in the paper)Extending the context of a pretrained RoPE model
YaRNSame as RoPE; scaling varied by dimension pair, with the score temperature also adjustedNone (short fine-tuning)Extends to Lβ€²L' and even extrapolated beyond the fine-tuning data lengthExtending 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
  • To adapt a pretrained RoPE model to long contexts with little computation, position interpolation is the simplest method. Change one setting (the factor) and fine-tune briefly.
  • To limit the performance drop at the original length or to use a larger factor, YaRN has been proposed as an improvement: it leaves fast-rotating pairs unscaled and shrinks only slow-rotating pairs. LongRoPE is also a method that varies the scaling by pair.
  • For a model about to be pretrained that should handle inputs longer than in training, another option is to choose from the start a position representation that extrapolates easily, such as ALiBi.

PyTorch example

Show code
python
import torch


def rope_cos_sin(seq_len: int, d: int, base: float = 10000.0, scale: float = 1.0):
    """Compute cos and sin using m * scale instead of position m (scale = L / L' for position interpolation)"""
    theta = base ** (-torch.arange(0, d, 2).float() / d)          # ΞΈ_j = 10000^(-2j/d)
    pos = torch.arange(seq_len).float() * scale                   # position interpolation: m β†’ m L / L' (becomes fractional)
    angle = pos[:, None] * theta                                   # [seq_len, d/2]
    cos = angle.cos().repeat_interleave(2, dim=-1)                 # the same angle for each pair of adjacent dimensions
    sin = angle.sin().repeat_interleave(2, dim=-1)
    return cos, sin


def apply_rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
    """x: [..., seq_len, d]. Rotate each pair (x1, x2) (same as RoPE)"""
    x1, x2 = x[..., 0::2], x[..., 1::2]
    rotated = torch.stack((-x2, x1), dim=-1).flatten(-2)
    return x * cos + rotated * sin


L, L_new = 2048, 8192                 # pretraining length and target length
scale = L / L_new                     # 1/4

B, h, d = 1, 8, 128
n = 4096                              # input longer than the pretraining length
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
cos, sin = rope_cos_sin(n, d, scale=scale)
q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin)
out = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
print(out.shape)                      # torch.Size([1, 8, 4096, 128])

# The largest position passed to RoPE stays within the trained range
print((n - 1) * scale < L)            # True (4095 / 4 = 1023.75)

# With LLaMA in Hugging Face Transformers, the same can be done by configuration alone (followed by short fine-tuning)
# from transformers import AutoModelForCausalLM
# model = AutoModelForCausalLM.from_pretrained(name, rope_scaling={"type": "linear", "factor": L_new / L})

FAQ

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

To some extent. In the paper, LLaMA 7B extended to 8192 had a PG-19 perplexity of 16.10 even without fine-tuning, far better than direct extrapolation (over 1000). However, it was worse than the original model's value (7.20), and about 200 steps of fine-tuning brought it down to 7.12. In practice, plan on brief fine-tuning.

Q. How large can the factor be?
A.

The paper tested extending LLaMA from 2048 up to 32768 (16x), and for 7B and 13B, PG-19 perplexity kept decreasing with longer contexts up to 32768. On the other hand, the larger the factor, the more performance at the original length drops; for the 7B model extended to 32768, BoolQ fell from 76.1 to 64.7. Choose the factor to match the length actually needed.

Q. How does it differ from YaRN?
A.

Position interpolation uniformly scales the rotation speed of every dimension pair by L/Lβ€²L/L'. YaRN leaves fast-rotating pairs (which represent the order of nearby words) unscaled, shrinks only slow-rotating pairs, and connects the two smoothly in between. It also adjusts the temperature of the attention scores. The YaRN paper reports lower perplexity than position interpolation with the same 400 steps of fine-tuning, and comparable results with 2.5x fewer steps than position interpolation.

References

  1. S. Chen, S. Wong, L. Chen, and Y. Tian, "Extending Context Window of Large Language Models via Position Interpolation," arXiv:2306.15595, 2023.
  2. J. Su, Y. Lu, S. Pan, A. Murtadha, B. Wen, and Y. Liu, "RoFormer: Enhanced Transformer with Rotary Position Embedding," arXiv:2104.09864, 2021.
  3. H. Touvron et al., "LLaMA: Open and Efficient Foundation Language Models," arXiv:2302.13971, 2023.
  4. Hugging Face Transformers, modeling_rope_utils.py(_compute_linear_scaling_rope_parameters)