Softmax.lean

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

/-
Softmax.lean. Equation 0.23, the softmax.

The softmax of a list of scores exponentiates each and divides by the sum, so the results
are positive and add to one. Adding the same constant to every score leaves the softmax
unchanged, and the softmax preserves the ordering of the scores, so a strictly larger score
gets a strictly larger weight. These are the facts the attention file builds on.
-/
import Mathlib

namespace DMO.Softmax

open Finset

variable {ι : Type*} [Fintype ι]

/-- **Equation 0.23.** The softmax of the scores `z`. -/
noncomputable def softmax (z : ι → ℝ) (i : ι) : ℝ := Real.exp (z i) / ∑ j, Real.exp (z j)

/-- The normalizer is positive when there is at least one score. -/
theorem denom_pos [Nonempty ι] (z : ι → ℝ) : 0 < ∑ j, Real.exp (z j) :=
  Finset.sum_pos (fun j _ => Real.exp_pos (z j)) Finset.univ_nonempty

/-- **Every weight is positive.** -/
theorem softmax_pos [Nonempty ι] (z : ι → ℝ) (i : ι) : 0 < softmax z i :=
  div_pos (Real.exp_pos _) (denom_pos z)

/-- **The weights sum to one.** -/
theorem softmax_sum [Nonempty ι] (z : ι → ℝ) : ∑ i, softmax z i = 1 := by
  unfold softmax
  rw [← Finset.sum_div, div_self (denom_pos z).ne']

/-- **Shift invariance.** Adding the same constant to every score leaves the softmax unchanged. -/
theorem softmax_shift [Nonempty ι] (z : ι → ℝ) (c : ℝ) (i : ι) :
    softmax (fun j => z j + c) i = softmax z i := by
  unfold softmax
  simp only [Real.exp_add, ← Finset.sum_mul]
  rw [mul_div_mul_right _ _ (Real.exp_pos c).ne']

/-- **Order preservation.** A larger score gets a larger weight. -/
theorem softmax_lt_iff [Nonempty ι] (z : ι → ℝ) (i j : ι) : softmax z i < softmax z j ↔ z i < z j := by
  unfold softmax
  rw [div_lt_div_iff_of_pos_right (denom_pos z), Real.exp_lt_exp]

end DMO.Softmax