TeacherForcing.lean

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

/-
TeacherForcing.lean. Chapter 0 section 0.11, teacher forcing.

Under teacher forcing a model predicts each token from the correct prefix. Running free, it
predicts each token from its own earlier outputs. The two runs agree exactly as long as the
forced predictions match the reference, and they part company at the first token the model
gets wrong, after which the free run's context is no longer the reference's. Perplexity
is measured under teacher forcing, which is why a perplexity can be good while a free run
is not, and why the C-12 record's difference vanished when teacher forcing was applied.
-/
import Mathlib

namespace DMO.TeacherForcing

variable {α : Type*}

/-- The free run of a model for `n` steps, each token predicted from the model's own earlier
outputs. -/
def free (model : List α → α) : ℕ → List α
  | 0 => []
  | n + 1 => free model n ++ [model (free model n)]

/-- **The runs agree while the forced predictions are right.** If the model predicts the
reference's token from every reference prefix shorter than `N`, the free run of length `n`
is the reference's first `n` tokens for every `n ≤ N`. -/
theorem free_eq_take (model : List α → α) (ref : List α) (N : ℕ) (hN : N ≤ ref.length)
    (h : ∀ t, t < N → ∀ (ht : t < ref.length), model (ref.take t) = ref[t]) :
    ∀ n, n ≤ N → free model n = ref.take n := by
  intro n
  induction n with
  | zero => intro _; simp [free]
  | succ k ih =>
    intro hk
    have hkN : k < N := by omega
    have hkl : k < ref.length := by omega
    rw [free, ih (by omega), h k hkN hkl]
    rw [List.take_add_one, List.getElem?_eq_getElem hkl]
    rfl

/-- The free run has the length it was run for. -/
theorem free_length (model : List α → α) (n : ℕ) : (free model n).length = n := by
  induction n with
  | zero => simp [free]
  | succ k ih => simp [free, ih]

/-- **The runs part at the first error.** If the model's forced prediction at position `t` is
not the reference token, the free run of length `t + 1` is not the reference's prefix. -/
theorem free_ne_of_error (model : List α → α) (ref : List α) (t : ℕ) (ht : t < ref.length)
    (hbefore : ∀ s, s < t → ∀ (hs : s < ref.length), model (ref.take s) = ref[s])
    (herr : model (ref.take t) ≠ ref[t]) : free model (t + 1) ≠ ref.take (t + 1) := by
  intro heq
  have hfree : free model t = ref.take t :=
    free_eq_take model ref t ht.le hbefore t le_rfl
  rw [free, hfree, List.take_add_one, List.getElem?_eq_getElem ht] at heq
  have := List.append_inj_right heq (by simp)
  simp at this
  exact herr this

end DMO.TeacherForcing