Augmentation graph, spectral contrastive loss, conductance and linear probe error
DefinitionSpectralContrastive_BasicObjects of Sections 3.1-3.3, 4.1 and Appendices B, D.1 of HaoChen, Wei, Gaidon and Ma (2021).
- Data model. The natural data form a finite set with population distribution (, ). Each has an augmentation distribution on the finite set of augmented data (). The set is the union of the supports of the with . Labels are .
- Augmentation graph (eq. 2). , with degree . A general weighted graph has nonnegative symmetric weights and positive degrees.
- Spectra (eq. 3, Definition B.1). with and , and . is the -th largest eigenvalue of and the -th smallest eigenvalue of (, with multiplicity).
- Conductance (Definitions 3.3, 3.4). For a set , . For , , the minimum over partitions of the vertex set into nonempty sets .
- Losses (eqs. 4, 6). The spectral contrastive loss is
for . Here independently with , and with an independent . The matrix factorization loss is for . 6. Linear probes (eq. 1). A head predicts on augmented data and on natural data, with ties broken arbitrarily. The error is , and the linear probe error is . 7. Label quantities (eqs. 18, 19). For , and . The squared probe loss is , where is the one-hot vector, and is the Frobenius norm. 8. Finite samples (Section 4.1). For a dataset the empirical loss is
The Rademacher complexity is with uniform on . Dataset probabilities are taken under .
Formalization Note Eigenvalues are the roots of the characteristic polynomial, sorted; indices outside give the value . The sparsest -partition value is likewise for (no surjection exists) and equals for . Most statements exclude these values by hypothesis; Theorem B.2 (no condition , so may be the value ) and part 2 of Theorem 3.8 (where may be ) do not, and remain true in those cases. A partition into nonempty sets is a surjection . Because the paper breaks argmax ties arbitrarily, is defined as the largest error over all admissible tie-breaking choices at both levels, so every bound proved for it holds for every tie-breaking rule. Linear heads are matrices acting by as in Section 3; the heads of Appendix B are their transposes, with the same Frobenius norm.
import Mathlib
/-!
HaoChen, Wei, Gaidon and Ma, *Provable Guarantees for Self-Supervised Deep Learning with Spectral
Contrastive Loss*, arXiv:2106.04156v7 (NeurIPS 2021): the finite natural/augmented data model,
the population augmentation graph, its normalized adjacency and Laplacian matrices and their
eigenvalues, Dirichlet conductance and sparsest partitions, the spectral contrastive and matrix
factorization losses, linear probes and their errors (Sections 3.1-3.3 and Appendix B), and the
empirical loss and Rademacher complexity of Section 4.1 and Appendix D.1.
-/
noncomputable section
namespace SpectralContrastive
section Graph
variable {V : Type*} [Fintype V] [DecidableEq V]
/-- Section 3.1: the total weight (degree) `w_x = ∑_{x'} w_{xx'}` of a vertex. -/
def degree (w : V → V → ℝ) (x : V) : ℝ := ∑ x', w x x'
/-- Lemma B.4 (p. 27): `G = (V, w)` is a weighted graph: the edge weights are nonnegative and
symmetric, and every vertex has positive total weight (so that `D^{-1/2}` exists). -/
def IsWeightedGraph (w : V → V → ℝ) : Prop :=
(∀ x x', 0 ≤ w x x') ∧ (∀ x x', w x x' = w x' x) ∧ (∀ x, 0 < degree w x)
/-- Eq. (3), p. 7: the normalized adjacency matrix `Ā = D^{-1/2} A D^{-1/2}`, with
`A_{xx'} = w_{xx'}` and `D = diag(w_x)`. -/
def normAdj (w : V → V → ℝ) : Matrix V V ℝ :=
fun x x' => w x x' / Real.sqrt (degree w x * degree w x')
/-- Definition B.1, p. 26: the normalized Laplacian matrix `L = I - D^{-1/2} A D^{-1/2}`. -/
def normLap (w : V → V → ℝ) : Matrix V V ℝ := 1 - normAdj w
/-- Section 3.1, p. 7: `γ_i`, the `i`-th largest eigenvalue of `Ā` (`i = 1, 2, …`), counted with
multiplicity, as the roots of the characteristic polynomial sorted in decreasing order. Statements
only use `1 ≤ i ≤ |V|`. -/
def adjEig (w : V → V → ℝ) (i : ℕ) : ℝ :=
((normAdj w).charpoly.roots.sort (· ≥ ·)).getD (i - 1) 0
/-- Appendix B.1, p. 26: `λ_i`, the `i`-th smallest eigenvalue of `L` (`i = 1, 2, …`), counted
with multiplicity, as the roots of the characteristic polynomial sorted in increasing order.
Statements only use `1 ≤ i ≤ |V|`. -/
def lapEig (w : V → V → ℝ) (i : ℕ) : ℝ :=
((normLap w).charpoly.roots.sort (· ≤ ·)).getD (i - 1) 0
/-- Definition 3.3, p. 10: the Dirichlet conductance
`φ_G(S) = (∑_{x ∈ S, x' ∉ S} w_{xx'}) / (∑_{x ∈ S} w_x)`. -/
def conductance (w : V → V → ℝ) (S : Finset V) : ℝ :=
(∑ x ∈ S, ∑ x' ∈ Sᶜ, w x x') / ∑ x ∈ S, degree w x
/-- Definition 3.4, p. 10: the sparsest `i`-partition
`ρ_i = min_{S_1, …, S_i} max_j φ_G(S_j)`, the minimum over partitions of `V` into `i` nonempty
sets. A partition is encoded by a surjective labelling `σ : V → Fin i`, with `S_j = σ⁻¹(j)`. -/
def sparsestPartition (w : V → V → ℝ) (i : ℕ) : ℝ :=
⨅ σ : {σ : V → Fin i // Function.Surjective σ},
⨆ j : Fin i, conductance w (Finset.univ.filter fun x => σ.1 x = j)
/-- Eq. (18), p. 26: `φ^ŷ = ∑_{x,x'} w_{xx'} 1[ŷ(x) ≠ ŷ(x')]` for an extended labeling
function `ŷ`. -/
def cutWeight {r : ℕ} (w : V → V → ℝ) (yhat : V → Fin r) : ℝ :=
∑ x, ∑ x', w x x' * if yhat x ≠ yhat x' then 1 else 0
end Graph
section Model
variable {Xbar X : Type*} [Fintype Xbar] [Fintype X] [DecidableEq X]
/-- Section 3, pp. 6-7: the finite data model. `P` is the population distribution `P_X̄` on the
natural data, `A x̄ x = 𝒜(x | x̄)` is the augmentation distribution of `x̄`, and the set `X` of
augmented data is the union of the supports of the `𝒜(· | x̄)`, `x̄` in the support of `P`. -/
def IsAugModel (P : Xbar → ℝ) (A : Xbar → X → ℝ) : Prop :=
(∀ xb, 0 ≤ P xb) ∧ (∑ xb, P xb = 1) ∧ (∀ xb x, 0 ≤ A xb x) ∧ (∀ xb, ∑ x, A xb x = 1) ∧
(∀ x, ∃ xb, 0 < P xb ∧ 0 < A xb x)
/-- Eq. (2), p. 7: the edge weights of the population augmentation graph,
`w_{xx'} = E_{x̄ ∼ P}[𝒜(x | x̄) 𝒜(x' | x̄)]`. -/
def augWeight (P : Xbar → ℝ) (A : Xbar → X → ℝ) (x x' : X) : ℝ :=
∑ xb, P xb * A xb x * A xb x'
/-- Eq. (6), p. 9 (written out on p. 26): the population spectral contrastive loss
`L(f) = -2 E_{x, x⁺}[f(x)ᵀ f(x⁺)] + E_{x, x⁻}[(f(x)ᵀ f(x⁻))²]`, where `x, x⁺ ∼ 𝒜(· | x̄)`
independently for `x̄ ∼ P`, and `x⁻ ∼ 𝒜(· | x̄')` for an independent `x̄' ∼ P`. -/
def scLoss {k : ℕ} (P : Xbar → ℝ) (A : Xbar → X → ℝ) (f : X → Fin k → ℝ) : ℝ :=
-2 * (∑ xb, P xb * ∑ x, ∑ x', A xb x * A xb x' * ∑ i, f x i * f x' i) +
∑ xb, ∑ xb', P xb * P xb' * ∑ x, ∑ x', A xb x * A xb' x' * (∑ i, f x i * f x' i) ^ 2
/-- Eq. (4), p. 8: the matrix factorization loss `L_mf(F) = ‖Ā - F Fᵀ‖_F²` of an embedding
matrix `F ∈ ℝ^{N × k}` (row `x` of `F` is `F x`). -/
def mfLoss {k : ℕ} (w : X → X → ℝ) (F : X → Fin k → ℝ) : ℝ :=
∑ x, ∑ x', (normAdj w x x' - ∑ i, F x i * F x' i) ^ 2
/-- Section 3, p. 6: `i` is a prediction of the linear classifier `B ∈ ℝ^{k × r}` on the
representation `f(x)`, i.e. an index maximising `(f(x)ᵀ B)_i`. The paper breaks ties
arbitrarily; `g` is any such choice. -/
def IsProbePred {k r : ℕ} (f : X → Fin k → ℝ) (B : Matrix (Fin k) (Fin r) ℝ)
(g : X → Fin r) : Prop :=
∀ x i, Matrix.vecMul (f x) B i ≤ Matrix.vecMul (f x) B (g x)
/-- Section 3, p. 6: `Pr_{x ∼ 𝒜(·|x̄)}[g(x) = i]`, the vote of the augmentations of `x̄`
for class `i`. -/
def votes {r : ℕ} (A : Xbar → X → ℝ) (g : X → Fin r) (xb : Xbar) (i : Fin r) : ℝ :=
∑ x, A xb x * if g x = i then 1 else 0
/-- Section 3, p. 6: `ḡ(x̄) = argmax_i Pr_{x ∼ 𝒜(·|x̄)}[g(x) = i]`, the ensembled prediction on
natural data (ties broken arbitrarily; `gbar` is any such choice). -/
def IsEnsemblePred {r : ℕ} (A : Xbar → X → ℝ) (g : X → Fin r) (gbar : Xbar → Fin r) : Prop :=
∀ xb i, votes A g xb i ≤ votes A g xb (gbar xb)
/-- Section 3, p. 6: `Pr_{x̄ ∼ P}[y(x̄) ≠ ḡ(x̄)]`. -/
def ensembleError {r : ℕ} (P : Xbar → ℝ) (y : Xbar → Fin r) (gbar : Xbar → Fin r) : ℝ :=
∑ xb, P xb * if gbar xb ≠ y xb then 1 else 0
/-- Section 3, p. 6: the error `E(f, B) = Pr_{x̄ ∼ P}[y(x̄) ≠ ḡ_{f,B}(x̄)]` of the representation
`f` with the linear head `B`. Since the paper breaks ties arbitrarily, this is the largest error
over all tie-breaking choices, so that a bound on it holds for every tie-breaking rule. -/
def probeError {k r : ℕ} (P : Xbar → ℝ) (A : Xbar → X → ℝ) (y : Xbar → Fin r)
(f : X → Fin k → ℝ) (B : Matrix (Fin k) (Fin r) ℝ) : ℝ :=
⨆ c : {c : (X → Fin r) × (Xbar → Fin r) // IsProbePred f B c.1 ∧ IsEnsemblePred A c.1 c.2},
ensembleError P y c.1.2
/-- Eq. (1), p. 6: the linear probe error `E(f) = min_{B ∈ ℝ^{k × r}} E(f, B)`. -/
def linearProbeError {k r : ℕ} (P : Xbar → ℝ) (A : Xbar → X → ℝ) (y : Xbar → Fin r)
(f : X → Fin k → ℝ) : ℝ :=
⨅ B : Matrix (Fin k) (Fin r) ℝ, probeError P A y f B
/-- Eq. (19), p. 26: `Δ(y, ŷ) = Pr_{x̄ ∼ P, x ∼ 𝒜(·|x̄)}(ŷ(x) ≠ y(x̄))`. With `ŷ = g` this is
also the error of a classifier `g` on augmented data (Assumption 3.6, p. 11). -/
def labelDisagree {r : ℕ} (P : Xbar → ℝ) (A : Xbar → X → ℝ) (y : Xbar → Fin r)
(yhat : X → Fin r) : ℝ :=
∑ xb, P xb * ∑ x, A xb x * if yhat x ≠ y xb then 1 else 0
/-- Theorem B.3, p. 27: the squared error `E_{x̄ ∼ P, x ∼ 𝒜(·|x̄)} ‖y⃗(x̄) - Bᵀ f(x)‖²` of the
linear head on the one-hot label `y⃗(x̄)`. -/
def probeSqLoss {k r : ℕ} (P : Xbar → ℝ) (A : Xbar → X → ℝ) (y : Xbar → Fin r)
(f : X → Fin k → ℝ) (B : Matrix (Fin k) (Fin r) ℝ) : ℝ :=
∑ xb, P xb * ∑ x, A xb x *
∑ c, ((if c = y xb then 1 else 0) - Matrix.vecMul (f x) B c) ^ 2
/-- Frobenius norm `‖B‖_F` of a real matrix (Theorem B.3, p. 27). -/
def frobNorm {m n : Type*} [Fintype m] [Fintype n] (B : Matrix m n ℝ) : ℝ :=
Real.sqrt (∑ i, ∑ j, B i j ^ 2)
/-- Section 4.1, p. 14 (Definition D.1, p. 37): the empirical spectral contrastive loss on a
dataset `x̄_1, …, x̄_n`:
`L̂_n(f) = -(2/n) ∑_i E_{x, x⁺ ∼ 𝒜(·|x̄_i)}[f(x)ᵀ f(x⁺)]
+ (1/(n(n-1))) ∑_{i ≠ j} E_{x ∼ 𝒜(·|x̄_i), x⁻ ∼ 𝒜(·|x̄_j)}[(f(x)ᵀ f(x⁻))²]`. -/
def empLoss {k n : ℕ} (A : Xbar → X → ℝ) (d : Fin n → Xbar) (f : X → Fin k → ℝ) : ℝ :=
-(2 / n) * (∑ i, ∑ x, ∑ x', A (d i) x * A (d i) x' * ∑ l, f x l * f x' l) +
(1 / (n * (n - 1) : ℝ)) * ∑ i, ∑ j ∈ Finset.univ.filter (fun j => j ≠ i),
∑ x, ∑ x', A (d i) x * A (d j) x' * (∑ l, f x l * f x' l) ^ 2
/-- Section 4.1, p. 14: the Rademacher complexity of a class `ℱ` of maps `X → ℝ^k` on `m` data,
`R̂_m(ℱ) = max_{x_1, …, x_m ∈ X} E_σ[sup_{f ∈ ℱ, i ∈ [k]} (1/m) ∑_j σ_j f_i(x_j)]`, with `σ`
uniform on `{-1, 1}^m` (encoded by `Bool`). -/
def rademacher {k : ℕ} (F : Set (X → Fin k → ℝ)) (m : ℕ) : ℝ :=
⨆ xs : Fin m → X, (1 / 2 ^ m : ℝ) * ∑ σ : Fin m → Bool,
⨆ p : F × Fin k, (1 / m : ℝ) * ∑ j, (if σ j then 1 else -1) * p.1.1 (xs j) p.2
open Classical in
/-- Section 4.1, p. 14: the probability, under a dataset `x̄_1, …, x̄_n` drawn i.i.d. from `P`,
of an event `E` of the dataset. -/
def datasetProb {n : ℕ} (P : Xbar → ℝ) (E : (Fin n → Xbar) → Prop) : ℝ :=
∑ d : Fin n → Xbar, (∏ i, P (d i)) * if E d then 1 else 0
end Model
end SpectralContrastive
Read-back
What the Lean code literally says, in plain math · claude-opus-5-5
degree — Let be a finite set with decidable equality and an arbitrary real-valued function. No nonnegativity or symmetry is assumed. For a vertex , the degree is the sum over the second argument:
IsWeightedGraph — For a finite set and a function , the property " is a weighted graph" holds exactly when all three of the following hold:
- for all ;
- for all ;
- for every .
Self-loops () are allowed and count toward the degree. If is empty, the property holds vacuously.
normAdj — For a finite set and any (no graph hypotheses assumed), the normalized adjacency matrix has entries
where is the degree. Two conventions apply:
- The square root is taken of the product , and the square root of a negative number is taken to be .
- Division by yields .
Hence whenever , for example when either degree is . When both degrees are negative, the product is positive and the entry is .
normLap — For a finite set and any , the normalized Laplacian is
where is the identity matrix and is the normalized adjacency matrix: , with , and division by zero .
adjEig — For a finite set , any and a natural number , the value is defined as follows:
- Take the real roots of the characteristic polynomial of the real matrix (the normalized adjacency matrix, with the conventions and ).
- Count them with multiplicity.
- Sort them in non-increasing order: .
- Set if , and if .
Edge cases:
- Because the index used is with truncated natural-number subtraction, .
- Non-real complex roots are discarded, so if is not symmetric, may be smaller than and the "missing" eigenvalues read as .
- If is empty, the characteristic polynomial is and every .
lapEig — For a finite set , any and a natural number , the value is defined as follows:
- Take the real roots of the characteristic polynomial of , the normalized Laplacian (with and the conventions , ).
- Count them with multiplicity.
- Sort them in non-decreasing order: .
- Set if , and if .
Edge cases:
- , because of truncated subtraction .
- Non-real roots are discarded.
- If is empty, all .
conductance — For a finite set , any and a finite subset , the conductance is
Division by zero yields . In particular:
- ;
- , since the numerator is an empty sum;
- whenever the total degree of is .
No nonnegativity of is assumed.
sparsestPartition — For a finite set , any and a natural number , the value is
where is the conductance defined above. Each surjective labelling describes an ordered partition of into exactly nonempty blocks . There are finitely many labellings, so when any exist the infimum is a minimum.
Empty-index conventions (an infimum or supremum over an empty index set is ):
- If , no surjection exists and .
- If , then , whether or not is empty.
cutWeight — For a finite set , any , a natural number and a labelling , the cut weight is
The sum runs over ordered pairs, so for symmetric each unordered cross-label pair is counted twice. Note also that if , a labelling exists only when is empty.
IsAugModel — Let (natural data) and (augmented data) be finite sets, with having decidable equality. Let and , where plays the role of . The property holds exactly when all of the following hold:
- for all , and ;
- for all ;
- for every , including those with ;
- for every there exists with and .
These conditions force both and to be nonempty.
augWeight — For finite sets , and arbitrary functions , (no probability assumptions are built in), the edge weight between is
scLoss — Let , be finite sets, a natural number, , arbitrary, and . Write . The spectral contrastive loss is
No normalisation or nonnegativity of or is assumed. When , .
mfLoss — For a finite set with decidable equality, any , a natural number and (row of an matrix), the matrix factorization loss is
Here is the normalized adjacency of , with , and division by zero .
IsProbePred — Let be a finite set, natural numbers, , and . The property holds exactly when, for every and every class ,
That is, is some maximizing index, with ties allowed. If and is nonempty, no such exists.
votes — For finite sets , , , , and a class , the vote count is
IsEnsemblePred — For finite sets , , , and , the property holds exactly when, for every (regardless of its probability) and every class ,
Here . That is, is some vote-maximizing class, with ties allowed.
ensembleError — For a finite set , , a label function and a prediction , the ensemble error is
probeError — Let , be finite sets, , , , and . The probe error is
The supremum ranges over all pairs such that:
- satisfies for all and all classes ;
- satisfies for all and all classes .
So this is the worst case over all tie-breaking choices at both stages. The set of pairs is finite. If it is empty, which happens when , the value is ; when and both sets are empty, the value is likewise .
linearProbeError — With , , , , and as above, the linear probe error is
Here is the worst-case-over-tie-breaking probe error defined above, and the infimum ranges over all real matrices. Since takes only finitely many values, the infimum is attained. Note that is allowed; it makes every class tie for every .
labelDisagree — For finite sets , , , , labels and , the label disagreement is
probeSqLoss — For finite sets , , , as above, , and , the squared probe loss is
Equivalently, it is the - and -weighted sum of , where is the one-hot vector of .
frobNorm — For finite index sets , and a real matrix , the Frobenius norm is
empLoss — Let , be finite sets, , natural numbers, a dataset (repetitions allowed) and . With , the empirical loss is
The coefficients are computed in the reals, and division by zero yields . Consequently:
- ;
- for , the second coefficient is (and its sum is empty anyway), so only the first term remains.
rademacher — Let be a finite set, natural numbers and any set of maps . The Rademacher complexity is
The points may repeat, and the average over is uniform. The suprema follow the real-number conventions, under which:
- the supremum over an empty index set is ;
- the supremum of a set unbounded above is also .
In particular:
- the inner supremum is if is empty, if , or if the values are unbounded above;
- if is empty and , the outer supremum is over nothing and ;
- if , the factor is and .
datasetProb — For a finite set , , a natural number and any property of datasets in , the dataset probability is
No probability assumption on is built in. For there is exactly one (empty) dataset with weight , so the value is if holds of it and otherwise.
Confirmed by the mission captain (proposal self-audit).
Confirmed by the moderator at approval.