Quantization.lean
Lean 4 source, lean/DataMiningAsObservation/Quantization.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.
/-
Quantization.lean. Chapter 0 section 0.11 and chapter 11 section 11.2, quantization.
A uniform quantizer with step `Δ` replaces a number by the nearest multiple of `Δ`, so the
error is at most half a step and is zero on a level. A per-channel quantizer chooses a step
per coordinate, so the squared error of a vector is at most the sum of the squared half
steps, and a finer step on one coordinate lowers that bound for that coordinate alone. What
a quantizer does to a consumer is a separate question, which the flip and the attention-key
finding answer, and the error bounds here are the identity reader's.
-/
import Mathlib
namespace DMO.Quantization
open Finset
/-- The uniform quantizer with step `Δ`, the nearest multiple of `Δ`. -/
noncomputable def quantize (Δ x : ℝ) : ℝ := Δ * round (x / Δ)
/-- **The error is at most half a step.** -/
theorem error_le_half_step (Δ x : ℝ) (hΔ : 0 < Δ) : |x - quantize Δ x| ≤ Δ / 2 := by
unfold quantize
have h := abs_sub_round (x / Δ)
have : x - Δ * round (x / Δ) = Δ * (x / Δ - round (x / Δ)) := by field_simp
rw [this, abs_mul, abs_of_pos hΔ]
calc Δ * |x / Δ - round (x / Δ)| ≤ Δ * (1 / 2) := mul_le_mul_of_nonneg_left h hΔ.le
_ = Δ / 2 := by ring
/-- **A level quantizes to itself.** -/
theorem quantize_level (Δ : ℝ) (hΔ : 0 < Δ) (k : ℤ) : quantize Δ (Δ * k) = Δ * k := by
unfold quantize
rw [mul_div_cancel_left₀ _ hΔ.ne', round_intCast]
/-- **Halving the step halves the error bound.** -/
theorem half_step_bound (Δ : ℝ) : (Δ / 2) / 2 = Δ / 4 := by ring
variable {n : ℕ}
/-- The per-channel quantizer, a step per coordinate. -/
noncomputable def quantizeVec (Δ : Fin n → ℝ) (x : Fin n → ℝ) (i : Fin n) : ℝ := quantize (Δ i) (x i)
/-- **The squared error of a per-channel quantizer is at most the sum of the squared half
steps.** -/
theorem sq_error_le (Δ x : Fin n → ℝ) (hΔ : ∀ i, 0 < Δ i) :
∑ i, (x i - quantizeVec Δ x i) ^ 2 ≤ ∑ i, (Δ i / 2) ^ 2 := by
apply Finset.sum_le_sum
intro i _
unfold quantizeVec
have h := error_le_half_step (Δ i) (x i) (hΔ i)
have h0 : 0 ≤ Δ i / 2 := by linarith [hΔ i]
calc (x i - quantize (Δ i) (x i)) ^ 2 = |x i - quantize (Δ i) (x i)| ^ 2 := (sq_abs _).symm
_ ≤ (Δ i / 2) ^ 2 := pow_le_pow_left₀ (abs_nonneg _) h 2
/-- **A finer step on one coordinate lowers that coordinate's bound alone.** -/
theorem finer_step (Δ Δ' : Fin n → ℝ) (hΔ : ∀ i, 0 < Δ i) (hle : ∀ i, Δ' i ≤ Δ i) (hΔ' : ∀ i, 0 < Δ' i) :
∑ i, (Δ' i / 2) ^ 2 ≤ ∑ i, (Δ i / 2) ^ 2 := by
apply Finset.sum_le_sum
intro i _
have := hΔ' i
have := hΔ i
have := hle i
nlinarith
end DMO.Quantization