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.
- Start with equal content scores. The raw scores are 0 for all three keys. Check: with equal scores, a softmax without bias would give each key weight .
- Measure the distance to each key. The query sits at position 3. The distance to key 1 is , to key 2 is , and to key 3 is . Check: nearer keys have smaller distances.
- Look up the bias for each distance. This head has a table with , and . 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.
- Add the bias to the score. The scores become . Check: the content part was zero, so the scores are exactly the biases.
- Apply softmax. The weights are , and . Check: the three weights add to 1.
- Form the output. If the values are , and , the output is . 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 be the query at position , and let and be the key and value at position . For one attention head with key dimension , the attention scores are
where is the bias for the offset . The output at position is the softmax of these scores times the values:
Here is the query position, is the key position, and runs over every key position so the softmax sums to 1.
Step 2 in symbols: the offset
The offset is the distance from key back to query . In the walkthrough, query and keys give offsets .
Step 3 in symbols: the table
A head holds one number per offset, , learned during training. The lookup 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 leaves the bias unchanged, since .
Steps 4 and 5 in symbols: the softmax
With scores , the weights are . Here adds the three exponentials, and the result is the weights .
Matrix form
For a full sequence, let be the matrix with entries . It is a Toeplitz matrix, which means every diagonal is constant. Then the attention layer is
Here , and stack the queries, keys and values as rows.
Worked examples
Two keys, at offsets 0 and 1 from the query. The head's table has and , so distance 1 is penalised. The content scores are equal, both 1.
- Scores with bias: key at offset 0 gets , and key at offset 1 gets .
- Exponentials: and .
- Sum: .
- Weights: for the current token and for the previous one.
- Check: .
Interpretation: a single negative number at offset 1 is enough to shift about 73 percent of the attention onto the current token.
A causal decoder uses the linear penalty for distance , with equal content scores. Compare the weights of four keys, at distances 0, 1, 2 and 3 from the query.
- Biases: , , and .
- Exponentials: , , and .
- Sum: .
- Weights: , , and .
- Check: the weights sum to 1, and each step back multiplies the weight by , since .
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.
A Swin Transformer window is 7 by 7 patches, which is 49 tokens. Offsets in each direction run from to because the largest difference between two positions in a window is 6 along each axis.
- Number of offsets along one axis: , from to .
- Entries in the two-dimensional table: .
- A full bias matrix for the 49 tokens would have entries.
- Check: , so the shared table is about 14 times smaller than the full matrix.
- With 3 heads, the table holds 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 to , giving per axis, so 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.
| Method | How it encodes distance | Beyond the trained length | Cost |
|---|---|---|---|
| Learned table with buckets (T5) | learned value per bucket | buckets stretch, but limited | small table |
| Learned table per window (Swin) | learned value per 2D offset | not needed; windows are fixed | small table |
| Linear penalty (ALiBi) | fixed slope times distance | extrapolates by formula | no parameters |
| Rotary embedding (RoPE) | rotation inside the dot product | depends on the method | no 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.