RoPE

Let an input vector \(x \in \mathbb{R}^d\) (where \(d\) is even) be split into two halves: \((x_1, x_2, \dots, x_{d/2})\) and \((x_{d/2+1}, x_{d/2+2}, \dots, x_d)\).

\[ \operatorname{rope}(x, m) = x \odot \cos(m\theta) + \operatorname{halfrotate}(x) \odot \sin(m\theta) \]

where \(m\) is the token position, \(\theta\) is the vector of rotation frequencies, and \(\operatorname{halfrotate}(x)\) swaps the two halves while negating the second half:

\[ \operatorname{halfrotate}(x) = (-x_{d/2+1}, -x_{d/2+2}, \dots, -x_d, x_1, x_2, \dots, x_{d/2}) \]

import numpy as np
import matplotlib.pyplot as plt

def half_rotate(x):
    d = x.shape[-1]
    x1, x2 = x[..., :d//2], x[..., d//2:]
    return np.concatenate([-x2, x1], axis=-1)

def rope(x, position, base=10000.0):
    d = x.shape[-1]
    # Compute inverse frequencies for each pair of dimensions
    inv_freq = 1.0 / (base ** (np.arange(0, d, 2) / d))
    # Duplicate frequencies so they match the split-half layout
    freqs = np.concatenate([inv_freq, inv_freq], axis=-1)
    
    # Angle = position * frequency
    theta = np.outer(position, freqs) if np.ndim(position) > 0 else position * freqs
    return x * np.cos(theta) + half_rotate(x) * np.sin(theta)

# Example: An all-ones 64-dimensional embedding vector across 100 token positions
d = 64
seq_len = 100
x = np.ones((seq_len, d))
positions = np.arange(seq_len)

y = rope(x, positions)

# Plot how the embedding values change across positions for a few dimensions
plt.plot(positions, y[:, 0], label="Dim 0 (High freq)")
plt.plot(positions, y[:, 10], label="Dim 10 (Mid freq)")
plt.plot(positions, y[:, 31], label="Dim 31 (Low freq)")
plt.xlabel("Token Position")
plt.ylabel("Rotated Value")
plt.title("RoPE applied across sequence positions")
plt.legend()
plt.show()

# plotly heat map of the RoPE embeddings across positions and dimensions
import plotly.graph_objects as go

fig = go.Figure(data=go.Heatmap(z=y, x=np.arange(d), y=np.arange(seq_len), colorscale='Viridis'))
fig.update_layout(title='RoPE Embeddings Heatmap', xaxis_title='Embedding Dimension', yaxis_title='Token Position')
fig.show()