Relative position: encode the relation between two tokens
相对位置表示
Compare relative keys, relative values and scalar biases with explicit clipped offsets.
relative-position“Two places to the left” can matter more than “position seventeen”
An adjective may help interpret a noun because it is nearby, not because both happen to occupy particular numbered slots. Relative position representations attach information to a pair of tokens: how far apart are the query and the key, and in which direction?
Shaw and colleagues add learned relative vectors to both the key-side score and the value-side message. T5 uses a simpler learned scalar bias in attention logits, with distances grouped into buckets. These are related design choices, not identical formulas. Begin with self-attention and positional encoding.
Put the relation in the score, the message, or both
Use i for a query position and j for a key position. The signed offset is key minus query. Clipping at radius K assigns all more distant offsets on each side to that side’s end entry:
A radius of two creates five table entries, for offsets minus two through two. Clipping is a modeling choice: it discards precise distance beyond the radius in this positional term. It does not make all distant tokens identical, because their content vectors can still differ.
Let q_i and k_j have width d_k. A relative-key vector with the same width modifies compatibility as follows:
The new term is a dot product with the query. Two different queries can receive opposite positional contributions from the same relative vector. This is more expressive than one fixed scalar assigned solely to that offset, though whether that flexibility helps is an experimental question.
A separate relative-value vector carries relation information into the output:
Its width matches the values, which need not equal the key width. Relative keys change the attention weights; relative values change what is aggregated. If only the relative-value table changes in this layer, the weights remain fixed while the output changes linearly:
For a hand calculation, take a scalar query of one, two zero content keys, values two and four, relative-key contributions zero and log three, and relative values zero and ten. The weights are one quarter and three quarters, so the output is eleven. Without the relative values it would be three and a half.
T5’s scalar alternative adds a learned bias after the content score. Its distance buckets are coarser farther away. Compare the two score forms explicitly:
The selected T5 description uses head-specific biases shared across layers. Our program implements clipped Shaw-style vector tables, not T5’s logarithmic bucket mapping. Do not call a clipped vector lookup a reproduction of T5 merely because both use relative positions.
A common shift of all query and key positions leaves the offsets unchanged:
Consequently this layer gives the same result when content vectors, pair availability and relative tables stay fixed. This is a statement about reindexing the same content. Moving or deleting tokens, changing boundary visibility, or changing earlier absolute-position features need not preserve the result.
Change a relation without changing a token
Save as relative_position.py and run with Python 3 and NumPy. All tables are fixed synthetic arrays; no model is trained.
"""Original clipped Shaw-style key/value experiment, plus a scalar-bias comparison."""
import json
import numpy as np
def offsets(qpos,kpos,radius):
q,k=np.asarray(qpos),np.asarray(kpos)
if not isinstance(radius,int) or not 0<=radius<=32 or any(a.ndim!=1 or not a.size or a.size>128 or a.dtype.kind not in 'iu' for a in (q,k)):
raise ValueError('bounded integer positions and radius0..32 required')
return np.clip(k[None,:]-q[:,None],-radius,radius).astype(int)+radius
def relative_attention(q,k,v,qpos,kpos,rk,rv):
q,k,v,rk,rv=[np.asarray(a,dtype=float) for a in (q,k,v,rk,rv)]
if any(a.ndim!=2 or not a.size or max(a.shape)>128 or not np.isfinite(a).all() for a in (q,k,v,rk,rv)):
raise ValueError('finite bounded matrices required')
if q.shape[1]!=k.shape[1] or len(k)!=len(v) or rk.shape[1]!=q.shape[1] or rv.shape[1]!=v.shape[1] or len(rk)!=len(rv) or len(rk)%2!=1:
raise ValueError('incompatible projections or relative tables')
idx=offsets(qpos,kpos,(len(rk)-1)//2)
if idx.shape!=(len(q),len(k)):raise ValueError('position counts differ')
scores=(q @ k.T+np.einsum('id,ijd->ij',q,rk[idx]))/np.sqrt(q.shape[1])
a=np.exp(scores-scores.max(axis=1,keepdims=True));a/=a.sum(axis=1,keepdims=True)
out=a @ v+np.einsum('ij,ijv->iv',a,rv[idx])
return out,a,scores
def demo():
rng=np.random.default_rng(42);q=rng.normal(size=(5,2));k=rng.normal(size=(5,2));v=rng.normal(size=(5,2))
rk=rng.normal(size=(5,2));rv=rng.normal(size=(5,2));p=np.arange(5)
y,a,s=relative_attention(q,k,v,p,p,rk,rv);translated=relative_attention(q,k,v,p+11,p+11,rk,rv)[0]
y0,a0,s0=relative_attention(q,k,v,p,p,rk,np.zeros_like(rv))
# Equal content: far offsets have identical clipped position contributions.
sameq=np.ones((1,2));samek=np.zeros((4,2));samev=np.zeros((4,2))
_,_,clipped=relative_attention(sameq,samek,samev,[0],[1,2,8,50],rk,rv)
qs=np.array([[1.,0.],[-1.,0.]]);rs=np.array([2.,0.]);query_dependent=qs @ rs/np.sqrt(2)
return dict(relative_index_grid=offsets(p,p,2).tolist(),translation_error=float(np.max(np.abs(y-translated))),
value_terms_output_gap=float(np.max(np.abs(y-y0))),value_terms_weight_error=float(np.max(np.abs(a-a0))),
clipped_offsets=[1,2,8,50],clipped_logits=clipped[0].tolist(),
opposite_query_relative_logits=query_dependent.tolist(),attention_weights=a.tolist(),
scope='Fixed random tables, no training or T5 bucket reproduction. Relative offsets are key minus query.')
if __name__ == '__main__':print(json.dumps(demo(),indent=2))
The five-by-five index grid makes the sign convention visible. Translating both position arrays by eleven changes the output by zero. Removing the relative-value table changes the output by about 0.669768 while leaving the attention weights exactly unchanged. The separate equal-key example gives identical positional logits for offsets two, eight and fifty because the clipping radius is two.
The two opposite queries also give opposite relative-key contributions for the same vector. A single position-only scalar bias cannot equal both of those contributions. This does not mean scalar biases are generally worse; it identifies a difference in what the two parameterizations can represent.
For n tokens, the direct implementation materializes pair vectors with order n²(d_k+d_v) storage and performs order n²(d_k+d_v) work, in addition to content projections. Its tables have (2K+1)(d_k+d_v) parameters. Sharing tables across heads reduces parameter duplication, but does not remove the quadratic attention matrix. The original paper discusses reorganizing the computation to avoid unnecessarily broadcasting every pair across batch and head axes.
A small table cannot promise long-context generalization
Clipped representations can be evaluated on longer sequences because every offset still maps to an entry. That is different from showing a trained model works well there. Information from several layers can combine, and content remains visible, so a clipping radius is not a hard bound on the model’s total receptive field.
This example uses no padding or causal mask. A decoder would combine the relative score with a correctly indexed visibility mask. Packed sequences also need a policy for document boundaries. Reversing the offset sign without transforming the table swaps the meanings of left and right.
Inspect the relation separately from the content
- For query positions and key positions
[0,1,2], what are the table indices when K=1?
Answer: They are [[1,2,2],[0,1,2],[0,0,1]]. The center entry represents zero offset. Above the diagonal, keys lie to the right; below it, they lie to the left.
- Recompute the scalar example’s output with and without the relative-value term.
Answer: Softmax of zero and log three gives weights one quarter and three quarters. With relative values, the weighted sum is one quarter times two plus three quarters times fourteen, or eleven. Without them it is one quarter times two plus three quarters times four, or three and a half.
- If offsets eight and fifty share one clipped entry, must their total attention scores be equal?
Answer: No. Their relative-key contributions coincide for a fixed query, but different content keys can still produce different content dot products. The program uses equal keys deliberately to isolate the positional term.
- Change only the relative-value table, then stack another attention layer on top. Must the second layer’s weights stay unchanged?
Answer: No. The first layer’s own weights stay unchanged, but its outputs change. The second layer builds queries and keys from those changed outputs and can therefore change its weights. The invariance was local to one layer with fixed inputs.
Read the parameterization before comparing results
Shaw’s method introduces relation-aware key and value vectors and describes clipped sequential offsets as one case. T5’s model section uses scalar relative biases instead. This chapter checks those mechanisms with original finite calculations; it does not reproduce either paper’s translation or language benchmarks. Compare them with RoPE, which places relative position inside a rotation identity rather than an added vector or scalar.
Make a prediction, then check
What changes if only the relative-value table changes in one attention layer?
Learning objectives
- Compute signed and clipped pair offsets.
- Separate relative-key and relative-value effects.
- Compare query-dependent terms with scalar biases.
Prerequisites & connections
Explore related knowledge →References
- Self-Attention with Relative Position Representations
Peter Shaw; Jakob Uszkoreit; Ashish Vaswani · 2018 - Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer
Colin Raffel; Noam Shazeer; Adam Roberts; Katherine Lee; Sharan Narang; Michael Matena; Yanqi Zhou; Wei Li; Peter J. Liu · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author read Shaw sections2.1-3.3/PDF2/3 and T5 section2.1/PDF5. Six paired equations and four explained exercises; signed key-minus-query offsets, clipping, key/value separation, query-dependent terms and scalar-bias alternative. Fixed vector tables, not T5 bucket reproduction or translation training.
- Single AI author read Shaw sections2.1-3.3/PDF2/3 and T5 section2.1/PDF5. Six paired equations and four explained exercises; signed key-minus-query offsets, clipping, key/value separation, query-dependent terms and scalar-bias alternative. Fixed vector tables, not T5 bucket reproduction or translation training.
- Four computed SVG variants per topic. Fifteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. Initial text-coordinate precision assertion and visual-label refinements preserved. Full article acceptance recorded separately.
Source locations checked:
- Self-Attention with Relative Position Representations · Read sections2.1-3.3; PDF2/3 viewed: clipped key-minus-query offsets, relative keys/values and shared storage. No translation benchmark reproduction.
- Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer · Read section2.1, PDF4/5 text and PDF5 visually: scalar relative biases, per-head parameters shared across layers,32 buckets and distant-offset grouping. No T5 bucket implementation or full empirical survey audited.
Related topics