Rope.lean

Lean 4 source, lean/DataMiningAsObservation/Rope.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.

/-
Rope.lean. Chapter 0 section 0.11, the rotary position embedding.

A rotary position embedding rotates each query and key by an angle proportional to its
position. A rotation preserves length, and the dot product of a query rotated to position
`m` with a key rotated to position `n` equals the dot product of the query with the key
rotated by the difference `n − m`, so a head reads relative position and not absolute
position. The file states both for the two-dimensional rotation the embedding is built
from.
-/
import Mathlib

namespace DMO.Rope

/-- The rotation of the plane by angle `θ`. -/
noncomputable def rot (θ : ℝ) (v : Fin 2 → ℝ) : Fin 2 → ℝ :=
  ![Real.cos θ * v 0 - Real.sin θ * v 1, Real.sin θ * v 0 + Real.cos θ * v 1]

/-- **A rotation preserves length.** -/
theorem rot_length (θ : ℝ) (v : Fin 2 → ℝ) : rot θ v ⬝ᵥ rot θ v = v ⬝ᵥ v := by
  simp only [rot, dotProduct, Fin.sum_univ_two, Matrix.cons_val_zero, Matrix.cons_val_one]
  nlinarith [Real.sin_sq_add_cos_sq θ]

/-- **The dot product of two rotated vectors depends only on the angle difference.** -/
theorem rot_dot (θ φ : ℝ) (q k : Fin 2 → ℝ) : rot θ q ⬝ᵥ rot φ k = q ⬝ᵥ rot (φ - θ) k := by
  simp only [rot, dotProduct, Fin.sum_univ_two, Matrix.cons_val_zero, Matrix.cons_val_one, Real.cos_sub, Real.sin_sub]
  nlinarith [Real.sin_sq_add_cos_sq θ, Real.sin_sq_add_cos_sq φ]

/-- **A head reads relative position.** With the query at position `m` and the key at
position `n`, each rotated by the position times a base angle, the score depends on `n − m`
alone. -/
theorem relative_position (ω : ℝ) (m n : ℝ) (q k : Fin 2 → ℝ) :
    rot (ω * m) q ⬝ᵥ rot (ω * n) k = q ⬝ᵥ rot (ω * (n - m)) k := by
  rw [rot_dot]
  congr 1
  ring_nf

/-- **Shifting both positions by the same amount changes no score.** -/
theorem shift_invariant (ω m n s : ℝ) (q k : Fin 2 → ℝ) :
    rot (ω * (m + s)) q ⬝ᵥ rot (ω * (n + s)) k = rot (ω * m) q ⬝ᵥ rot (ω * n) k := by
  rw [relative_position, relative_position]
  congr 2
  ring

end DMO.Rope