Implement RoPE and prove the relative-position property
CPU · your Macnotebook90 minrequiredGoal · Write sinusoidal and rotary encodings from scratch and numerically demonstrate that RoPE dot products depend only on relative offset.
- 1Implement sinusoidal_pe(T, d) from the formula and plot it as a (T, d) heatmap for T=128, d=64.
- 2Implement rope(x, positions, theta=10000) using the rotate_half trick on tensors of shape (T, d).
- 3Generate a random q and k of dimension 64; compute dot(rope(q, m), rope(k, n)) for (m, n) in [(0, 5), (10, 15), (100, 105)] and show the three values are equal within 1e-5.
- 4Repeat with sinusoidal added encodings and show the dot products are not equal.
- 5Load TinyLlama and compare your rope output on a random tensor with the model's apply_rotary_pos_emb using its rotary_emb cos/sin.
- 6Change theta to 500000 and plot how the rotation angle of dimension pair 0 and pair 31 changes with position.
- Deliverable
- A notebook with the equality assertion, the TinyLlama match and the two heatmaps.
- Check
- The three RoPE dot products agree within 1e-5 and your rope matches apply_rotary_pos_emb at atol 1e-5.