Supervised contrastive and cross-entropy losses of labelled point configurations, and the sphere-inscribed regular simplex
DefinitionSupConGeometry_BasicObjects of Sections 2-3 and the Supplementary Material of Graf, Hofer, Niethammer and Kwitt (ICML 2021).
- Configurations and labels. A free configuration is with , carrying labels . Write . is balanced if for every class .
- Regular simplex (Definition 3). form a regular simplex inscribed in the sphere of radius if (S1) , (S2) for all , and (S3) for one and all .
- Cross-entropy loss (Definition 1). For a weight matrix with rows ,
and . 4. Supervised contrastive loss (Definition 2). is the set of all multisets of indices from . For , and . The batch-wise loss is
where sums over a multiset count multiplicity and removes one copy of . The loss is . The class-specific batch-wise loss is the part of this sum with when , and otherwise. 5. Batch partition (Definition 4). and . 6. Auxiliary functions (Definition 5). With :
, and , the second summand being omitted when . 7. Combinatorial factor (Lemma 5). , where is the multiplicity of in . 8. radius (Corollary 2, Lemma 14). , and is the solution in of .
Formalization Note Points live in EuclideanSpace ℝ (Fin h), labels in Fin K and indices in Fin N. A batch is an element of Sym (Fin N) b, a multiset of size , and sums over all of them. Balance is written , which avoids natural-number division. is the infimum of the solution set of its equation. By Lemma 14 this set is a single point when and . and follow the paper's case split on .
import Mathlib
/-!
Graf, Hofer, Niethammer and Kwitt, *Dissecting Supervised Contrastive Learning*, ICML 2021,
arXiv:2102.08817v4: free point configurations with labels, the cross-entropy loss (Definition 1),
the supervised contrastive loss over all multiset batches (Definition 2), the sphere-inscribed
regular simplex (Definition 3), balanced labels (Section 3), and the auxiliary objects of the
proofs in Supplementary S1.1 (Definitions 4 and 5), S1.3 (Lemma 5) and S2 (Lemma 14, Corollary 2).
-/
noncomputable section
namespace SupConGeometry
/-- Section 2: the representation space `ℝ^h` with its Euclidean inner product and norm. -/
abbrev Rep (h : ℕ) : Type := EuclideanSpace ℝ (Fin h)
variable {N K h : ℕ}
/-- Supplementary S1.1: `m_Y(y) = |{n ∈ [N] : y_n = y}|`, the number of instances of class `y`. -/
def labelCount (Y : Fin N → Fin K) (y : Fin K) : ℕ :=
(Finset.univ.filter (fun n => Y n = y)).card
/-- Section 3 (p. 4): the label configuration `Y` is balanced, `|{n ∈ [N] : y_n = y}| = N / K`
for every class `y`; written as `K · m_Y(y) = N` to avoid natural-number division. -/
def IsBalanced (Y : Fin N → Fin K) : Prop :=
∀ y : Fin K, K * labelCount Y y = N
/-- Definition 3 (S1)-(S3): `ζ_1, …, ζ_K` form the vertices of a regular simplex inscribed in the
hypersphere of radius `ρ`: they sum to `0`, all have norm `ρ`, and all inner products
`⟨ζ_i, ζ_j⟩`, `i < j`, equal one common value `d`. -/
def IsSphereInscribedRegularSimplex (ζ : Fin K → Rep h) (ρ : ℝ) : Prop :=
(∑ y, ζ y = 0) ∧ (∀ y, ‖ζ y‖ = ρ) ∧
∃ d : ℝ, ∀ y y' : Fin K, y < y' → inner ℝ (ζ y) (ζ y') = d
/-- Definition 1, eq. (3): the instance loss
`ℓ_CE(Z, W; Y, n) = -log(exp⟨z_n, w_{y_n}⟩ / ∑_{l=1}^K exp⟨z_n, w_l⟩)`, where `w_y` is the `y`-th
row of the classifier weight matrix `W ∈ ℝ^{K×h}`. -/
def ceInstanceLoss (Z : Fin N → Rep h) (W : Fin K → Rep h) (Y : Fin N → Fin K) (n : Fin N) : ℝ :=
-Real.log (Real.exp (inner ℝ (Z n) (W (Y n))) / ∑ l, Real.exp (inner ℝ (Z n) (W l)))
/-- Definition 1, eq. (2): the cross-entropy loss `L_CE(Z, W; Y) = (1/N) ∑_n ℓ_CE(Z, W; Y, n)`. -/
def ceLoss (Z : Fin N → Rep h) (W : Fin K → Rep h) (Y : Fin N → Fin K) : ℝ :=
(1 / (N : ℝ)) * ∑ n, ceInstanceLoss Z W Y n
/-- Theorem 1: the Frobenius norm `‖W‖_F = (∑_y ‖w_y‖²)^{1/2}` of the weight matrix with rows `w_y`. -/
def frobNorm (W : Fin K → Rep h) : ℝ :=
Real.sqrt (∑ y, ‖W y‖ ^ 2)
/-- Definition 2: `B_y = {{j ∈ B : y_j = y}}`, the sub-multiset of a batch `B` with label `y`. -/
def batchClass (Y : Fin N → Fin K) (B : Multiset (Fin N)) (y : Fin K) : Multiset (Fin N) :=
B.filter (fun j => Y j = y)
/-- Supplementary S1.1: `B_y^C = {{j ∈ B : y_j ≠ y}}`, the complement of `B_y` in the batch `B`. -/
def batchClassCompl (Y : Fin N → Fin K) (B : Multiset (Fin N)) (y : Fin K) : Multiset (Fin N) :=
B.filter (fun j => Y j ≠ y)
/-- Definition 2, eq. (6): the summand `log(exp⟨z_i, z_j⟩ / ∑_{k ∈ B \ {{i}}} exp⟨z_i, z_k⟩)`, where
`B \ {{i}}` removes one copy of `i` from the multiset `B`. -/
def scLogRatio (Z : Fin N → Rep h) (B : Multiset (Fin N)) (i j : Fin N) : ℝ :=
Real.log (Real.exp (inner ℝ (Z i) (Z j)) /
((B.erase i).map (fun k => Real.exp (inner ℝ (Z i) (Z k)))).sum)
/-- Definition 2, eq. (6): the batch-wise supervised contrastive loss
`ℓ_SC(Z; Y, B) = -∑_{i ∈ B} 1_{|B_{y_i}|>1} / (|B_{y_i}| - 1) ∑_{j ∈ B_{y_i} \ {{i}}} log(…)`,
sums over the multiset `B` counting multiplicity, with the paper's convention that the summand of
`i` is `0` when `|B_{y_i}| = 1`. -/
def scBatchLoss (Z : Fin N → Rep h) (Y : Fin N → Fin K) (B : Multiset (Fin N)) : ℝ :=
-((B.map (fun i =>
if 1 < Multiset.card (batchClass Y B (Y i)) then
(1 / ((Multiset.card (batchClass Y B (Y i)) : ℝ) - 1)) *
(((batchClass Y B (Y i)).erase i).map (fun j => scLogRatio Z B i j)).sum
else 0)).sum)
/-- Definition 2, eqs. (4)-(5): the supervised contrastive loss
`L_SC(Z; Y) = ∑_{B ∈ 𝓑} ℓ_SC(Z; Y, B)`, summed over the set `𝓑` of all index multisets of size `b`
over `[N]` (here `Sym (Fin N) b`). -/
def scLoss (Z : Fin N → Rep h) (Y : Fin N → Fin K) (b : ℕ) : ℝ :=
∑ B : Sym (Fin N) b, scBatchLoss Z Y (B : Multiset (Fin N))
/-- Supplementary S1.1, eq. (10): the class-specific batch-wise loss `ℓ_SC(Z; Y, B, y)`, equal to
`-∑_{i ∈ B_y} 1/(|B_y| - 1) ∑_{j ∈ B_y \ {{i}}} log(…)` if `|B_y| > 1` and `0` otherwise. -/
def scClassBatchLoss (Z : Fin N → Rep h) (Y : Fin N → Fin K) (B : Multiset (Fin N)) (y : Fin K) :
ℝ :=
if 1 < Multiset.card (batchClass Y B y) then
-(((batchClass Y B y).map (fun i =>
(1 / ((Multiset.card (batchClass Y B y) : ℝ) - 1)) *
(((batchClass Y B y).erase i).map (fun j => scLogRatio Z B i j)).sum)).sum)
else 0
/-- Definition 4 (Supplementary S1.1), eq. (16): `𝓑_{y,l}`, the batches of size `b` containing exactly `l`
instances of class `y`. -/
def batchesWithCount (Y : Fin N → Fin K) (b : ℕ) (y : Fin K) (l : ℕ) : Finset (Sym (Fin N) b) :=
Finset.univ.filter (fun B => Multiset.card (batchClass Y (B : Multiset (Fin N)) y) = l)
/-- Theorem 2 (p. 5) and Lemma 2: `M_l = ∑_{y ∈ 𝒴} |{B ∈ 𝓑 : |B_y| = l}| = ∑_y |𝓑_{y,l}|`. -/
def batchCountTotal (Y : Fin N → Fin K) (b : ℕ) (l : ℕ) : ℕ :=
∑ y, (batchesWithCount Y b y l).card
/-- Definition 5, eq. (19): the attraction term
`S_att(Z; Y, B, y) = -1/(|B_y|(|B_y| - 1)) ∑_{i ∈ B_y} ∑_{j ∈ B_y \ {{i}}} ⟨z_i, z_j⟩`. -/
def sAtt (Z : Fin N → Rep h) (Y : Fin N → Fin K) {b : ℕ} (B : Sym (Fin N) b) (y : Fin K) : ℝ :=
-(1 / ((Multiset.card (batchClass Y (B : Multiset (Fin N)) y) : ℝ) *
((Multiset.card (batchClass Y (B : Multiset (Fin N)) y) : ℝ) - 1))) *
((batchClass Y (B : Multiset (Fin N)) y).map (fun i =>
(((batchClass Y (B : Multiset (Fin N)) y).erase i).map (fun j => inner ℝ (Z i) (Z j))).sum)).sum
/-- Definition 5, eq. (20): the repulsion term
`S_rep(Z; Y, B, y) = 1/(|B_y| |B_y^C|) ∑_{i ∈ B_y} ∑_{j ∈ B_y^C} ⟨z_i, z_j⟩` if `|B_y| ≠ b`, and
`0` if `|B_y| = b`. -/
def sRep (Z : Fin N → Rep h) (Y : Fin N → Fin K) {b : ℕ} (B : Sym (Fin N) b) (y : Fin K) : ℝ :=
if Multiset.card (batchClass Y (B : Multiset (Fin N)) y) = b then 0 else
(1 / ((Multiset.card (batchClass Y (B : Multiset (Fin N)) y) : ℝ) *
(Multiset.card (batchClassCompl Y (B : Multiset (Fin N)) y) : ℝ))) *
((batchClass Y (B : Multiset (Fin N)) y).map (fun i =>
((batchClassCompl Y (B : Multiset (Fin N)) y).map (fun j => inner ℝ (Z i) (Z j))).sum)).sum
/-- Definition 5, eqs. (17)-(18): `S(Z; Y, B, y) = S_att(Z; Y, B, y) + S_rep(Z; Y, B, y)`. -/
def sAux (Z : Fin N → Rep h) (Y : Fin N → Fin K) {b : ℕ} (B : Sym (Fin N) b) (y : Fin K) : ℝ :=
sAtt Z Y B y + sRep Z Y B y
/-- Definition 5, eq. (21): the per-instance term
`S_i(Z; Y, B, y) = -1/(|B_y| - 1) ∑_{j ∈ B_y \ {{i}}} ⟨z_i, z_j⟩ + 1/|B_y^C| ∑_{j ∈ B_y^C} ⟨z_i, z_j⟩`
if `|B_y| ≠ b`, and only the first summand if `|B_y| = b`. -/
def sInd (Z : Fin N → Rep h) (Y : Fin N → Fin K) {b : ℕ} (B : Sym (Fin N) b) (y : Fin K)
(i : Fin N) : ℝ :=
-(1 / ((Multiset.card (batchClass Y (B : Multiset (Fin N)) y) : ℝ) - 1)) *
(((batchClass Y (B : Multiset (Fin N)) y).erase i).map (fun j => inner ℝ (Z i) (Z j))).sum +
if Multiset.card (batchClass Y (B : Multiset (Fin N)) y) = b then 0 else
(1 / (Multiset.card (batchClassCompl Y (B : Multiset (Fin N)) y) : ℝ)) *
((batchClassCompl Y (B : Multiset (Fin N)) y).map (fun j => inner ℝ (Z i) (Z j))).sum
/-- Lemma 5 (Supplementary S1.3), eq. (61): the combinatorial factor
`K_{n,m}(y, l) = 1/(l(b - l)) ∑_{B ∈ 𝓑_{y,l}} m_{B_y}(n) m_{B_y^C}(m)`, where `m_M(x)` is the
multiplicity of `x` in the multiset `M`. -/
def combFactor (Y : Fin N → Fin K) (b : ℕ) (y : Fin K) (l : ℕ) (n m : Fin N) : ℝ :=
(1 / ((l : ℝ) * ((b : ℝ) - l))) *
∑ B ∈ batchesWithCount Y b y l,
((Multiset.count n (batchClass Y (B : Multiset (Fin N)) y) : ℝ) *
(Multiset.count m (batchClassCompl Y (B : Multiset (Fin N)) y) : ℝ))
/-- Lemma 14, eq. (147): `f(x) = log(1 + (K - 1) exp(-ρ K x/(K - 1))) + λ K x²`, the lower bound
of Theorem 1 plus the penalty `λ‖W‖_F²`, written in `x = ‖W‖_F / √K`. -/
def ceL2Profile (K : ℕ) (ρ lam x : ℝ) : ℝ :=
Real.log (1 + ((K : ℝ) - 1) * Real.exp (-(ρ * ((K : ℝ) / ((K : ℝ) - 1)) * x))) +
lam * (K : ℝ) * x ^ 2
/-- Corollary 2 (Section 3.1, p. 5) and Lemma 14, eq. (148): `r_W(ρ, λ)`, the solution in `x` of
`2λx - ρ / (exp(Kρx/(K - 1)) + K - 1) = 0` (unique by Lemma 14), taken as the infimum of the
solution set. -/
def ceL2Radius (K : ℕ) (ρ lam : ℝ) : ℝ :=
sInf {x : ℝ | 2 * lam * x - ρ / (Real.exp ((K : ℝ) * ρ * x / ((K : ℝ) - 1)) + (K : ℝ) - 1) = 0}
end SupConGeometry
Read-back
What the Lean code literally says, in plain math · claude-opus-5-5
Conventions used throughout. are arbitrary natural numbers, and any of them may be . and are index sets. A label configuration is any function , written . A point configuration is any function , written . A weight configuration is any function , written . Here carries its standard Euclidean inner product and norm .
All real arithmetic follows these total conventions:
- Division by zero gives , so and .
- .
- Natural numbers cast to reals are subtracted as reals, so .
"Multiset" means a finite collection of indices with multiplicity. All sums over a multiset count each element as often as it occurs. For a multiset and index , removes one copy of if occurs in , and leaves unchanged otherwise. is the size of counted with multiplicity.
Rep. For a natural number , the representation space is (vectors indexed by ) with the Euclidean inner product and norm. When this is the zero space.
labelCount. For and a class ,
the number of indices carrying label .
IsBalanced. is called balanced when
- This forces to divide , with every class having exactly members.
- If and , every is balanced, since all counts are .
- If , then necessarily (no map exists otherwise), and the condition holds vacuously.
IsSphereInscribedRegularSimplex. For vectors and a real number , the property holds iff all three of the following are true:
- ;
- for every ;
- there exists a real with for all . By symmetry of the inner product, this means all pairs of distinct indices have the same inner product.
Notes on what the definition does and does not say:
- The value of is not specified.
- No relation between and is required.
- Distinctness of the is not required.
- If , condition 2 forces .
- is allowed, with all .
- If , condition 1 forces , and hence .
- If , the property holds for every , including negative .
ceInstanceLoss. For , , and an index ,
The denominator is a sum over all weight vectors. It is positive whenever an index exists, because then .
ceLoss. The cross-entropy loss is
When it equals .
frobNorm. For ,
which is when .
batchClass. For a multiset of indices in and a class , is the sub-multiset of consisting of all elements with , keeping their multiplicities.
batchClassCompl. is the sub-multiset of consisting of all elements with , keeping their multiplicities. Thus .
scLogRatio. For , a multiset , and indices ,
The sum runs over with one copy of removed, counted with multiplicity.
- Neither nor is required to lie in .
- If is empty, the denominator is . The quotient is then , and the value is .
scBatchLoss. For , and a multiset ,
where the outer sum runs over with multiplicity and
- The inner -sum is over the same-class sub-multiset with one copy of removed, counted with multiplicity.
- The denominator inside the logarithm ranges over the whole batch minus one copy of .
- For the empty batch the value is .
scLoss. For , and a natural number ,
summed over all multisets of size exactly drawn from .
- Each multiset is counted once, giving terms when .
- There is no normalizing factor.
- If , the only batch is empty and .
- If and , there are no batches and .
scClassBatchLoss. For , , a multiset and a class , is
and if . The sums are taken with multiplicity, and the denominator inside the logarithm again ranges over the whole batch minus one copy of .
batchesWithCount. For , a size , a class and a natural number ,
the set of size- batches containing exactly elements (with multiplicity) of label . It is empty if .
batchCountTotal. For , and ,
sAtt. For , , a batch of size and a class ,
with all sums taken with multiplicity. When the prefactor is , so the value is .
sRep. For , , a batch of size and a class ,
with all sums taken with multiplicity. If , the prefactor is and the value is .
sAux. The auxiliary term is
sInd. For , , a batch of size , a class and an index ,
- The index is not required to lie in , or even in . If , no copy is removed.
- When , the first prefactor is .
- When , the first prefactor is , but its sum is empty.
combFactor. For , , a class , a natural number and indices ,
where is the number of copies of in the multiset , and is computed as a real number.
- The value is whenever or , because the prefactor is .
- The value is whenever , because the set is empty.
- The value is unless and , because otherwise one of the multiplicities vanishes.
ceL2Profile. For a natural number (used as a real) and reals ,
No sign or range conditions are imposed on , or . Degenerate cases:
- : and the logarithm term is , so .
- : , the logarithm argument is , and .
ceL2Radius. For a natural number and reals ,
The infimum is the real infimum. Its value is if is empty or unbounded below. Nothing in the definition asserts that is nonempty or has exactly one element, and no conditions on or are imposed. Degenerate cases:
- : , so the value is .
- : the exponent is and the denominator is , so the equation reads .
- : the denominator is , so the equation reads , and the value is .
Note also the sign of the exponent in each definition: the exponent in this equation is , while the profile uses .
Confirmed by the mission captain (proposal self-audit).
Confirmed by the moderator at approval.