DirectionQuantizer.lean

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

/-
DirectionQuantizer.lean. Chapter 11 section 11.2, the direction-only quantizer.

A direction-only quantizer stores each vector's length exactly and rounds its direction to a
unit codeword. The quantized vector has the original's length, its cosine with any query is
the codeword's cosine with that query, and its score against a query is the length times
the query's dot product with the codeword, so the score error is the length times the
query's dot product with the direction error. A key's cosine with its own quantized form
can therefore be near one while its score against a query moves by a multiple of its
length, which is the attention-key finding in one line.
-/
import Mathlib
import DataMiningAsObservation.DotProduct

namespace DMO.DirectionQuantizer

open DMO.DotProduct

variable {n : ℕ}

/-- The quantized vector, the original length times a unit codeword `u`. -/
noncomputable def quantized (v u : Fin n → ℝ) : Fin n → ℝ := Real.sqrt (v ⬝ᵥ v) • u

/-- **The length is stored exactly.** With a unit codeword the quantized vector has the
original's squared length. -/
theorem length_preserved (v u : Fin n → ℝ) (hu : u ⬝ᵥ u = 1) :
    quantized v u ⬝ᵥ quantized v u = v ⬝ᵥ v := by
  unfold quantized
  rw [smul_dotProduct, dotProduct_smul, hu, smul_eq_mul, smul_eq_mul, mul_one,
    Real.mul_self_sqrt (self_nonneg v)]

/-- **The score against a query is the length times the codeword's score.** -/
theorem score_eq (q v u : Fin n → ℝ) : q ⬝ᵥ quantized v u = Real.sqrt (v ⬝ᵥ v) * (q ⬝ᵥ u) := by
  unfold quantized
  rw [dotProduct_smul, smul_eq_mul]

/-- **The score error scales with the length.** The difference between the true score and the
quantized score is the length times the query's dot product with the direction error. -/
theorem score_error (q v u : Fin n → ℝ) (hv : v ⬝ᵥ v ≠ 0) :
    q ⬝ᵥ v - q ⬝ᵥ quantized v u
      = Real.sqrt (v ⬝ᵥ v) * (q ⬝ᵥ ((1 / Real.sqrt (v ⬝ᵥ v)) • v - u)) := by
  rw [score_eq, dotProduct_sub, dotProduct_smul, smul_eq_mul]
  have hs : Real.sqrt (v ⬝ᵥ v) ≠ 0 := by
    rw [Real.sqrt_ne_zero']; exact lt_of_le_of_ne (self_nonneg v) (Ne.symm hv)
  field_simp

/-- **The cosine with a query is the codeword's cosine**, since the cosine ignores length. -/
theorem cosine_eq (q v u : Fin n → ℝ) (hv : v ⬝ᵥ v ≠ 0) :
    cosine (quantized v u) q = cosine u q := by
  unfold quantized
  have hpos : 0 < Real.sqrt (v ⬝ᵥ v) := by
    rw [Real.sqrt_pos]; exact lt_of_le_of_ne (self_nonneg v) (Ne.symm hv)
  exact cosine_smul u q _ hpos

end DMO.DirectionQuantizer