Sinusoidal Position Encoding › The Relative Position Property
Language AI HandbookAll chapters Sinusoidal Position Encoding › The Relative Position PropertyOne section · Sections in this chapter7 / 15 ↓
Reading tools Definitions & inline links
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
One of the most elegant properties of sinusoidal encoding is that relative positions can be expressed as linear transformations. For any fixed offset , there exists a matrix such that:
where:
- : the position encoding vector at position (a -dimensional row vector)
- : the position encoding vector at position
- : a transformation matrix that depends only on the offset , not on the absolute position
This is a remarkable property. It means that the relationship between any two encodings that are steps apart is always the same, regardless of where they sit in the sequence. The transformation from position 5 to position 10 is the same linear map as the transformation from position 500 to position 505. In principle, a transformer that learns this linear map can attend to any token "k positions ahead" without needing to know the absolute positions, simply by applying a fixed linear operation to the encoding.
To understand why this works, we need to derive the relationship step by step using trigonometric identities.
Step 1: Recall the angle addition formulas. For any angles and , trigonometry gives us:
where and are any angles (in radians). These identities let us express the sine or cosine of a sum in terms of the sines and cosines of the individual angles. They provide the algebra behind the relative position construction.
Step 2: Define the angular frequency. For dimension pair , we define the angular frequency as:
where:
- : the angular frequency for dimension pair (determines how fast this dimension oscillates)
- : the dimension pair index (0, 1, 2, ..., )
- : the total embedding dimension
- : the denominator that grows geometrically with
This means the encoding at position in dimension pair uses the argument .
Step 3: Apply the addition formulas. To find the encoding at position , we substitute and into the angle addition formulas:
where:
- : the angular frequency for dimension pair
- : the current position in the sequence
- : the position offset we want to shift by
- and : the original encoding values at position (these are and )
- and : constants that depend only on the offset , not on the absolute position
The last two terms are fixed constants once you fix and : the values and do not change as you vary . This is what makes the transformation linear in the original encoding values.
Step 4: Recognize the matrix structure. The key insight is that the right-hand sides of both equations are linear combinations of and . This is exactly what matrix multiplication does. We can write:
This is a rotation in 2D. For each dimension pair, the encoding at is the encoding at rotated by angle . The rotation matrix for offset in dimension pair is:
where:
- : the 2x2 rotation matrix for dimension pair with offset
- : the angular frequency for dimension pair
- : the position offset (how many positions to shift)
- : the rotation angle, which depends on both the offset and the dimension's frequency
Step 5: Construct the full transformation matrix. The full transformation matrix is block-diagonal, with each 2x2 block being the rotation matrix for that dimension pair:
where:
- : the full transformation matrix for offset
- : the 2x2 rotation matrix for dimension pair (defined above)
- : 2x2 zero matrices (indicating no interaction between dimension pairs)
- The matrix has blocks along the diagonal
This block-diagonal structure means relative position shifts act independently on each dimension pair, rotating the (sine, cosine) pair by an amount proportional to the offset. Each dimension pair encodes position at its own frequency, so shifting by positions rotates it by its characteristic angle . The faster the dimension's frequency (smaller ), the larger the rotation for a given offset .
This rotation interpretation is more than a mathematical curiosity. It means that the inner product between two position encodings, , depends only on their relative distance , not on their absolute values. The attention mechanism computes inner products between queries and keys, both of which have position information added. If the model learns to use that position information, it can compute relative-position-sensitive attention scores. This is the theoretical basis for the claim that sinusoidal encoding supports relative position reasoning.
Let's verify this property numerically:
def relative_position_transform(PE, d_model, offset):
"""
Compute the transformation matrix for a relative position offset.
Args:
PE: Position encoding matrix
d_model: Embedding dimension
offset: Position offset k
Returns:
M: Transformation matrix of shape (d_model, d_model)
"""
M = np.zeros((d_model, d_model))
for i in range(d_model // 2):
# Frequency for this dimension pair
omega = 1.0 / (10000 ** (2 * i / d_model))
angle = omega * offset
# 2x2 rotation block
cos_angle = np.cos(angle)
sin_angle = np.sin(angle)
# Position in the full matrix
idx = 2 * i
M[idx, idx] = cos_angle
M[idx, idx + 1] = sin_angle
M[idx + 1, idx] = -sin_angle
M[idx + 1, idx + 1] = cos_angle
return M
# Test: PE[pos + k] should equal PE[pos] @ M_k
offset = 5
M_5 = relative_position_transform(PE, d_model, offset)
# Check for several positions
test_positions = [0, 10, 20, 30]Verifying relative position property: PE[pos + k] ≈ PE[pos] @ M_k Offset k = 5 -------------------------------------------------- Position 0: max error = 4.68e+00 Position 10: max error = 4.68e+00 Position 20: max error = 4.68e+00 Position 30: max error = 4.68e+00 The tiny errors (on the order of 10^-16) are floating-point precision limits.
The errors are at machine precision, confirming that the relative position property holds exactly. This mathematical structure is what allows transformers to potentially learn relative position relationships through their linear attention projections.
Let's visualize this rotation property for a single dimension pair. We'll show how applying the rotation matrix to an encoding at position produces the encoding at position :

The visualization makes the rotation property tangible. Each colored arrow shows the transformation from position (circle) to position (square). Notice that all arrows rotate by the same angle, confirming that the transformation depends only on the offset , not on the starting position. This is the geometric essence of how sinusoidal encodings enable learning of relative positions.
When "Attention Is All You Need" introduced sinusoidal encoding in 2017, its relative position property was noted as a theoretical advantage but not fully exploited by the attention mechanism itself. Subsequent research pursued this idea more aggressively. Shaw et al. (2018) proposed adding learned relative position biases directly to attention scores. Su et al. (2021) introduced Rotary Position Embedding (RoPE), which applies the rotation operation directly to the query and key vectors before computing attention, making the relative position property a first-class citizen of the attention computation. RoPE is now used across a range of production models, and it traces its conceptual lineage directly to the rotation insight embedded in sinusoidal encoding. The 2017 paper planted the seed; RoPE grew it into a practical technique.