KVCache.lean

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

/-
KVCache.lean. Chapter 0 section 0.11 and chapter 11 section 11.1, the KV cache.

The cache holds the keys and values of every earlier token for every layer, so its size is
the product of layers, tokens, two, the head width, and the bits per number, linear in each.
Compressing it changes the keys the heads read. Since a head reads a key only through its
score against the query, a compression that preserves every score preserves every output,
and one that preserves the keys' cosine need not, which is the attention-key finding. The
file checks the size formula, the arithmetic of the chapter's compression ratios, and the
cache-level form of the score condition.
-/
import Mathlib
import DataMiningAsObservation.Attention

namespace DMO.KVCache

open DMO.Attention

/-- The cache size in bits. -/
def cacheBits (layers tokens width bitsPerNumber : ℕ) : ℕ := layers * tokens * 2 * width * bitsPerNumber

/-- **The size is linear in the tokens.** -/
theorem cacheBits_tokens (layers tokens width b : ℕ) :
    cacheBits layers (2 * tokens) width b = 2 * cacheBits layers tokens width b := by
  unfold cacheBits; ring

/-- **Halving the bits per number halves the cache.** Sixteen bits to eight. -/
theorem cacheBits_half (layers tokens width : ℕ) :
    cacheBits layers tokens width 8 * 2 = cacheBits layers tokens width 16 := by
  unfold cacheBits; ring

/-- **The chapter's ratios.** Keeping five percent of the tokens shrinks the cache twenty
times, and evicting ninety-seven percent leaves three percent. -/
theorem ratios : (1 : ℝ) / 0.05 = 20 ∧ (1 : ℝ) - 0.97 = 0.03 := by
  constructor <;> norm_num

variable {ι : Type*} [Fintype ι] [Nonempty ι] {d : ℕ}

omit [Nonempty ι] in
/-- **A compression that preserves every score preserves every output.** For every query in
the set, the compressed keys give the same head output as the originals. -/
theorem output_of_scores_preserved (Q : Finset (Fin d → ℝ)) (k k' : ι → Fin d → ℝ) (v : ι → ℝ)
    (h : ∀ q ∈ Q, ∀ i, q ⬝ᵥ k i = q ⬝ᵥ k' i) : ∀ q ∈ Q, output q k v = output q k' v :=
  fun q hq => output_congr q k k' v (h q hq)

/-- **Cosine is not the score.** Two keys with the same direction and different lengths have
cosine one with each other and different scores against a query that reads them. -/
theorem cosine_not_score (q k : Fin d → ℝ) (c : ℝ) (hc : c ≠ 1) (hq : q ⬝ᵥ k ≠ 0) :
    q ⬝ᵥ (c • k) ≠ q ⬝ᵥ k := by
  rw [dotProduct_smul, smul_eq_mul]
  intro h
  have : (c - 1) * (q ⬝ᵥ k) = 0 := by linarith
  rcases mul_eq_zero.1 this with h0 | h0
  · exact hc (by linarith)
  · exact hq h0

end DMO.KVCache