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 and key at position , begin with . 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 for clipped displacement modifies the logit to . Another table 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 , 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 be the number of buckets available for one sign and the number of exact distances. For distance , before saturation the assigned index is
where is the maximum reference distance. The result is clipped to . For the bucket is . In bidirectional mode use and add to the positive-side index; in causal mode use 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 to head ‘s logit, with positive slope . In the causal case only are used and the bias penalizes the distant past. With eight heads, slopes under the original geometric rule are . 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 , the ratio of their unnormalized weights is . 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 . 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 into two-coordinate blocks and rotates the query at position by and the key at position by . Each block is a Givens rotation and the total matrix is a block matrix . Only queries and keys are rotated, not values.
Euler’s formula makes the identity visible. For one pair, identify with and with . Rotation multiplies by or . The real product is the real part of the conjugate of the first times the second:
Equivalently in matrices, orthogonality and composition of rotations give . Therefore, for fixed content vectors,
The positional operation depends only on , but vectors 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 ; the key contributes . The relative rotation is therefore , not . 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 for , with base . The pair’s wavelength is tokens. The fastest pair has period ; the slowest frequency exceeds because its final index is . 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.
For this example with and equal energy in each pair, the normalized score is . The magnitude of the normalized complex sum bounds , 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 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.
In this comparison the absolute table contains illustrative values 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 , 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 and target symbol , define if key contains and zero otherwise. Assigned probability is . Before the softmax derivative, . The softmax rule turns this into . The code averages over batch and valid rows and propagates 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.
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 resultFirst 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.
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.
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)result = run('absoluta')
print('absoluta', 'longitud 12:', result[0], 'longitud 24:', result[1])result = run('t5')
print('t5', 'longitud 12:', result[0], 'longitud 24:', result[1])result = run('alibi')
print('alibi', 'longitud 12:', result[0], 'longitud 24:', result[1])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 ; the halves representation orders . Let be the permutation from the first to the second. If the input vector is a column, convert the output rows of and using ; if batches are rows and use , permute columns of . 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.
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')npm run lab and open the connection link.Exercises
Step 1 of 3. What is the transpose of R_m?
import numpy as np
def t5_relative_bucket(rel_pos, num_buckets=32, max_distance=128, bidirectional=False):
pass