AI Logic

Positional Encodings

xPos (Extrapolatable Position Embedding)

Updated:

How xPos works. The left shows the flow of an attention layer: nothing is added to the input, and in each layer the query is rotated by the angle for position m and multiplied by ζ to the power m, the key is rotated by the angle for position n and multiplied by ζ to the power −n, and then the score is computed; the values are not rotated. The top right shows the expected score at each distance n: RoPE swings widely above and below 0 at long distances, while xPos decreases smoothly. The bottom right shows the decay strength ζ_i for each dimension pair i, rising from about 0.29 for the fast-rotating pair 0 to about 0.98 for pair 31.

What is xPos?

xPos (Extrapolatable Position Embedding) is a position representation that, in addition to the rotation of RoPE, scales the queries and keys up or down according to position so that the score decays exponentially with distance. It was proposed by Sun et al. at Microsoft in 2022. Its goal is to keep accuracy from collapsing when inference runs on sequences longer than in training.

RoPE rotates the queries and keys by an angle proportional to position so that their dot product depends only on distance. The paper points out a weakness of RoPE: the expected score oscillates sharply as distance grows. When the monotonic relation "the farther the word, the smaller the score" breaks down, the model has difficulty telling positions apart, and accuracy drops on sequences longer than in training.

xPos suppresses this oscillation by decaying more strongly the fast-rotating dimension pairs that cause it. The paper calls the model that combines this with blockwise causal attention (BCA) at inference time the LEX Transformer, and shows that a model trained at length 1024 keeps decreasing in perplexity even when the length is extended to 4096.

The left of the figure at the top of the article shows where position information is injected. It has the same layout as the figure in the RoPE article: after the queries and keys are rotated, the query is multiplied by ζm\zeta^{m} and the key by ζ−n\zeta^{-n}. The top right shows the expected score per distance computed for RoPE and xPos (the same quantity as Figure 1 in the paper), and the bottom right shows the decay strength ζi\zeta_i of each dimension pair.

Theory (scaling by position in addition to rotation)

The explanation follows the equations in Chapter 3 of the paper. Let dd be the head dimension, split into d/2d/2 pairs of two dimensions as in RoPE.

  1. For each pair ii, set the same rotation speed as RoPE, θi=10000−2i/d\theta_i = 10000^{-2i/d}, and a decay strength ζi\zeta_i (a value between 0 and 1). Neither is learned.
  2. Rotate the query at position mm by the angle mθim\theta_i for each pair and multiply it by ζim\zeta_i^{m}.
  3. Rotate the key at position nn by the angle nθin\theta_i for each pair and multiply it by ζi−n\zeta_i^{-n}.
  4. Compute the score q⋅k/dq \cdot k / \sqrt{d} as usual and take the softmax-weighted sum of the values. Nothing is done to the values.

Writing steps 2 and 3 for each pair ii gives the following (Eq. (10) and Algorithm 1 in the paper). RmθiR_{m\theta_i} is the 2D rotation by the angle mθim\theta_i.

q~m=ζi mRmθi qm,k~n=ζi−nRnθi kn\tilde{q}_m = \zeta_i^{\,m} R_{m\theta_i}\, q_m, \qquad \tilde{k}_n = \zeta_i^{-n} R_{n\theta_i}\, k_n

Taking the dot product, the rotation leaves only the difference (m−n)θi(m - n)\theta_i, as in RoPE, and the scaling combines into ζi mζi−n=ζi m−n\zeta_i^{\,m}\zeta_i^{-n} = \zeta_i^{\,m-n}.

q~m⊤k~n=ζi m−n  qm⊤R(n−m)θi kn\tilde{q}_m^\top \tilde{k}_n = \zeta_i^{\,m-n}\; q_m^\top R_{(n-m)\theta_i}\, k_n

With ζi=1\zeta_i = 1 this is the same as RoPE. In a language model that does not look ahead, m≥nm \ge n, so with ζi<1\zeta_i < 1 the score decreases exponentially as the distance m−nm - n grows. Since it depends only on the difference, not on mm and nn themselves, it is a relative position method like RoPE. The paper derives it in the form of the complex exponential eξn+iθne^{\xi n + i\theta n} (with ζ=eξ\zeta = e^{\xi}) (Eqs. (4)–(6)).

The decay strength is set from the pair index by the following formula (Eq. (9)).

ζi=i/(d/2)+γ1+γ∈[0,1]\zeta_i = \frac{i/(d/2) + \gamma}{1 + \gamma} \in [0, 1]

Pairs with smaller ii (faster-rotating pairs) have smaller ζi\zeta_i and decay more strongly. The paper says γ\gamma was chosen by hand, considering both how well positions can be distinguished ("attention resolution," described in the next section) and the range in which ζn\zeta^n can be represented in half-precision floating point (fp16). The official implementation (TorchScale) uses γ=0.4\gamma = 0.4 and an exponent of n/512n/512 instead of nn. The figure at the top of the article is computed with these values.

Blockwise causal attention (Section 3.3): When long sequences are fed at inference time, with pre-training length ll, the queries are split into blocks of length l/2l/2, and each query sees only the keys in its own block and the previous block. Training uses ordinary attention.

The rotation and scaling can be computed with the same code as RoPE by multiplying RoPE's cos⁡\cos and sin⁡\sin tables by ζm\zeta^{m} (by ζ−n\zeta^{-n} for keys) (Algorithm 1 in the paper). The only extra computation is multiplication.

Why adding decay helps on long sequences

The paper defines attention resolution as a measure of how well position is handled. With s[n]s[n] the expected score at distance nn, it is computed as follows (Eq. (3)).

R(s)=∑i=0Nes[i](es[i]−es[i+1])(∑i=0Nes[i])2R(s) = \frac{\sum_{i=0}^{N} e^{s[i]} \left(e^{s[i]} - e^{s[i+1]}\right)}{\left(\sum_{i=0}^{N} e^{s[i]}\right)^2}

The more reliably the score decreases each time the distance grows by one (s[i]>s[i+1]s[i] > s[i+1]), the larger the value. It is a measure that is higher the more easily the model can tell "which word is closer."

In RoPE, the expected score is proportional to ∑icos⁡(nθi)\sum_i \cos(n\theta_i) (Eqs. (7) and (8)). The cos⁡\cos of fast-rotating pairs flips between positive and negative with even a small increase in distance, so the sum oscillates sharply with distance. This is the thin line at the top right of the figure at the top of the article, which still swings widely above and below 0 beyond 2000. It is like trying to tell "how many minutes have passed" from a clock's second hand: a fast-rotating hand gives no clue for distinguishing distant times.

xPos multiplies the fast pairs that cause the oscillation by a weight ζin\zeta_i^{n} that shrinks with distance.

gζ[n]=∑i=0d/2cos⁡(nθi) ζi ng_\zeta[n] = \sum_{i=0}^{d/2} \cos(n\theta_i)\, \zeta_i^{\,n}

At long distances the contribution of the fast pairs almost vanishes and only the slowly rotating pairs remain, so the curve decreases smoothly (the thick line at the top right of the figure). On the other hand, at small distances or for slow pairs ζin≈1\zeta_i^{n} \approx 1, so relations between nearby words are almost the same as in RoPE. The paper explains that this smoothly connects short- and long-range dependencies.

Blockwise attention is also a device for raising resolution. Because it limits the attended range to about the training length, scores are compared within the range of distances seen in training. Information across blocks propagates forward through the keys and values as layers are stacked.

Experimental results

The paper trained Transformers of width 1024, 16 heads, and 24 layers (about GPT-3 Medium) from scratch with a maximum length of 1024 on a subset of the Pile (Books3, OpenWebText2, Wikipedia, etc.) and compared them. Evaluation used arXiv papers, which are often longer than 6000 tokens, measuring perplexity on the first 4000 tokens of each document split into the evaluation length (lower is better).

Lengths equal to or shorter than training (Table 2 in the paper)

Evaluation length2565121024
Absolute position (sinusoidal)46.3436.3929.94
ALiBi37.6629.9224.99
RoPE38.0930.3825.52
LEX (xPos + blockwise attention)34.327.5523.31

Even within the training length, xPos was about 1–3 lower.

Lengths longer than training (Table 5): The presence or absence of blockwise attention (BCA) is also compared.

Method20484096
RoPE73.6294.45
RoPE + BCA25.5725.65
ALiBi23.1424.26
ALiBi + BCA24.625.37
xPos22.5628.43
xPos + BCA21.620.73

RoPE collapsed without BCA and stopped collapsing with BCA. xPos worsened at 4096 without BCA, but combined with BCA it was the only method whose perplexity kept decreasing as the length grew. ALiBi did well without BCA and got slightly worse with it.

Attention resolution (Table 3): Values measured on actually trained models (higher means positions are easier to distinguish).

Method1024 (training length)2048
Absolute position (sinusoidal)0.870.28
ALiBi0.810.88
RoPE0.910.08
LEX (xPos + BCA)0.981.08
LEX without BCA0.980.54

Is rotation needed? (Table 4): Removing the rotation from xPos, leaving only the scaling, worsened validation perplexity at length 1024 sharply from 17.54 to 33.68 (RoPE: 17.74). Decay alone is not enough as a position representation; it needs to be combined with rotation.

Practical considerations

The decay ζm−n\zeta^{m-n} of xPos assumes that each query only looks at keys before it (m≥nm \ge n). The paper also derives the equations assuming a language model that does not look ahead. In bidirectional attention, ζm−n>1\zeta^{m-n} > 1 for later keys (n>mn > m), so the score grows with distance.

Also keep the following in mind.

  • BCA also contributes to accuracy on long sequences: In the paper's results, perplexity kept decreasing up to 4× the training length only when xPos was combined with blockwise attention. xPos alone worsened at 4096.
  • Watch the numeric range: Since queries are multiplied by ζm\zeta^{m} and keys by ζ−n\zeta^{-n}, values become extremely small or large as positions grow. The paper also says γ\gamma was chosen with the range representable in fp16 in mind. The official implementation shrinks the exponent to n/512n/512 and shifts position indices so that the middle of the sequence is 0.
  • γ\gamma is a hand-chosen value: The paper tried to find ζ\zeta by numerical optimization, but the result depended on initialization and was hard to handle when changing dimensions, so it uses hand-chosen values.

Comparison with other position representations

MethodWhere position is injectedLearned parametersSequences longer than trainingMain uses
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
T5 relative position biasA learned number per distance bucket added to scores in every layerYes (32 buckets × number of heads)Improves up to about 2× the lengthT5, mT5
RoPEQueries and keys rotated by an angle proportional to position in every layerNoneOnly slightly longerLLaMA, PaLM, etc.
ALiBiA penalty proportional to distance subtracted from scores in every layerNoneAccuracy is easier to maintainWhen sequences longer than training are needed
xPos (this article)Position-dependent scaling added to RoPE's rotationNoneWith BCA, perplexity kept decreasing up to 4× the lengthCausal language models (LEX Transformer)
  • To stabilize on long sequences while keeping RoPE's properties (relative position, form of the computation), xPos is a candidate. It only requires adding the ζ\zeta multiplication to a RoPE implementation.
  • To handle inputs longer than in training without extra devices, ALiBi, which did well without BCA in the paper's comparison too, is simpler. In the xPos paper's experiments, however, ALiBi's perplexity within the training length was slightly higher than that of RoPE or xPos.
  • To extend the context of an already-trained RoPE model, use methods such as position interpolation or YaRN rather than xPos, which requires retraining.

Blockwise attention belongs to the same family of ideas as reusing keys and values from the previous segment, as in Transformer-XL, and limiting the attended range, as in sparse attention.

PyTorch example

Show code
python
import torch
import torch.nn.functional as F


def xpos_tables(seq_len: int, d: int, gamma: float = 0.4, scale_base: float = 512.0):
    """cos, sin and scale factors for xPos (Eqs. (9), (10) and Algorithm 1 in the paper; γ and scale_base follow the official implementation)"""
    i = torch.arange(0, d // 2).float()
    theta = 10000.0 ** (-2 * i / d)                              # θ_i (same as RoPE)
    zeta = (i / (d / 2) + gamma) / (1 + gamma)                   # ζ_i: smaller for faster-rotating pairs
    pos = torch.arange(seq_len).float()
    pos = pos - seq_len // 2                                     # the official implementation centers positions at 0 to limit the numeric range
    angle = pos[:, None] * theta                                 # [seq_len, d/2]
    scale = zeta ** (pos[:, None] / scale_base)                  # ζ_i^(n/512)
    rep = lambda t: t.repeat_interleave(2, dim=-1)               # each pair of dimensions shares a value
    return rep(angle.cos()), rep(angle.sin()), rep(scale)


def rotate_every_two(x: torch.Tensor) -> torch.Tensor:
    x1, x2 = x[..., 0::2], x[..., 1::2]
    return torch.stack((-x2, x1), dim=-1).flatten(-2)


def apply_xpos(q: torch.Tensor, k: torch.Tensor):
    n, d = q.shape[-2], q.shape[-1]
    cos, sin, scale = xpos_tables(n, d)
    q = (q * cos + rotate_every_two(q) * sin) * scale            # query: rotate and multiply by ζ^m
    k = (k * cos + rotate_every_two(k) * sin) / scale            # key: rotate and multiply by ζ^(-n)
    return q, k


B, h, n, d = 2, 16, 128, 64
q, k, v = (torch.randn(B, h, n, d) for _ in range(3))
q, k = apply_xpos(q, k)                                          # values are unchanged
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)   # assumes no look-ahead (m >= n)
print(out.shape)                                                 # torch.Size([2, 16, 128, 64])

FAQ

Q. How does it differ from RoPE?
A.

The rotation is the same as RoPE; in addition, the query is multiplied by ζm\zeta^{m} and the key by ζ−n\zeta^{-n}. The dot product is multiplied by ζm−n\zeta^{m-n}, so the score decreases exponentially with distance. Setting ζ=1\zeta = 1 gives RoPE. In the paper's comparison, perplexity was slightly lower than RoPE even within the training length (23.31 versus 25.52 at length 1024).

Q. Is blockwise causal attention (BCA) required?
A.

For sequences much longer than the training length, it is effectively necessary. In the paper's comparison, xPos alone worsened to a perplexity of 28.43 at length 4096, while combined with BCA it fell to 20.73. BCA is used only at inference time; training uses ordinary attention.

Q. Can it be used in an encoder (bidirectional attention)?
A.

Not as is. The decay ζm−n\zeta^{m-n} of xPos assumes each query only looks at keys before it (m≥nm \ge n). For later keys, ζm−n>1\zeta^{m-n} > 1, so the score grows with distance. The paper's derivation and experiments also target language models that do not look ahead.

References

  1. Y. Sun, L. Dong, B. Patra, S. Ma, S. Huang, A. Benhaim, V. Chaudhary, X. Song, and F. Wei, "A Length-Extrapolatable Transformer," arXiv:2212.10554, 2022.
  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. microsoft/torchscale, xpos_relative_position.py (official implementation of xPos)