Perplexity.lean
Lean 4 source, lean/DataMiningAsObservation/Perplexity.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Perplexity.lean. Equations 0.22 and 11.1, perplexity.
Perplexity is two to the power of the average number of bits the model spends per token.
It is at least one, since no probability exceeds one, it equals the vocabulary size for a
model that spreads its mass evenly, and it is monotone in the bits. The attention-key
finding of chapter 11 raised perplexity from 12.24 to 10643 at cosine 0.995, which is a
rise of more than nine bits per token, since 12.24 lies below two to the fourth and 10643
above two to the thirteenth.
-/
import Mathlib
namespace DMO.Perplexity
open Finset Real
/-- The average bits per token of a model assigning probability `p t` to the token at
position `t` over `T` positions. -/
noncomputable def bits (T : ℕ) (p : Fin T → ℝ) : ℝ := -(∑ t, logb 2 (p t)) / T
/-- **Equation 0.22.** Perplexity is two to the average bits. -/
noncomputable def perplexity (T : ℕ) (p : Fin T → ℝ) : ℝ := (2 : ℝ) ^ bits T p
/-- **Bits are nonnegative** when no probability exceeds one. -/
theorem bits_nonneg (T : ℕ) (p : Fin T → ℝ) (hp : ∀ t, 0 < p t) (hp1 : ∀ t, p t ≤ 1) :
0 ≤ bits T p := by
unfold bits
apply div_nonneg _ (by positivity)
rw [neg_nonneg]
exact Finset.sum_nonpos fun t _ => logb_nonpos (by norm_num) (hp t).le (hp1 t)
/-- **Perplexity is at least one.** -/
theorem one_le_perplexity (T : ℕ) (p : Fin T → ℝ) (hp : ∀ t, 0 < p t) (hp1 : ∀ t, p t ≤ 1) :
1 ≤ perplexity T p := by
unfold perplexity
exact Real.one_le_rpow (by norm_num) (bits_nonneg T p hp hp1)
/-- **A uniform model over `V` tokens has perplexity `V`.** -/
theorem perplexity_uniform (T V : ℕ) (hT : 0 < T) (hV : 0 < V) :
perplexity T (fun _ => 1 / V) = V := by
unfold perplexity bits
have hV' : (0 : ℝ) < V := by exact_mod_cast hV
have hT' : (T : ℝ) ≠ 0 := by exact_mod_cast hT.ne'
simp only [Finset.sum_const, Finset.card_univ, Fintype.card_fin, nsmul_eq_mul]
rw [one_div, logb_inv, mul_neg, neg_neg, mul_div_cancel_left₀ _ hT',
rpow_logb (by norm_num) (by norm_num) hV']
/-- **Perplexity is monotone in the bits.** -/
theorem perplexity_mono (T : ℕ) (p q : Fin T → ℝ) (h : bits T p ≤ bits T q) :
perplexity T p ≤ perplexity T q :=
rpow_le_rpow_of_exponent_le (by norm_num) h
/-- **The chapter 11 numbers.** A perplexity of 12.24 is under four bits per token and 10643
is over thirteen, so the reconstruction cost more than nine bits per token. -/
theorem bits_of_finding : logb 2 (12.24 : ℝ) < 4 ∧ 13 < logb 2 (10643 : ℝ) := by
constructor
· rw [logb_lt_iff_lt_rpow (by norm_num) (by norm_num)]
norm_num
· rw [lt_logb_iff_rpow_lt (by norm_num) (by norm_num)]
norm_num
end DMO.Perplexity