Contrastive.lean

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

/-
Contrastive.lean. Chapter 12 section 12.4, the contrastive objective.

A contrastive objective pulls pairs declared similar together and pushes other pairs
apart. With a margin loss, the loss is nonnegative and is zero exactly when every declared
pair scores above every other pair by the margin. Swapping which pairs are declared similar
reverses that condition, and with a positive margin no scorer can satisfy both, so the
declared pairs are where an encoder learns what similar means, and not the data alone.
-/
import Mathlib

namespace DMO.Contrastive

open Finset

variable {π : Type*}

/-- The margin loss over the declared-similar pairs `P` and the other pairs `N`, with a
similarity score `s` on pairs and margin `m`. -/
noncomputable def loss (P N : Finset π) (s : π → ℝ) (m : ℝ) : ℝ :=
  ∑ p ∈ P, ∑ n ∈ N, max 0 (m - (s p - s n))

/-- **The loss is nonnegative.** -/
theorem loss_nonneg (P N : Finset π) (s : π → ℝ) (m : ℝ) : 0 ≤ loss P N s m :=
  Finset.sum_nonneg fun _ _ => Finset.sum_nonneg fun _ _ => le_max_left _ _

/-- **Zero loss means every declared pair beats every other pair by the margin.** -/
theorem loss_eq_zero_iff (P N : Finset π) (s : π → ℝ) (m : ℝ) :
    loss P N s m = 0 ↔ ∀ p ∈ P, ∀ n ∈ N, s n + m ≤ s p := by
  unfold loss
  rw [Finset.sum_eq_zero_iff_of_nonneg fun p _ => Finset.sum_nonneg fun n _ => le_max_left _ _]
  constructor
  · intro h p hp n hn
    have := (Finset.sum_eq_zero_iff_of_nonneg fun n _ => le_max_left _ _).1 (h p hp) n hn
    rw [max_eq_left_iff] at this
    linarith
  · intro h p hp
    apply Finset.sum_eq_zero
    intro n hn
    rw [max_eq_left_iff]
    linarith [h p hp n hn]

/-- **The declared pairs decide.** With a positive margin and at least one pair on each side,
a scorer cannot have zero loss for both a declaration and its swap. -/
theorem not_both (P N : Finset π) (hP : P.Nonempty) (hN : N.Nonempty) (s : π → ℝ) (m : ℝ)
    (hm : 0 < m) : ¬ (loss P N s m = 0 ∧ loss N P s m = 0) := by
  rintro ⟨h1, h2⟩
  rw [loss_eq_zero_iff] at h1 h2
  obtain ⟨p, hp⟩ := hP
  obtain ⟨n, hn⟩ := hN
  have := h1 p hp n hn
  have := h2 n hn p hp
  linarith

/-- A larger margin never lowers the loss. -/
theorem loss_mono_margin (P N : Finset π) (s : π → ℝ) (m m' : ℝ) (h : m ≤ m') :
    loss P N s m ≤ loss P N s m' := by
  unfold loss
  apply Finset.sum_le_sum; intro p _
  apply Finset.sum_le_sum; intro n _
  exact max_le_max le_rfl (by linarith)

end DMO.Contrastive