Module contents
Lesson 7 of 22Advanced 110 min

Relative position: relative biases, ALiBi and RoPE

Study relative position representations, T5 bucket biases, ALiBi, and RoPE. Derive RoPE with complex numbers, analyze its frequency spectrum, and implement and compare positional methods.

After this lesson you can

  • Implement learned relative position biases with T5-style logarithmic buckets.
  • Derive ALiBi as a per-head linear bias and explain geometric slopes.
  • Derive RoPE using complex numbers and show the rotated dot product depends on relative position.
  • Analyze the effect of the RoPE base on frequencies and distance behavior.
  • Implement interleaved and half-split RoPE conventions and convert between them.

Before you start

Distance travels with the text

If you shift a sentence ten positions, the distance between subject and verb does not change. A learned absolute-position table must learn its effects separately in every location. An absolute sinusoidal encoding has structure that can express shifts, but adding it to the input does not force all attention products to be translation invariant. This lesson’s methods directly introduce relationships between positions.

For one head, with a query at position ii and key at position jj, begin with sij=qi⊤kj/dks_{ij}=\vb{q}_i\T\vb{k}_j/\sqrt{d_k}. An additive bias is added before softmax and can vary by head. The causal mask still excludes future keys. With multiple heads each can use a different pattern; relative position does not by itself determine attention, since content also participates.

From relative vectors to buckets

Shaw et al. introduce relative position representations: a vector aijK\vb{a}^{K}_{ij} for clipped displacement clip⁡(j−i,−k,k)\operatorname{clip}(j-i,-k,k) modifies the logit to qi⊤(kj+aijK)/dk\vb{q}_i\T(\vb{k}_j+\vb{a}^{K}_{ij})/\sqrt{d_k}. Another table aijV\vb{a}^{V}_{ij} can modify the aggregated values. The position term depends on the query, unlike a fixed scalar per distance. Clipping shares representations among extreme distances and limits parameters; it also loses the distinction between them.

The T5 relative bias uses one learned scalar per bucket and head, added to the logit. Small displacements have exact buckets; large ones are grouped approximately logarithmically and the last interval absorbs larger distances. In the architecture described by Raffel et al., bias is shared across layers. Bidirectional attention reserves one half of buckets for each sign; in causal attention only present or previous keys matter. The code below uses the convention j−ij-i, so a distant past is negative.

Two distances in one bucket have identical bias, not necessarily identical probability: queries and keys can distinguish their content. The last bucket allows evaluation beyond training length, but the model receives no information to distinguish distances that have already saturated.

To specify the function, let bb be the number of buckets available for one sign and e=b/2e=b/2 the number of exact distances. For distance r≥er\ge e, before saturation the assigned index is

e+⌊log⁡(r/e)log⁡(D/e)(b−e)⌋,e+\left\lfloor \frac{\log(r/e)}{\log(D/e)}(b-e)\right\rfloor,

where D>eD>e is the maximum reference distance. The result is clipped to b−1b-1. For r<er<e the bucket is rr. In bidirectional mode use b=B/2b=B/2 and add bb to the positive-side index; in causal mode use b=Bb=B and future keys are masked afterward. The function need not distinguish causal future positions because that mask removes them. The implementation and its limits follow the T5 reference function.

ALiBi: a preference, not a mask

ALiBi adds −mh∣i−j∣-m_h|i-j| to head hh‘s logit, with positive slope mhm_h. In the causal case only j≤ij\le i are used and the bias penalizes the distant past. With eight heads, slopes under the original geometric rule are 2−1,2−2,…,2−82^{-1},2^{-2},\ldots,2^{-8}. Some heads are very local and others less biased. The rule for head counts that are not powers of two requires an additional construction, not this simplified sequence.

The penalty changes probability ratios: if two content logits are equal and their distances differ by rr, the ratio of their unnormalized weights is e−mhre^{-m_h r}. A sufficiently high content logit can compensate for the bias. Press et al. studied length extrapolation under their training conditions; being defined at every distance does not guarantee generalization on every task.

With slopes 0.5 and 1/256, the first head introduces a much stronger preference for proximity. Bias is applied to the already scaled logit, not divided again by dk\sqrt{d_k}. A constant can also be removed from all logits in one row: softmax is invariant to that translation. This equivalence allows causal implementations that store only one term per column, provided they preserve the same bias difference between allowed keys.

RoPE: two clocks and a difference

RoPE splits even dkd_k into two-coordinate blocks and rotates the query at position mm by mωrm\omega_r and the key at position nn by nωrn\omega_r. Each block is a Givens rotation and the total matrix is a block matrix Rm\mat{R}_m. Only queries and keys are rotated, not values.

InteractiveTwo hands and a shift
  • Rotated query
  • Rotated key
2
5
0
0
Distance n − m3
Dot product of this pair−0.584
Sum over both pairs−0.624
Change the positions and displayed pair. Shifting both positions together rotates both hands, but each pair's product and their sum stay equal.

Euler’s formula makes the identity visible. For one pair, identify (q0,q1)(q_0,q_1) with zq=q0+iq1z_q=q_0+\mathrm{i}q_1 and (k0,k1)(k_0,k_1) with zkz_k. Rotation multiplies by eimωe^{\mathrm{i}m\omega} or einωe^{\mathrm{i}n\omega}. The real product is the real part of the conjugate of the first times the second:

Re⁡ ⁣(zqeimω‾ zkeinω)=Re⁡ ⁣(zq‾zkei(n−m)ω).\operatorname{Re}\!\left(\overline{z_qe^{\mathrm{i}m\omega}}\,z_ke^{\mathrm{i}n\omega}\right) =\operatorname{Re}\!\left(\overline{z_q}z_ke^{\mathrm{i}(n-m)\omega}\right).

Equivalently in matrices, orthogonality and composition of rotations give Rm⊤Rn=Rn−m\mat{R}_m\T\mat{R}_n=\mat{R}_{n-m}. Therefore, for fixed content vectors,

⟨RmWQxm,RnWKxn⟩=xm⊤WQ⊤Rn−mWKxn.\langle\mat{R}_m\mat{W}_Q\vb{x}_m,\mat{R}_n\mat{W}_K\vb{x}_n\rangle =\vb{x}_m\T\mat{W}_Q\T\mat{R}_{n-m}\mat{W}_K\vb{x}_n.

The positional operation depends only on n−mn-m, but vectors xm,xn\vb{x}_m,\vb{x}_n may depend on context and previous positions: whole-model output invariance to shifting text does not follow. Frequencies and conventions must match when loading a checkpoint. The original proposal is RoFormer.

The complex example also explains the sign. The transpose of the query rotation is the inverse rotation, with angle −mω-m\omega; the key contributes nωn\omega. The relative rotation is therefore (n−m)ω(n-m)\omega, not (m+n)ω(m+n)\omega. Changing the sign convention for both rotations yields another coherent system, but changing only one convention changes the model. An implementation can produce numerically finite outputs and still degrade the result if query and key do not share the same pair layout.

The spectrum and its limits

The standard RoPE frequency spectrum uses ωr=θ−2r/dk\omega_r=\theta^{-2r/d_k} for r=0,…,dk/2−1r=0,\ldots,d_k/2-1, with base θ>1\theta>1. The pair’s wavelength is 2π/ωr2\pi/\omega_r tokens. The fastest pair has period 2π2\pi; the slowest frequency exceeds 1/θ1/\theta because its final index is dk/2−1d_k/2-1. If training context is shorter than its period, that pair travels less than one revolution and provides a slowly varying channel, not an exactly position-free coordinate.

InteractiveFrequencies and correlation
  • Correlation in this example
  • Bound on its absolute value
4.0
32
128
Pairs with wavelength longer than the context10 / 16
Longest wavelength35332.9
Change base, dimension, and context. The first curve is the normalized cosine sum for identical vectors with equal energy per pair; the second bounds its absolute value. The counter shows how many pairs do not complete a revolution within the context.

For this example with q=kq=k and equal energy in each pair, the normalized score is C(Δ)=2dk∑rcos⁡(Δωr)C(\Delta)=\frac{2}{d_k}\sum_r\cos(\Delta\omega_r). The magnitude of the normalized complex sum 2dk∣∑reiΔωr∣\frac{2}{d_k}|\sum_r e^{\mathrm{i}\Delta\omega_r}| bounds ∣C(Δ)∣|C(\Delta)|, since the real part of a complex number does not exceed its modulus. This is the second curve: even this bound oscillates and can rise again; it is not a universal decreasing bound. By Cauchy-Schwarz, the general bound ∣⟨Rmq,Rnk⟩∣≤∥q∥∥k∥|\langle R_mq,R_nk\rangle|\le\|q\|\|k\| is constant. RoFormer’s decay analysis uses summation by parts and cancellation among frequencies; it does not make every individual score a monotone function of distance. Low frequencies, training, and content distribution matter.

InteractiveFour positional effects
Illustrative absolute table
Buckets (example)
ALiBi
RoPE (q = k)
12
0.25
Training length in this example8
Extend the sequence beyond 8. Each matrix shows an explicit function, not measured model weights. Blue indicates a positive effect and red negative; intensity represents magnitude saturated at 1.

In this comparison the absolute table contains illustrative values cos⁡(0.7i)\cos(0.7i) for the first eight positions, and the product of two entries represents their logit contribution; outside the table zero is used to make one possible extension explicit. Buckets use illustrative value −b/7-b/7, ALiBi uses the selected slope, and RoPE sums two cosines with frequencies 1 and 0.1. Actual learned biases can have either sign. The four panels are not probabilities and do not apply a causal mask: they distinguish the structure of their positional effects. The training-length boundary is a reference, not a behavior guarantee.

Lab: copying at a fixed distance

Train a two-head causal attention layer from scratch in NumPy. Each sequence contains uniform symbols from 0 through 7; the output is a mixture of fixed one-hot values and must copy the symbol three positions back. Query and key matrices are learned, as are the absolute table or T5 biases. Value projections are identity and heads are averaged, making this a deliberately restricted small model, not a full transformer with FFN. To find the correct symbol’s probability, probabilities of all keys containing that symbol are summed and the negative logarithm is taken afterward; this allows repeated symbols.

Train for 120 steps with independent batches of 16 sequences of length 12 and evaluate 256 new sequences at lengths 12 and 24. For the absolute table, unseen positions get the zero vector: this explicit choice enables comparison but does not necessarily describe how a production table is extended. ALiBi keeps slopes fixed and RoPE rotates interleaved pairs. The four methods have different positional parameters, so the comparison does not equalize capacity. A single seed does not establish a general ranking.

For a row with weights AhjA_{hj} and target symbol yy, define Mj=1M_j=1 if key jj contains yy and zero otherwise. Assigned probability is py=H−1∑h,jAhjMjp_y=H^{-1}\sum_{h,j}A_{hj}M_j. Before the softmax derivative, ∂(−log⁡py)/∂Ahj=−Mj/(Hpy)\partial(-\log p_y)/\partial A_{hj}=-M_j/(Hp_y). The softmax rule turns this into Ghj=Ahj(uhj−∑lAhluhl)G_{hj}=A_{hj}(u_{hj}-\sum_l A_{hl}u_{hl}). The code averages over batch and valid rows and propagates GG to Q and K. With RoPE, backward applies the inverse rotation because its Jacobian is orthogonal. For T5, it sums into the same table entry all contributions whose distances fall in that bucket.

[ ]Relative attention and gradients from scratchBrowser
import numpy as np

def rot(x, pos, inverse=False):
    d=x.shape[-1]
    angle=np.asarray(pos)[:,None]*10000.0**(-2*np.arange(d//2)/d)
    if inverse: angle=-angle
    c,s=np.cos(angle)[None,:,:],np.sin(angle)[None,:,:]
    a,b=x[...,0::2],x[...,1::2]
    out=np.empty_like(x); out[...,0::2]=a*c-b*s; out[...,1::2]=a*s+b*c
    return out

def bucket(rel_pos, num_buckets=32, max_distance=128, bidirectional=False):
    r=np.asarray(rel_pos); b=np.zeros_like(r,dtype=int)
    count=num_buckets
    if bidirectional:
        count//=2; b+=(r>0)*count; distance=np.abs(r)
    else: distance=np.maximum(-r,0)
    exact=count//2
    large=exact+(np.log(np.maximum(distance,exact)/exact)/np.log(max_distance/exact)*(count-exact)).astype(int)
    return b+np.where(distance<exact,distance,np.minimum(large,count-1))

def softmax(z):
    e=np.exp(z-np.max(z,axis=-1,keepdims=True)); return e/e.sum(axis=-1,keepdims=True)

def run(kind, steps=120, seed=7):
    rng=np.random.default_rng(seed); d=8; L=12; distance=3; B=16
    heads=2; dh=4
    Wq=rng.normal(0,0.1,(heads,d,dh)); Wk=rng.normal(0,0.1,(heads,d,dh)); P=np.zeros((L,d)); bias=np.zeros((heads,32))
    def forward(tokens, update=False):
        T=tokens.shape[1]; X=np.eye(d)[tokens]; H=X.copy()
        if kind=='absoluta': H[:,:min(T,L)]+=P[:min(T,L)]
        Q=np.einsum('btd,hdf->hbtf',H,Wq); K=np.einsum('btd,hdf->hbtf',H,Wk)
        if kind=='rope': Q=np.stack([rot(q,np.arange(T)) for q in Q]); K=np.stack([rot(k,np.arange(T)) for k in K])
        [email protected](0,1,3,2)/np.sqrt(dh)
        rel=np.arange(T)[None,:]-np.arange(T)[:,None]
        ids=bucket(rel)
        if kind=='t5': S=S+bias[:,ids][:,None,:,:]
        if kind=='alibi': S=S-np.array([0.25,0.0625])[:,None,None,None]*np.maximum(-rel,0)
        S=np.where(rel<=0,S,-1e9); A=softmax(S)
        target=np.roll(tokens,distance,axis=1)
        match=tokens[:,None,:]==target[:,:,None]
        mass=(A.mean(0)*match).sum(-1).clip(1e-12)
        valid=np.arange(T)>=distance
        loss=-np.log(mass[:,valid]).mean()
        pred=np.argmax(A.mean(0)@X,axis=-1)
        accuracy=(pred[:,valid]==target[:,valid]).mean()
        if update:
            dA=-match[None,:,:,:].astype(float)/(heads*mass[None,:,:,None]); G=A*(dA-(dA*A).sum(-1,keepdims=True))
            G[:,:,~valid,:]=0; G/=B*valid.sum()
            gq=G@K/np.sqrt(dh); gk=G.transpose(0,1,3,2)@Q/np.sqrt(dh)
            if kind=='rope': gq=np.stack([rot(q,np.arange(T),True) for q in gq]); gk=np.stack([rot(k,np.arange(T),True) for k in gk])
            dq=np.einsum('bti,hbtj->hij',H,gq); dk=np.einsum('bti,hbtj->hij',H,gk)
            if kind=='absoluta': P[:T]-=0.5*(np.einsum('hbtf,hdf->btd',gq,Wq)+np.einsum('hbtf,hdf->btd',gk,Wk)).sum(0)
            if kind=='t5':
                for h in range(heads): np.add.at(bias[h],ids.ravel(),-0.5*G[h].sum(0).ravel())
            Wq[:]-=0.5*dq; Wk[:]-=0.5*dk
        return loss,accuracy
    for _ in range(steps): forward(rng.integers(d,size=(B,L)),True)
    result=[]
    for length in (12,24):
        tokens=rng.integers(d,size=(256,length)); result.append(forward(tokens))
    return result

First we check the relative property for fixed vectors and a common shift. The rotation matrix also preserves each vector’s norm. In this cell positions are integers and the computation uses double precision.

[ ]Check the RoPE identityBrowser
rng = np.random.default_rng(9)
q = rng.normal(size=(1,1,8)); k = rng.normal(size=(1,1,8))
def score(m,n):
    return float((rot(q,[m])*rot(k,[n])).sum())
reference = score(3,11)
print('puntuación original:',reference,'desplazada:',score(40,48))
assert np.isclose(reference,score(40,48),atol=1e-12,rtol=0)
assert np.isclose(reference,score(0,8),atol=1e-12,rtol=0)
assert np.allclose(np.linalg.norm(rot(q,[40])),np.linalg.norm(q))

The derivative of symbol loss with respect to attention uses the sum of probabilities of all matching keys. Before training, check the softmax rule with central differences in a small case. This independent test also covers repeated keys.

[ ]Check the copying gradientBrowser
z = np.array([0.2,-0.3,0.8,0.1]); match = np.array([True,False,True,False])
def loss_of(z):
    p = softmax(z)
    return -np.log(p[match].sum())
p = softmax(z); mass = p[match].sum()
analytic = p - p*match/mass
h = 1e-6; eye = np.eye(len(z))
finite = np.array([(loss_of(z+h*e)-loss_of(z-h*e))/(2*h) for e in eye])
print('error de gradiente:',np.max(np.abs(analytic-finite)))
assert np.allclose(analytic,finite,atol=1e-9)
[ ]Train absoluteBrowser
result = run('absoluta')
print('absoluta', 'longitud 12:', result[0], 'longitud 24:', result[1])
[ ]Train t5Browser
result = run('t5')
print('t5', 'longitud 12:', result[0], 'longitud 24:', result[1])
[ ]Train alibiBrowser
result = run('alibi')
print('alibi', 'longitud 12:', result[0], 'longitud 24:', result[1])
[ ]Train ropeBrowser
result = run('rope')
print('rope', 'longitud 12:', result[0], 'longitud 24:', result[1])

In a reference run of this code, T5 reaches accuracy 1.0 at both sizes; the other variants stay near 0.3 to 0.4. This is consistent with a bucket directly learning exact distance 3 in this task, but does not demonstrate general superiority: other variants may need another architecture, initialization, data, or training. Evaluation samples differ from training batches.

Loss can be low even when several locations have the same symbol, because the task is to copy the symbol, not select a unique position. Accuracy is calculated after summing the probabilities of all keys with each symbol; it is therefore not the accuracy of retrieving the index three positions back. To audit alignment, also measure attention mass at that position. The first three rows have no valid target and are excluded from the average. Future positions receive a very negative logit before normalization and must not contribute information.

Conventions and precision

The interleaved representation orders (a0,b0,a1,b1,…)(a_0,b_0,a_1,b_1,\ldots); the halves representation orders (a0,a1,…,b0,b1,…)(a_0,a_1,\ldots,b_0,b_1,\ldots). Let PP be the permutation from the first to the second. If the input vector is a column, convert the output rows of WQW_Q and WKW_K using PWP W; if batches are rows and use XWXW, permute columns of WW. Biases and per-head ordering must also be converted. The rotated output changes order, but the dot product agrees when query and key are permuted consistently.

In generation with a cache, a new query needs its true absolute position, not position zero of a length-one batch. Calculate frequencies and angles in at least float32 before sine and cosine: bfloat16 represents large positions at low resolution and can round two different positions to the same phase. Converting the result to the attention type is a separate decision. Finite precision can make the algebraic identity approximate.

The next local cell compares an interleaved complex implementation with a real half-split one and Transformers’ apply_rotary_pos_emb. Example weights are permuted along the output axis of nn.Linear, which stores its matrix as (salida, entrada) (output, input). The example uses standard frequencies, shifted positions, and float32; it does not download a model.

[ ]Complex, real, and Llama RoPELocal GPU
import torch
import numpy as np
from transformers.models.llama.modeling_llama import apply_rotary_pos_emb

torch.manual_seed(19)
B,H,T,D = 2,2,5,8
pos = torch.arange(7,7+T,dtype=torch.float32)
freq = 10000.0 ** (-2*torch.arange(D//2,dtype=torch.float32)/D)
angle = pos[:,None]*freq[None,:]
cos = torch.cos(angle)[None,:,:].expand(B,-1,-1)
sin = torch.sin(angle)[None,:,:].expand(B,-1,-1)

def complex_interleaved(x):
    z = torch.view_as_complex(x.contiguous().reshape(*x.shape[:-1],D//2,2))
    phase = torch.polar(torch.ones_like(angle),angle)[None,None,:,:]
    return torch.view_as_real(z*phase).flatten(-2)

def real_halves(x):
    first,second = x.chunk(2,dim=-1)
    c,s = cos[:,None,:,:],sin[:,None,:,:]
    return torch.cat((first*c-second*s, first*s+second*c),dim=-1)

perm = torch.cat((torch.arange(0,D,2),torch.arange(1,D,2)))
x = torch.randn(B,H,T,D)
y_complex = complex_interleaved(x)
y_real = real_halves(x[...,perm])
assert torch.allclose(y_complex[...,perm],y_real,atol=1e-6)
cos_half = torch.cat((cos,cos),dim=-1)
sin_half = torch.cat((sin,sin),dim=-1)
llama_q,llama_k = apply_rotary_pos_emb(x[...,perm],x[...,perm],cos_half,sin_half)
assert torch.allclose(y_real,llama_q,atol=1e-6)
assert torch.allclose(llama_q,llama_k,atol=1e-6)

inputs = torch.randn(B,T,12)
Wq,Wk = torch.randn(D,12),torch.randn(D,12)
q = inputs @ Wq.T; k = inputs @ Wk.T
q_rot = complex_interleaved(q[:,None,:,:]); k_rot = complex_interleaved(k[:,None,:,:])
qh = inputs @ Wq[perm].T; kh = inputs @ Wk[perm].T
qh_rot = real_halves(qh[:,None,:,:]); kh_rot = real_halves(kh[:,None,:,:])
assert torch.allclose(q_rot @ k_rot.transpose(-1,-2),qh_rot @ kh_rot.transpose(-1,-2),atol=1e-5,rtol=1e-5)
print('error máximo frente a Llama:',float((y_real-llama_q).abs().max()))
print('error máximo de logits tras convertir pesos:',float((q_rot @ k_rot.transpose(-1,-2)-qh_rot @ kh_rot.transpose(-1,-2)).abs().max()))

from transformers.models.t5.modeling_t5 import T5Attention
rel = np.arange(-256,257)
for bidirectional in (False,True):
    expected=T5Attention._relative_position_bucket(torch.tensor(rel),bidirectional=bidirectional,num_buckets=32,max_distance=128)
    r=rel; count=16 if bidirectional else 32
    base=(r>0).astype(int)*count if bidirectional else np.zeros_like(r)
    distance=np.abs(r) if bidirectional else np.maximum(-r,0)
    exact=count//2
    large=exact+(np.log(np.maximum(distance,exact)/exact)/np.log(128/exact)*(count-exact)).astype(int)
    actual=base+np.where(distance<exact,distance,np.minimum(large,count-1))
    assert np.array_equal(actual,expected.numpy())
print('cubetas T5 coinciden para los 513 desplazamientos en ambos modos')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

Proof
Prove: Prove the relative RoPE identity for projection matrices and column vectors.
0
Each block of R is an orthogonal rotation with angle proportional to position.

Step 1 of 3. What is the transpose of R_m?

Numeric
With eight heads, calculate the ALiBi bias of the first head at distance 100.
Numeric
In the same example, what is the last head's bias at distance 100?
Numeric
For d_k = 128 and θ = 10000, calculate the slowest pair's wavelength in tokens.
Quiz
What does RoPE change before the attention product?
Quiz
Which statement distinguishes a learned absolute table from a T5 bias?
Code
Implement t5_relative_bucket(rel_pos, num_buckets, max_distance, bidirectional) with NumPy arrays. rel_pos is key minus query. In bidirectional mode separate signs; in causal mode assign future positions distance zero before masking. Divide available buckets equally between exact and logarithmic distances; saturate at the last. Assume num_buckets is divisible by 4 and max_distance exceeds the number of exact buckets.
import numpy as np
def t5_relative_bucket(rel_pos, num_buckets=32, max_distance=128, bidirectional=False):
  pass
Shift+Enter to run
Key idea
Relative positions are different structural assumptions: learned buckets, linear penalties, or Q and K rotations. RoPE’s relative identity is exact in real arithmetic for fixed content; generalizing to long contexts remains an experimental question.