Chapter 5 · Section 5.5 · 50 min

RoPE and ALiBi

Section 5.4 ended with a wish. We want an attention score between a query at position mm and a key at position nn that depends on their positions only through the offset m−nm - n, exactly and in every layer. We would like it to cost no parameters and no T×TT \times T table, and we do not want to lose any information about content along the way.

There is a beautiful way to get all of that, and you have already seen its key ingredient. In §5.4 the shift from position tt to t+kt + k turned out to be a rotation. Rotations have a property that makes them perfect for the job. If you rotate two vectors by different angles, their dot product depends only on the difference of the angles. So instead of adding position to the token, rotate each query and key by an angle proportional to its position. That is rotary position embedding, RoPE (Su et al., 2021), and it is the position scheme of LLaMA, Mistral, Qwen, Gemma, DeepSeek, and most other open models.

This section derives RoPE from complex numbers, proves its relative-position property, implements it the two ways real codebases do, and then covers ALiBi (Press, Smith & Lewis, 2022), which takes the opposite approach and directly penalizes distance.

Two dimensions first, with complex numbers

Start with a single pair of coordinates. A vector (q0,q1)∈R2(q_0, q_1) \in \R^2 is the same thing as the complex number q~=q0+i q1\tilde q = q_0 + \mathrm{i}\,q_1, where i\mathrm{i} is the imaginary unit. The real dot product of two such vectors is the real part of one times the conjugate of the other,

q~ k~‾=(q0+iq1)(k0−ik1)=(q0k0+q1k1)+i (q1k0−q0k1),soq⋅k=Re⁡(q~ k~‾).\tilde q\,\overline{\tilde k} = (q_0 + \mathrm{i}q_1)(k_0 - \mathrm{i}k_1) = (q_0k_0 + q_1k_1) + \mathrm{i}\,(q_1k_0 - q_0k_1), \qquad \text{so} \qquad \mathbf{q}\cdot\mathbf{k} = \operatorname{Re}\big(\tilde q\,\overline{\tilde k}\big).

Multiplying by eiα=cos⁡α+isin⁡αe^{\mathrm{i}\alpha} = \cos\alpha + \mathrm{i}\sin\alpha rotates a complex number by the angle α\alpha without changing its length. Now rotate the query at position mm by mωm\omega and the key at position nn by nωn\omega, for some fixed frequency ω\omega. Their score is

Re⁡(q~ eimω  k~ einω‾)=Re⁡(q~ k~‾  ei(m−n)ω),\operatorname{Re}\Big(\tilde q\,e^{\mathrm{i}m\omega}\;\overline{\tilde k\,e^{\mathrm{i}n\omega}}\Big) = \operatorname{Re}\Big(\tilde q\,\overline{\tilde k}\;e^{\mathrm{i}(m-n)\omega}\Big),

because einω‾=e−inω\overline{e^{\mathrm{i}n\omega}} = e^{-\mathrm{i}n\omega} and the exponents add.

In plain words, the score of a rotated query and a rotated key equals the score of the original pair with the key rotated by the difference of their angles. Absolute positions cancel, and only m−nm - n survives.

A worked example. Take q=k=(1,0)\mathbf{q} = \mathbf{k} = (1, 0) and ω=0.5\omega = 0.5. At m=3m = 3 the query is rotated by 1.5 radians to (cos⁡1.5,sin⁡1.5)≈(0.071,0.997)(\cos 1.5, \sin 1.5) \approx (0.071, 0.997). At n=1n = 1 the key is rotated by 0.5 radians to (0.878,0.479)(0.878, 0.479). Their dot product is 0.071⋅0.878+0.997⋅0.479≈0.5400.071 \cdot 0.878 + 0.997 \cdot 0.479 \approx 0.540, which is cos⁡(1.0)\cos(1.0), the cosine of (3−1)⋅0.5(3 - 1)\cdot 0.5. Move both to m=10m = 10 and n=8n = 8 and you get exactly the same number.

How does rotating queries and keys make attention depend only on the offset?
Left, one 2-D pair of a query (indigo) at position m and a key (pink) at position n, each rotated by its position times the pair's frequency. Right, the full 32-dimensional score as a function of the offset m minus n.
Loading interactive figure…

Deriving RoPE from what we want

Su et al. did not guess rotations. They wrote down the property they wanted and solved for the encoding. The derivation is short and worth knowing, because it shows that rotation is not just one option. Under mild assumptions, it is the solution.

∂ Solving for the encoding (Su et al., 2021, Section 3.4)

Work in two dimensions with complex numbers. We look for a function f(x,m)f(\mathbf{x}, m) that encodes a vector x\mathbf{x} at position mm, with f(x,0)=xf(\mathbf{x}, 0) = \mathbf{x} (position 0 changes nothing), such that the score depends only on the vectors and the offset,

Re⁡(f(q,m) f(k,n)‾)=g(q,k,m−n).\operatorname{Re}\Big(f(\mathbf{q}, m)\,\overline{f(\mathbf{k}, n)}\Big) = g(\mathbf{q}, \mathbf{k}, m - n) .

Su et al. impose the stronger complex version f(q,m)f(k,n)‾=g(q,k,m−n)f(\mathbf{q}, m)\overline{f(\mathbf{k}, n)} = g(\mathbf{q},\mathbf{k}, m-n). Write every complex quantity in polar form, f(x,m)=R(x,m) eiΘ(x,m)f(\mathbf{x}, m) = R(\mathbf{x}, m)\,e^{\mathrm{i}\Theta(\mathbf{x}, m)} and g=RgeiΘgg = R_g e^{\mathrm{i}\Theta_g}. Matching moduli and phases gives two equations,

R(q,m) R(k,n)=Rg(q,k,m−n),Θ(q,m)−Θ(k,n)=Θg(q,k,m−n).R(\mathbf{q}, m)\,R(\mathbf{k}, n) = R_g(\mathbf{q}, \mathbf{k}, m - n), \qquad \Theta(\mathbf{q}, m) - \Theta(\mathbf{k}, n) = \Theta_g(\mathbf{q}, \mathbf{k}, m - n).

The modulus. Set n=mn = m. Then R(q,m)R(k,m)=Rg(q,k,0)R(\mathbf{q}, m)R(\mathbf{k}, m) = R_g(\mathbf{q}, \mathbf{k}, 0), and at m=0m = 0 this equals ∥q∥ ∥k∥\lVert\mathbf{q}\rVert\,\lVert\mathbf{k}\rVert. So the product of moduli at any common position equals the product of the original lengths, and the natural solution is R(x,m)=∥x∥R(\mathbf{x}, m) = \lVert\mathbf{x}\rVert for every mm. The encoding preserves length.

The phase. Again set n=mn = m. Then Θ(q,m)−Θ(k,m)=Θg(q,k,0)=Θ(q,0)−Θ(k,0)\Theta(\mathbf{q}, m) - \Theta(\mathbf{k}, m) = \Theta_g(\mathbf{q}, \mathbf{k}, 0) = \Theta(\mathbf{q}, 0) - \Theta(\mathbf{k}, 0). Rearranging, Θ(q,m)−Θ(q,0)=Θ(k,m)−Θ(k,0)\Theta(\mathbf{q}, m) - \Theta(\mathbf{q}, 0) = \Theta(\mathbf{k}, m) - \Theta(\mathbf{k}, 0). The left side depends only on q\mathbf{q} and mm, the right only on k\mathbf{k} and mm, so both equal a function φ(m)\varphi(m) of the position alone,

Θ(x,m)=Θ(x,0)+φ(m)=arg⁡(x)+φ(m).\Theta(\mathbf{x}, m) = \Theta(\mathbf{x}, 0) + \varphi(m) = \arg(\mathbf{x}) + \varphi(m).

Now take n=m−1n = m - 1 in the phase equation. The left side is arg⁡q+φ(m)−arg⁡k−φ(m−1)\arg\mathbf{q} + \varphi(m) - \arg\mathbf{k} - \varphi(m-1) and the right side, Θg(q,k,1)\Theta_g(\mathbf{q},\mathbf{k}, 1), does not depend on mm. So φ(m)−φ(m−1)\varphi(m) - \varphi(m-1) is a constant, call it ω\omega, and φ\varphi is an arithmetic progression, φ(m)=mω+φ(0)\varphi(m) = m\omega + \varphi(0) with φ(0)=0\varphi(0) = 0.

Putting modulus and phase together,

f(x,m)=∥x∥ ei(arg⁡x+mω)=x~ eimω,f(\mathbf{x}, m) = \lVert\mathbf{x}\rVert\,e^{\mathrm{i}(\arg\mathbf{x} + m\omega)} = \tilde{x}\,e^{\mathrm{i}m\omega},

a rotation by mωm\omega. ∎

Any dimension, block-diagonal rotations

A head's query and key live in Rdk\R^{d_k}, not R2\R^2. RoPE splits them into dk/2d_k/2 pairs and rotates pair jj at its own frequency, reusing the geometric frequencies of the sinusoidal encoding,

ωj=b−2j/dk,j=0,1,…,dk2−1,\omega_j = b^{-2j/d_k}, \qquad j = 0, 1, \dots, \tfrac{d_k}{2} - 1,

where bb is the base (10,000 in the original paper). With column vectors and the standard counterclockwise rotation R(α)=(cos⁡α−sin⁡αsin⁡αcos⁡α)\mathbf{R}(\alpha) = \begin{pmatrix}\cos\alpha & -\sin\alpha\\ \sin\alpha & \cos\alpha\end{pmatrix}, the rotation for position mm is the block-diagonal matrix

Rm=diag⁡(R(mω0), R(mω1), …, R(mωdk/2−1))∈Rdk×dk,\mathbf{R}_m = \operatorname{diag}\big(\mathbf{R}(m\omega_0),\ \mathbf{R}(m\omega_1),\ \dots,\ \mathbf{R}(m\omega_{d_k/2-1})\big) \in \R^{d_k\times d_k},

and RoPE replaces each query and key by its rotated version, qm↦Rmqm\mathbf{q}_m \mapsto \mathbf{R}_m\mathbf{q}_m and kn↦Rnkn\mathbf{k}_n \mapsto \mathbf{R}_n\mathbf{k}_n, after the projections and before the dot product. The values are not rotated.

The relative-position property, proved. Every block is a rotation, so R(α)⊤=R(−α)\mathbf{R}(\alpha)^\top = \mathbf{R}(-\alpha), and rotations of the same plane compose by adding angles, R(α)R(β)=R(α+β)\mathbf{R}(\alpha)\mathbf{R}(\beta) = \mathbf{R}(\alpha + \beta). Block-diagonal matrices multiply block by block, so Rm⊤Rn=Rn−m\mathbf{R}_m^\top\mathbf{R}_n = \mathbf{R}_{n-m}. Therefore

(Rmq)⊤(Rnk)=q⊤Rm⊤Rnk=q⊤Rn−m k.(\mathbf{R}_m\mathbf{q})^\top(\mathbf{R}_n\mathbf{k}) = \mathbf{q}^\top\mathbf{R}_m^\top\mathbf{R}_n\mathbf{k} = \mathbf{q}^\top\mathbf{R}_{n-m}\,\mathbf{k}.

In plain words, the score between a query at mm and a key at nn is the score of the unrotated query against the key rotated by the offset. It depends on content through q\mathbf{q} and k\mathbf{k}, and on position only through n−mn - m. This is exact, at every layer, for any learned WQ\mathbf{W}_Q and WK\mathbf{W}_K, which is precisely what added sinusoids could not guarantee.

Several other properties fall out immediately.

  • No parameters and no change of scale. Rotations preserve the norms of q\mathbf{q} and k\mathbf{k}, so RoPE never changes how large a logit can be (it stays within ±∥q∥∥k∥/dk\pm\lVert\mathbf{q}\rVert\lVert\mathbf{k}\rVert/\sqrt{d_k}), only how it depends on position.
  • Position enters every layer. RoPE is applied inside every attention layer, so every layer sees exact relative positions, instead of whatever trace of an input-layer encoding has survived in the stream.
  • Values stay position-free. Since v\mathbf{v} is not rotated, position affects which tokens are mixed but not what is written into the stream.
  • It works with a KV cache. A key's rotation depends only on its own position, so keys can be rotated once, cached, and reused (§6.5).

A gentle decay with distance

Su et al. also showed that, with the geometric frequencies, the largest possible score between a query and a key tends to shrink as their distance grows. Here is the idea in a picture you can compute. Take a query and a key with identical content, and give every pair the same magnitude. Then the score at offset Δ\Delta is ∑jcos⁡(Δ ωj)\sum_j\cos(\Delta\,\omega_j), which is exactly the sinusoidal similarity curve of §5.4. It starts at its maximum dk/2d_k/2 and falls off, with ripples, as the fast pairs dephase.

∂ Su et al.'s bound, by summation by parts

Write the complex score at offset Δ=m−n\Delta = m - n as ∑j=0dk/2−1hjeiΔωj\sum_{j=0}^{d_k/2-1} h_j e^{\mathrm{i}\Delta\omega_j} with hj=q~jk~j‾h_j = \tilde q_j\overline{\tilde k_j}. Define partial sums Sj=∑i=0j−1eiΔωiS_j = \sum_{i=0}^{j-1} e^{\mathrm{i}\Delta\omega_i}, with S0=0S_0 = 0, and set hdk/2=0h_{d_k/2} = 0. Summation by parts (the discrete version of integration by parts, also called the Abel transformation) gives

∑jhj (Sj+1−Sj)=−∑jSj+1 (hj+1−hj),so∣∑jhjeiΔωj∣≤(max⁡j∣hj+1−hj∣)∑j∣Sj+1∣.\sum_{j} h_j\,(S_{j+1} - S_j) = -\sum_j S_{j+1}\,(h_{j+1} - h_j), \qquad\text{so}\qquad \Big|\sum_j h_j e^{\mathrm{i}\Delta\omega_j}\Big| \le \Big(\max_j |h_{j+1} - h_j|\Big)\sum_{j} |S_{j+1}| .

The first factor depends only on content. The second, ∑j∣Sj+1∣\sum_j|S_{j+1}|, depends only on the offset, and Su et al. show numerically that its average, 2dk∑j∣Sj∣\frac{2}{d_k}\sum_j |S_{j}|, decays as ∣Δ∣|\Delta| grows. So the bound, not the score itself, decays. A trained model can still attend strongly to a distant token, but it has to pay for it with content.

Python · cell 1

Implementing it without matrices, and the two conventions

Nobody builds Rm\mathbf{R}_m. For each pair, the rotation is two multiplies and an add, which vectorizes as

RoPE⁡(x,m)=x⊙cos⁡(mω′)+rot⁡(x)⊙sin⁡(mω′),\operatorname{RoPE}(\mathbf{x}, m) = \mathbf{x}\odot\cos(m\boldsymbol{\omega}') + \operatorname{rot}(\mathbf{x})\odot\sin(m\boldsymbol{\omega}'),

where ω′\boldsymbol{\omega}' repeats each frequency twice to line up with its pair, and rot⁡(x)\operatorname{rot}(\mathbf{x}) maps each pair (xa,xb)(x_a, x_b) to (−xb,xa)(-x_b, x_a). The cosines and sines depend only on positions, so they are computed once for the maximum length and cached.

There are two conventions for which coordinates form a pair, and this trips up many people.

Interleaved, as in the RoFormer paper, GPT-J, and Meta's original LLaMA code, pairs adjacent coordinates (x2j,x2j+1)(x_{2j}, x_{2j+1}). Half-split, as in GPT-NeoX and the Hugging Face LLaMA implementation, pairs xjx_j with xj+dk/2x_{j + d_k/2}, so rot⁡(x)=(−xdk/2:, x:dk/2)\operatorname{rot}(\mathbf{x}) = (-\mathbf{x}_{d_k/2:},\ \mathbf{x}_{:d_k/2}), often written rotate_half. The two are the same function up to a fixed permutation of the dkd_k coordinates, and a permutation of the coordinates of q\mathbf{q} and k\mathbf{k} can be absorbed into WQ\mathbf{W}_Q and WK\mathbf{W}_K (their columns in this book's xW\mathbf{x}\mathbf{W} convention, the rows of a PyTorch nn.Linear weight). Applying the same permutation to both leaves every dot product unchanged. They are equally good for training. But a checkpoint trained with one convention gives garbage under the other, which is why the script that converts Meta's LLaMA weights to the Hugging Face format permutes the query and key projection weights.

Warm-up

The RoPE angle cache

Write rope_cos_sin(positions, d, base=10000.0) returning (cos, sin), each of shape (T, d/2), with entry [t, j] equal to cos⁡(pt ωj)\cos(p_t\,\omega_j) and sin⁡(pt ωj)\sin(p_t\,\omega_j) for ωj=b−2j/d\omega_j = b^{-2j/d}, where positions is an integer array of length T and d is the head dimension.

Hidden tests, hints, and AI help, from $1.99 a month.
Interview

Apply RoPE to queries and keys

Write apply_rope(x, positions, base=10000.0) for x of shape (..., T, d) (any leading axes, such as batch and heads) using the interleaved convention, where pair jj is coordinates (2j,2j+1)(2j, 2j+1) and is rotated counterclockwise by pt ωjp_t\,\omega_j. That is, the new pair is (x2jcos⁡α−x2j+1sin⁡α, x2jsin⁡α+x2j+1cos⁡α)(x_{2j}\cos\alpha - x_{2j+1}\sin\alpha,\ x_{2j}\sin\alpha + x_{2j+1}\cos\alpha). No loops.

The tests are strict. Your rotation must match the complex-number definition, preserve norms, leave position 0 unchanged, and make every query-key score depend only on the offset.

Hidden tests, hints, and AI help, from $1.99 a month.
Core

Port weights between the two RoPE conventions

You have a model trained with interleaved RoPE and want to run it with a half-split implementation, where pair jj is coordinates (j,j+d/2)(j, j + d/2). Write interleaved_to_half_perm(d) returning an index array perm of length d such that, for every vector, applying half-split RoPE to x[perm] gives the interleaved RoPE of x, permuted the same way. In other words, if you reorder the columns of WQ\mathbf{W}_Q and WK\mathbf{W}_K by perm, the half-split code computes exactly the original scores. The setup provides rope_interleaved(x, pos) and rope_half(x, pos).

Hidden tests, hints, and AI help, from $1.99 a month.

Where RoPE goes in a real attention layer

In a multi-head layer, RoPE acts on each head separately, after the projections and the split into heads, with frequencies computed from the head dimension dkd_k, not the model width dd. A LLaMA attention layer computes Q,K,V\mathbf{Q}, \mathbf{K}, \mathbf{V}, reshapes them to (h,T,dk)(h, T, d_k) for hh heads (keys and values to (nkv,T,dk)(n_{kv}, T, d_k) with grouped-query attention), rotates Q\mathbf{Q} and K\mathbf{K}, and then runs ordinary causal attention. Some models rotate only part of each head. GPT-NeoX-20B rotates a quarter of each head's dimensions and leaves the rest position-free, and DeepSeek's multi-head latent attention keeps a separate small rotated component (§12.5).

Interview

Causal multi-head attention with RoPE

Write rope_attention(X, Wq, Wk, Wv, Wo, H, offset=0) for X of shape (T, d) and square weight matrices of shape (d, d). Split Q,K,V\mathbf{Q}, \mathbf{K}, \mathbf{V} into H heads (the hh of the text) of size dkd_k = d // H (head i owns columns i*d_k to (i+1)*d_k), apply interleaved RoPE to each head's queries and keys at positions offset + arange(T) with frequencies from dkd_k, run causal softmax attention with scale 1/dk1/\sqrt{d_k}, merge the heads, and apply WO\mathbf{W}_O. The setup provides apply_rope(x, positions). No loops over heads.

The key test is one an interviewer would ask you to predict. Because RoPE is relative, the output must not depend on offset at all.

Hidden tests, hints, and AI help, from $1.99 a month.

The base, and a preview of context extension

The base bb sets the slowest rotation. Pair jj completes a full turn every 2πb2j/dk2\pi b^{2j/d_k} tokens, so with dk=128d_k = 128 and b=10,000b = 10{,}000 the slowest pair has a wavelength of about 54,000 tokens, while the fastest turns every 6.3 tokens. LLaMA 3 raised the base to 500,000, which pushes the slowest wavelength past 2.5 million tokens.

Why would that matter? Consider a model trained on sequences of 4,096 tokens. Its fast pairs have rotated through many full circles during training and have seen every angle. Its slow pairs have only ever seen a small arc. Run the model on 32,000 tokens and the slow pairs reach angles it never saw, and attention degrades. Press et al. (2022) found that rotary models extrapolate a little better than sinusoidal ones (on the order of 100 to 200 extra tokens in their setups) but nowhere near the lengths people want.

The standard fixes all manipulate the angles. Position interpolation (Chen et al., 2023) divides every position by the extension factor, so 32,000 tokens are squeezed into the angle range of 4,096, and a short fine-tune (under 1,000 steps in their experiments) adapts the model. Raising the base (sometimes called NTK-aware scaling) slows the low frequencies while barely touching the high ones. YaRN (Peng et al., 2023) interpolates different frequency bands by different amounts and adjusts the attention temperature. All of this is the subject of §12.7. For now, notice that every one of these methods is possible only because RoPE makes position an explicit, adjustable angle.

ALiBi, a penalty for distance

Press, Smith & Lewis (2022) took the most direct route imaginable. Add no position information to the tokens at all, and subtract from each attention logit a penalty proportional to the distance,

smn=qm⋅kndk−λi (m−n),n≤m,s_{mn} = \frac{\mathbf{q}_m\cdot\mathbf{k}_n}{\sqrt{d_k}} - \lambda_i\,(m - n), \qquad n \le m,

for head ii, where λi>0\lambda_i > 0 is a fixed, head-specific slope (we write λi\lambda_i for what the paper calls mm, since mm is our query position). For hh heads the slopes are a geometric sequence,

λi=2−8i/h,i=1,…,h,\lambda_i = 2^{-8i/h}, \qquad i = 1, \dots, h,

so 8 heads get 12,14,…,1256\tfrac12, \tfrac14, \dots, \tfrac1{256}. The slopes are not learned.

In plain words, every head starts with a built-in preference for recent tokens, and each head has a different horizon.

Put next to §5.4, ALiBi is T5's relative bias with the learned table replaced by a fixed straight line, one slope per head, and no buckets, so it costs no parameters and nothing changes at lengths never seen in training.

The horizon has a precise meaning. Softmax ignores any constant added to a whole row of logits, and −λi(m−n)=−λim+λin-\lambda_i(m - n) = -\lambda_i m + \lambda_i n, where the first term is constant along the row. So ALiBi multiplies the attention weight of a key Δ\Delta tokens back by e−λiΔe^{-\lambda_i\Delta} relative to the current token. That is an exponential recency prior with a decay length of 1/λi1/\lambda_i tokens. The steepest of 8 heads (λ=1/2\lambda = 1/2) mostly sees the last few tokens, and the gentlest (λ=1/256\lambda = 1/256) can look back hundreds.

What prior does ALiBi put on each attention head?
ALiBi subtracts slope times distance from every causal logit. Left, the bias for the chosen head (darker means a bigger penalty). Right, where the last of 64 queries attends, with optional random content scores mixed in.
Loading interactive figure…

ALiBi was designed for extrapolation, and it delivers. In the paper, a 1.3-billion-parameter model trained on 1,024 tokens and evaluated on 2,048 matched the perplexity of a sinusoidal model trained on 2,048, while training 11% faster and using 11% less memory. BLOOM and MPT used it. The catch is the flip side of the prior. Distant tokens are penalized by construction, and the paper's own analysis is candid about what that means. Its extrapolation gains come largely from avoiding the "early token curse" (in non-overlapping evaluation, the first tokens of each window have almost no context), and with sliding-window evaluation the ALiBi models did not improve perplexity by looking further back than their training length. Good perplexity on long inputs is not the same as using a long context well. In practice, models that must retrieve facts from far away have standardized on RoPE with context extension.

For a head count that is not a power of 2, the authors' code takes the slopes for the largest power of 2 below hh, then fills the remaining heads with every other slope from the sequence for twice that power.

Core

ALiBi slopes and the bias tensor

Write alibi_slopes(H) and alibi_bias(T, H).

Here H is the number of heads, the hh of the text.

  • alibi_slopes(H) returns the H slopes. For a power of 2, they are 2−8i/h2^{-8i/h} for i=1,…,hi = 1, \dots, h. Otherwise, with P the largest power of 2 below H, return alibi_slopes(P) followed by the first H - P entries of alibi_slopes(2 * P)[0::2].
  • alibi_bias(T, H) returns the (H, T, T) tensor whose entry [i, m, n] is −λi(m−n)-\lambda_i(m - n) for n≤mn \le m, with λi\lambda_i the slope in position i of alibi_slopes(H), and -np.inf for n>mn > m (the causal mask is built in).
Hidden tests, hints, and AI help, from $1.99 a month.

In PyTorch

The half-split convention is the common one in PyTorch codebases, because rotate_half is a cheap concatenation. ALiBi plugs into F.scaled_dot_product_attention as an additive mask.

🔥 In PyTorchfor a machine with PyTorch

Every position scheme, compared

schemehow position entersparametersexactly relativelong inputsused by
sinusoidaladded to input embeddings0nodegrades quicklyoriginal Transformer
learned absoluteadded to input embeddingsTmax⁡dT_{\max}dnoimpossible past Tmax⁡T_{\max}BERT, GPT-2, GPT-3
Shaw relativevectors added to keys and valuesO(Kdk)O(Kd_k) per layeryes, clippedfar offsets mergeearly MT models
T5 biaslearned scalar per offset bucket32h32h per stackyes, bucketedgood, but slowT5, Flan-T5
RoPErotates queries and keys0yesmodest, extendable by rescaling anglesLLaMA, Mistral, Qwen, Gemma, DeepSeek
ALiBilinear penalty on logits0yesstrong, with a recency biasBLOOM, MPT
NoPEcausal mask only0implicitgood in some studiesresearch models

Read more

Watch next

🎬 Rotary Positional Embeddings: Combining Absolute and Relative · Efficient NLPA short, clear derivation of RoPE with good pictures of the rotation.
🎬 How Rotary Position Embedding Supercharges Modern LLMs [RoPE] · Jia-Bin HuangAnimations of the rotation and of why the dot product depends only on the offset.
🎬 ALiBi - Train Short, Test Long: Attention with linear biases enables input length extrapolation · Yannic KilcherA paper walkthrough of ALiBi and its extrapolation experiments.