Search

Search papers and lessons

Relative Position Bias

Level 3 · 11 min read

Relative position bias adds a learned or fixed number to each attention score, chosen by how far apart the two tokens are, so attention can favour nearby or specific offsets.

On this page

  • Colour = topic mix
  • Discrete math
  • Linear algebra
  • Neural network basics
  • Calculus
  • Architectures
  • Language & LLMs
  • ReadReady to readNot yet

TL;DR

Relative position bias tells an attention layer how far apart two tokens are by adding a number to their attention score, chosen by the distance between them. Attention can then favour tokens just before the current one, or tokens at a specific offset, without knowing their absolute positions. It is a simpler alternative to adding position vectors to the inputs, and it suits tasks where distance matters more than absolute location.

Builds on: Positional Encoding · Leads to: Multi-Head Attention, Rotary Position Embedding

Where it's used

Text-to-text models. The T5 family of transformers (Raffel et al., 2019) uses relative position biases in every attention layer. Distances are grouped into buckets, with exact buckets for nearby offsets and wider buckets for far ones, so the table of biases stays small.

Image windows. The Swin Transformer (Liu et al., 2021) splits an image into windows of 7 by 7 patches and runs attention inside each window. It adds a relative position bias that depends only on the difference in row and column between two patches, which is what lets the same window table serve every window in the image.

Long contexts with a linear penalty. ALiBi (Press, Smith and Lewis, 2021) skips the learned table and subtracts a penalty that grows linearly with distance, with a fixed slope per head. Because the penalty is a formula, it can be applied to distances the model never saw in training, which is why it is used for length extrapolation.

How it works

Take one tiny instance: a sequence of three tokens, and the last one attending to all three. Every token has the same content score with the query, so the content cannot decide the attention. Only the position can.

  1. Start with equal content scores. The raw scores q⊤kj/d\mathbf{q}^\top \mathbf{k}_j / \sqrt{d} are 0 for all three keys. Check: with equal scores, a softmax without bias would give each key weight 1/31/3.
  2. Measure the distance to each key. The query sits at position 3. The distance to key 1 is 3−1=23 - 1 = 2, to key 2 is 3−2=13 - 2 = 1, and to key 3 is 3−3=03 - 3 = 0. Check: nearer keys have smaller distances.
  3. Look up the bias for each distance. This head has a table with b0=0b_0 = 0, b1=1b_1 = 1 and b2=2b_2 = 2. So the biases for keys 1, 2 and 3 are 2, 1 and 0. Check: the bias grows with distance, so this head favours far tokens.
  4. Add the bias to the score. The scores become (0+2,0+1,0+0)=(2,1,0)(0 + 2, 0 + 1, 0 + 0) = (2, 1, 0). Check: the content part was zero, so the scores are exactly the biases.
  5. Apply softmax. The weights are e2/(e2+e1+e0)≈0.665e^{2} / (e^{2} + e^{1} + e^{0}) \approx 0.665, e1/(… )≈0.245e^{1} / (\dots) \approx 0.245 and e0/(… )≈0.090e^{0} / (\dots) \approx 0.090. Check: the three weights add to 1.
  6. Form the output. If the values are v1=(1,0)\mathbf{v}_1 = (1, 0), v2=(0,1)\mathbf{v}_2 = (0, 1) and v3=(1,1)\mathbf{v}_3 = (1, 1), the output is 0.665⋅(1,0)+0.245⋅(0,1)+0.090⋅(1,1)=(0.755,0.335)0.665 \cdot (1, 0) + 0.245 \cdot (0, 1) + 0.090 \cdot (1, 1) = (0.755, 0.335). Check: the output is a weighted average of the three values, so it lies inside their span.
flowchart LR
  A["Content scores q dot k over root d"] --> C["Add bias b for each offset"]
  B["Distance i minus j"] --> D["Look up bias table"]
  D --> C
  C --> E["Softmax over keys"]
  E --> F["Weighted sum of values"]

The math

Setup and the full formula

Let qi\mathbf{q}_i be the query at position ii, and let kj\mathbf{k}_j and vj\mathbf{v}_j be the key and value at position jj. For one attention head with key dimension dd, the attention scores are

sij=qi⊤kjd+bi−j,s_{ij} = \frac{\mathbf{q}_i^\top \mathbf{k}_j}{\sqrt{d}} + b_{i - j},

where bi−jb_{i - j} is the bias for the offset i−ji - j. The output at position ii is the softmax of these scores times the values:

oi=∑jexp⁡(sij)∑lexp⁡(sil) vj.\mathbf{o}_i = \sum_{j} \frac{\exp(s_{ij})}{\sum_{l} \exp(s_{il})} \, \mathbf{v}_j.

Here ii is the query position, jj is the key position, and ll runs over every key position so the softmax sums to 1.

Step 2 in symbols: the offset

The offset i−ji - j is the distance from key jj back to query ii. In the walkthrough, query i=3i = 3 and keys j=1,2,3j = 1, 2, 3 give offsets 2,1,02, 1, 0.

Step 3 in symbols: the table

A head holds one number per offset, b0,b1,b2,…b_0, b_1, b_2, \dots, learned during training. The lookup bi−jb_{i - j} returns one entry of that table. The table is shared across all positions, so the same offset gives the same bias everywhere in the sequence. That property is called translation invariance: shifting every position by the same amount cc leaves the bias unchanged, since (i+c)−(j+c)=i−j(i + c) - (j + c) = i - j.

Steps 4 and 5 in symbols: the softmax

With scores s=(2,1,0)s = (2, 1, 0), the weights are αj=esj/∑lesl\alpha_j = e^{s_j} / \sum_l e^{s_l}. Here ∑l\sum_l adds the three exponentials, and the result is the weights (0.665,0.245,0.090)(0.665, 0.245, 0.090).

Matrix form

For a full sequence, let BB be the matrix with entries Bij=bi−jB_{ij} = b_{i - j}. It is a Toeplitz matrix, which means every diagonal is constant. Then the attention layer is

Attention(Q,K,V)=softmax(QK⊤d+B)V.\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\left(\frac{Q K^\top}{\sqrt{d}} + B\right) V.

Here QQ, KK and VV stack the queries, keys and values as rows.

Worked examples

Example
1. Tiny: a bias that favours the current token

Two keys, at offsets 0 and 1 from the query. The head's table has b0=0b_0 = 0 and b1=−1b_1 = -1, so distance 1 is penalised. The content scores are equal, both 1.

  1. Scores with bias: key at offset 0 gets 1+0=11 + 0 = 1, and key at offset 1 gets 1+(−1)=01 + (-1) = 0.
  2. Exponentials: e1≈2.718e^{1} \approx 2.718 and e0=1e^{0} = 1.
  3. Sum: 2.718+1=3.7182.718 + 1 = 3.718.
  4. Weights: 2.718/3.718≈0.7312.718 / 3.718 \approx 0.731 for the current token and 1/3.718≈0.2691 / 3.718 \approx 0.269 for the previous one.
  5. Check: 0.731+0.269=1.0000.731 + 0.269 = 1.000.

Interpretation: a single negative number at offset 1 is enough to shift about 73 percent of the attention onto the current token.

Example
2. Standard: a linear penalty as a recency bias

A causal decoder uses the linear penalty bd=−0.5db_d = -0.5 d for distance dd, with equal content scores. Compare the weights of four keys, at distances 0, 1, 2 and 3 from the query.

  1. Biases: 00, −0.5-0.5, −1.0-1.0 and −1.5-1.5.
  2. Exponentials: e0=1e^{0} = 1, e−0.5≈0.6065e^{-0.5} \approx 0.6065, e−1.0≈0.3679e^{-1.0} \approx 0.3679 and e−1.5≈0.2231e^{-1.5} \approx 0.2231.
  3. Sum: 1+0.6065+0.3679+0.2231=2.19751 + 0.6065 + 0.3679 + 0.2231 = 2.1975.
  4. Weights: 0.4550.455, 0.2760.276, 0.1670.167 and 0.1020.102.
  5. Check: the weights sum to 1, and each step back multiplies the weight by e−0.5≈0.6065e^{-0.5} \approx 0.6065, since 0.276/0.455≈0.6070.276 / 0.455 \approx 0.607.

Interpretation: a fixed linear penalty gives a smooth recency preference with no table to learn, and the same formula covers any distance, including ones longer than any training sequence.

Example
3. Realistic: the size of a window table

A Swin Transformer window is 7 by 7 patches, which is 49 tokens. Offsets in each direction run from −6-6 to 66 because the largest difference between two positions in a window is 6 along each axis.

  1. Number of offsets along one axis: 2⋅7−1=132 \cdot 7 - 1 = 13, from −6-6 to 66.
  2. Entries in the two-dimensional table: 13⋅13=16913 \cdot 13 = 169.
  3. A full bias matrix for the 49 tokens would have 49⋅49=240149 \cdot 49 = 2401 entries.
  4. Check: 2401/169≈14.22401 / 169 \approx 14.2, so the shared table is about 14 times smaller than the full matrix.
  5. With 3 heads, the table holds 3⋅169=5073 \cdot 169 = 507 learned values, the same for every window in the image.

Interpretation: a table indexed by offset is much cheaper than a bias for every pair of positions, and it generalises because the same offset means the same thing in every window.

Try it: how many entries does the table have for windows of 8 by 8 patches? Answer: offsets run from −7-7 to 77, giving 2⋅8−1=152 \cdot 8 - 1 = 15 per axis, so 15⋅15=22515 \cdot 15 = 225 entries.

Common mistakes and tradeoffs

It is tempting to think that a relative bias replaces the content of the scores. In fact it is added to the score, so the content term still matters. A large enough content match can outweigh a penalty at a distance.

It is tempting to think that a relative bias gives the model absolute positions. In fact it knows only offsets. A token at position 1 and a token at position 100 with the same offset to the query get the same bias, so a model that needs to know which token is first has to find that from content or from another signal.

It is tempting to think a larger table always helps. In fact a learned table has entries only for the offsets seen in training. Offsets beyond that range need either bucketing, which groups far distances together, or a formula such as the linear penalty, which covers any distance.

MethodHow it encodes distanceBeyond the trained lengthCost
Learned table with buckets (T5)learned value per bucketbuckets stretch, but limitedsmall table
Learned table per window (Swin)learned value per 2D offsetnot needed; windows are fixedsmall table
Linear penalty (ALiBi)fixed slope times distanceextrapolates by formulano parameters
Rotary embedding (RoPE)rotation inside the dot productdepends on the methodno bias matrix

When to use a relative bias: when the task has a natural notion of distance, such as text or image windows, and when the model needs to favour particular offsets. When not to use it: when the model must know absolute positions, or when the bias matrix would be too large to build for every head and every layer. Alternatives: absolute encodings added to the inputs, which the Positional Encoding lesson covers, and rotary embeddings, which put position inside the dot product.

History

Absolute position vectors were introduced with the transformer in 2017, as sinusoidal encodings added to the inputs (Vaswani et al., 2017). Shaw, Uszkoreit and Vaswani (2018) then proposed relative position representations, which encode the distance between two positions inside the attention computation itself.

Later work made relative biases simpler and more general. The T5 models (Raffel et al., 2019) used bucketed relative biases shared across layers. The Swin Transformer (Liu et al., 2021) used a two-dimensional table for windows of patches, and ALiBi (Press, Smith and Lewis, 2021) replaced the learned table with a fixed linear penalty so that models could run on longer inputs than they were trained on.

Recap

  • A relative position bias adds a number to each attention score, chosen by the offset between the query and the key.
  • The bias depends only on the offset, so it is translation invariant and shared across all positions.
  • A table of biases is learned per head, or a formula such as a linear penalty is used instead.
  • A bias changes the weights only through the softmax, so it competes with the content term.
  • Read next: Multi-Head Attention for how many heads each keep their own table, and Rotary Position Embedding for an alternative that puts relative position inside the dot product.

Check yourself

QuestionRecall: what does a relative position bias depend on, and what does it not depend on?Show answer
It depends only on the offset between the query position and the key position. It does not depend on the absolute positions of the tokens, so the same offset gives the same bias anywhere in the sequence.
QuestionComputation: a head has bias table b0=0b_0 = 0, b1=−2b_1 = -2, and the content scores are equal. What are the attention weights for a query and two keys at offsets 0 and 1?Show answer
The scores are 00 and −2-2. The exponentials are 11 and e−2≈0.1353e^{-2} \approx 0.1353, with sum 1.13531.1353. The weights are 1/1.1353≈0.8811 / 1.1353 \approx 0.881 for offset 0 and 0.1353/1.1353≈0.1190.1353 / 1.1353 \approx 0.119 for offset 1.
QuestionWhy: why does a fixed linear penalty extrapolate to longer sequences better than a learned table?Show answer
A learned table has an entry only for offsets it saw in training, so offsets beyond that range have no value. A linear penalty is a formula, −m⋅d-m \cdot d for distance dd, so it gives a value for any distance, including ones longer than the training sequences.
QuestionApplied: a Swin-style model uses 8 by 8 windows, and a colleague proposes a full bias matrix for each window instead of a shared table. Why is the shared table the better choice?Show answer
The full matrix has 64⋅64=409664 \cdot 64 = 4096 entries per head, while the shared table has 15⋅15=22515 \cdot 15 = 225 entries per head. The table is also shared across every window, so each window learns from all the windows in the image, and the same offset means the same thing everywhere.

Sources