SDE & MLE Prep

Positional Encodings: Sinusoidal & RoPE

Key idea: sinusoidal encodings add sin/cos(pos / 10000^(2i/d)) to the embeddings. RoPE instead rotates each pair of query/key dimensions by an angle proportional to the position, so the dot product q_m · k_n depends only on the offset m − n.

import numpy as np

def sinusoidal(n_pos, d):
    pos = np.arange(n_pos)[:, None]
    angle = pos / 10000 ** (np.arange(0, d, 2)[None, :] / d)
    pe = np.zeros((n_pos, d))
    pe[:, 0::2], pe[:, 1::2] = np.sin(angle), np.cos(angle)
    return pe

def rope(x, pos, base=10000.0):           # x: (..., d), d even; rotate pairs (x[2i], x[2i+1])
    d = x.shape[-1]
    ang = np.asarray(pos)[..., None] * base ** (-np.arange(0, d, 2) / d)
    cos, sin = np.cos(ang), np.sin(ang)
    x1, x2 = x[..., 0::2], x[..., 1::2]
    out = np.empty_like(x)
    out[..., 0::2] = x1 * cos - x2 * sin
    out[..., 1::2] = x1 * sin + x2 * cos
    return out

pe = sinusoidal(50, 16)
assert pe.shape == (50, 16) and np.allclose(pe[0], np.tile([0, 1], 8))
rng = np.random.default_rng(0)
q, k = rng.normal(size=8), rng.normal(size=8)
assert np.isclose(rope(q, 3) @ rope(k, 7), rope(q, 10) @ rope(k, 14))   # only the offset (4) matters
assert np.isclose(np.linalg.norm(rope(q, 5)), np.linalg.norm(q))        # rotation preserves norms
X = rng.normal(size=(5, 8))
assert np.allclose(rope(X, np.arange(5))[2], rope(X[2], 2))              # batched == per position
print("ok", round(float(rope(q, 3) @ rope(k, 7)), 4))