Sinusoidal Position Encoding › The Relative Position Property

Michael BrenndoerferUpdated June 6, 202510 min read
Language AI HandbookAll chapters
Part 14 of 67Positional Encoding
Chapter 97Sinusoidal Position Encoding › The Relative Position Property
Reading section 7 of 15 · The Relative Position Property · 10 minSection 7 of 15 · 10 min

Book contents

Section 7 of 15 · 10 min read

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 kk, there exists a matrix MkM_k such that:

PEpos+k=PEpos⋅MkPE_{pos+k} = PE_{pos} \cdot M_k

where:

  • PEposPE_{pos}: the position encoding vector at position pospos (a dd-dimensional row vector)
  • PEpos+kPE_{pos+k}: the position encoding vector at position pos+kpos + k
  • MkM_k: a d×dd \times d transformation matrix that depends only on the offset kk, not on the absolute position

This is a remarkable property. It means that the relationship between any two encodings that are kk 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 aa and bb, trigonometry gives us:

sin⁡(a+b)=sin⁡(a)cos⁡(b)+cos⁡(a)sin⁡(b)\sin(a + b) = \sin(a)\cos(b) + \cos(a)\sin(b) cos⁡(a+b)=cos⁡(a)cos⁡(b)−sin⁡(a)sin⁡(b)\cos(a + b) = \cos(a)\cos(b) - \sin(a)\sin(b)

where aa and bb 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 ii, we define the angular frequency as:

ωi=1100002i/d\omega_i = \frac{1}{10000^{2i/d}}

where:

  • ωi\omega_i: the angular frequency for dimension pair ii (determines how fast this dimension oscillates)
  • ii: the dimension pair index (0, 1, 2, ..., d/2−1d/2 - 1)
  • dd: the total embedding dimension
  • 100002i/d10000^{2i/d}: the denominator that grows geometrically with ii

This means the encoding at position pospos in dimension pair ii uses the argument ωi⋅pos\omega_i \cdot pos.

Step 3: Apply the addition formulas. To find the encoding at position pos+kpos + k, we substitute a=ωi⋅posa = \omega_i \cdot pos and b=ωi⋅kb = \omega_i \cdot k into the angle addition formulas:

sin⁡(ωi(pos+k))=sin⁡(ωi⋅pos)cos⁡(ωik)+cos⁡(ωi⋅pos)sin⁡(ωik)\sin(\omega_i(pos + k)) = \sin(\omega_i \cdot pos)\cos(\omega_i k) + \cos(\omega_i \cdot pos)\sin(\omega_i k) cos⁡(ωi(pos+k))=cos⁡(ωi⋅pos)cos⁡(ωik)−sin⁡(ωi⋅pos)sin⁡(ωik)\cos(\omega_i(pos + k)) = \cos(\omega_i \cdot pos)\cos(\omega_i k) - \sin(\omega_i \cdot pos)\sin(\omega_i k)

where:

  • ωi=1/100002i/d\omega_i = 1/10000^{2i/d}: the angular frequency for dimension pair ii
  • pospos: the current position in the sequence
  • kk: the position offset we want to shift by
  • sin⁡(ωi⋅pos)\sin(\omega_i \cdot pos) and cos⁡(ωi⋅pos)\cos(\omega_i \cdot pos): the original encoding values at position pospos (these are PE(pos,2i)PE_{(pos, 2i)} and PE(pos,2i+1)PE_{(pos, 2i+1)})
  • sin⁡(ωik)\sin(\omega_i k) and cos⁡(ωik)\cos(\omega_i k): constants that depend only on the offset kk, not on the absolute position

The last two terms are fixed constants once you fix kk and ii: the values sin⁡(ωik)\sin(\omega_i k) and cos⁡(ωik)\cos(\omega_i k) do not change as you vary pospos. 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 sin⁡(ωi⋅pos)\sin(\omega_i \cdot pos) and cos⁡(ωi⋅pos)\cos(\omega_i \cdot pos). This is exactly what matrix multiplication does. We can write:

[sin⁡(ωi(pos+k))cos⁡(ωi(pos+k))]=[cos⁡(ωik)sin⁡(ωik)−sin⁡(ωik)cos⁡(ωik)][sin⁡(ωi⋅pos)cos⁡(ωi⋅pos)]\begin{bmatrix} \sin(\omega_i(pos + k)) \\ \cos(\omega_i(pos + k)) \end{bmatrix} = \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \\ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix} \begin{bmatrix} \sin(\omega_i \cdot pos) \\ \cos(\omega_i \cdot pos) \end{bmatrix}

This is a rotation in 2D. For each dimension pair, the encoding at pos+kpos + k is the encoding at pospos rotated by angle ωik\omega_i k. The rotation matrix for offset kk in dimension pair ii is:

Rk(i)=[cos⁡(ωik)sin⁡(ωik)−sin⁡(ωik)cos⁡(ωik)]R_k^{(i)} = \begin{bmatrix} \cos(\omega_i k) & \sin(\omega_i k) \\ -\sin(\omega_i k) & \cos(\omega_i k) \end{bmatrix}

where:

  • Rk(i)R_k^{(i)}: the 2x2 rotation matrix for dimension pair ii with offset kk
  • ωi=1/100002i/d\omega_i = 1/10000^{2i/d}: the angular frequency for dimension pair ii
  • kk: the position offset (how many positions to shift)
  • ωik\omega_i k: 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 MkM_k is block-diagonal, with each 2x2 block being the rotation matrix for that dimension pair:

Mk=[Rk(0)0⋯00Rk(1)⋯0⋮⋮⋱⋮00⋯Rk(d/2−1)]M_k = \begin{bmatrix} R_k^{(0)} & 0 & \cdots & 0 \\ 0 & R_k^{(1)} & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & R_k^{(d/2-1)} \end{bmatrix}

where:

  • MkM_k: the full d×dd \times d transformation matrix for offset kk
  • Rk(i)R_k^{(i)}: the 2x2 rotation matrix for dimension pair ii (defined above)
  • 00: 2x2 zero matrices (indicating no interaction between dimension pairs)
  • The matrix has d/2d/2 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 kk positions rotates it by its characteristic angle ωik\omega_i k. The faster the dimension's frequency (smaller ii), the larger the rotation for a given offset kk.

This rotation interpretation is more than a mathematical curiosity. It means that the inner product between two position encodings, PEpos1⋅PEpos2PE_{pos_1} \cdot PE_{pos_2}, depends only on their relative distance ∣pos1−pos2∣|pos_1 - pos_2|, 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:

In[16]:
Code
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]
Out[17]:
Console
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 pospos produces the encoding at position pos+kpos + k:

Out[18]:
Visualization
Plot showing position encodings as points on a circle with arrows indicating rotation from each position to its offset position.
Rotation property of sinusoidal encodings for dimension pair i=0. Each colored dot (circle) shows an original position encoding, and the matching square shows the encoding after a fixed offset of k=5. All arrows rotate by the same angle, confirming that the shift transformation depends only on the offset k, not on which absolute position you start from. This is the geometric essence of the relative position property.

The visualization makes the rotation property tangible. Each colored arrow shows the transformation from position pospos (circle) to position pos+5pos + 5 (square). Notice that all arrows rotate by the same angle, confirming that the transformation depends only on the offset kk, not on the starting position. This is the geometric essence of how sinusoidal encodings enable learning of relative positions.

Historical Context: From Sinusoidal Encoding to RoPE

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.