Contrastive loss, alignment and uniformity, and Gaussian energies on the hypersphere
DefinitionAlignmentUniformity_BasicObjects of Sections 3, 4.1 and 4.2 and Appendix A of Wang and Isola (2020).
- Spaces. Data live in and features in , both with the Euclidean norm. , and is the unit sphere of .
- Gaussian potential. For , .
- Measures on the sphere. is the set of Borel probability measures on that give no mass to the complement of . is the normalized surface area measure of .
- Energies. For a kernel and finite measures : , and . The energy of the finite signed measure is .
- Point configurations. For , the pairwise potential is and the normalized counting measure is .
- Weak* convergence. weak* if for every continuous .
- Hypergeometric function (eq. 5). , with and .
- Relaxed problem (eqs. 12-13). , and the objective is .
- Data and positive pairs (Assumption, Section 3). is a distribution on . is a distribution on that is symmetric under and whose first marginal is .
- Encoders. An encoder is a Borel measurable with for every .
- Contrastive loss (eq. 1). For and negatives,
- The two limit terms (eq. 2). The alignment term is . The uniformity term is .
- Alignment and uniformity losses (Section 4.1). and .
- Perfect alignment and uniformity (Section 4.2). is perfectly aligned if almost surely over . It is perfectly uniform if the law of , , is .
Formalization Note is EuclideanSpace ℝ (Fin k). Measures on the sphere are measures on the ambient space that are concentrated on the sphere. is Mathlib's Measure.toSphere of Lebesgue measure, divided by its total mass and pushed forward to the ambient space. The paper writes and as densities. Here they are probability measures, which is also how the paper uses them for finite datasets in Section 4.2. A finite signed measure is written as a difference of finite measures, and its energy is expanded by bilinearity.
import Mathlib
/-!
Wang and Isola, *Understanding Contrastive Representation Learning through Alignment and
Uniformity on the Hypersphere*, ICML 2020, arXiv:2005.10242v10: the data and positive-pair
distributions and the contrastive loss of Section 3, the alignment and uniformity losses, the
Gaussian potential, the uniform distribution on the sphere and weak* convergence of Section 4.1,
perfect alignment and perfect uniformity of Section 4.2, and the energies, the hypergeometric
function `₀F₁` and the relaxed problem of Appendix A.
-/
open MeasureTheory Filter Topology
noncomputable section
namespace AlignmentUniformity
/-- The Euclidean space `ℝ^k`. Data live in `ℝ^n`; features live in `ℝ^m`, on the unit sphere
`S^{m-1}`; the sphere `S^d` of Section 4.1 is the unit sphere of `ℝ^{d+1}`. -/
abbrev Vec (k : ℕ) := EuclideanSpace ℝ (Fin k)
section Sphere
variable {k : ℕ}
/-- Section 4.1.2, p. 4: the Gaussian potential kernel `G_t(u, v) = exp(-t ‖u - v‖₂²)`. -/
def gaussKernel (t : ℝ) (u v : Vec k) : ℝ := Real.exp (-t * ‖u - v‖ ^ 2)
/-- Proposition 1 (Section 4.1.2, p. 5) and Appendix A.1, p. 14: `μ ∈ 𝓜(S^{k-1})`, i.e. `μ` is a
Borel probability measure on the unit sphere, viewed as a Borel probability measure on `ℝ^k`
that gives no mass to the complement of the sphere. -/
def IsSphereProb (μ : Measure (Vec k)) : Prop :=
IsProbabilityMeasure μ ∧ μ (Metric.sphere (0 : Vec k) 1)ᶜ = 0
/-- Definition (Uniform distribution on `S^d`), Section 4.1.2, p. 5: `σ` is the normalized surface
area measure on the unit sphere of `ℝ^k`, pushed forward to `ℝ^k`. The surface area measure is
Mathlib's `Measure.toSphere` of Lebesgue measure, `s ↦ k · vol {r x : 0 < r < 1, x ∈ s}`. -/
def sphereUnif (k : ℕ) : Measure (Vec k) :=
((((volume : Measure (Vec k)).toSphere Set.univ)⁻¹ • (volume : Measure (Vec k)).toSphere)).map
Subtype.val
/-- Appendix A.1, p. 14 (Definition of strict positive definiteness): the energy
`∫∫ K(u, v) dν(v) dμ(u)`. For `μ = ν` this is `I_K[μ]`; for `K = G_t` it is the expected pairwise
Gaussian potential of Proposition 1, eq. (4). -/
def energy (K : Vec k → Vec k → ℝ) (μ ν : Measure (Vec k)) : ℝ :=
∫ u, ∫ v, K u v ∂ν ∂μ
/-- Appendix A.1, p. 14 (Definition of strict positive definiteness): the energy `I_K[ν₁ - ν₂]` of
the finite signed measure `ν₁ - ν₂`, expanded by bilinearity. -/
def signedEnergy (K : Vec k → Vec k → ℝ) (ν₁ ν₂ : Measure (Vec k)) : ℝ :=
energy K ν₁ ν₁ - energy K ν₁ ν₂ - energy K ν₂ ν₁ + energy K ν₂ ν₂
/-- Proposition 2, Section 4.1.2, p. 5: the pairwise potential `∑_{1 ≤ i < j ≤ N} G_t(u_i, u_j)`
of an `N`-point configuration. -/
def pairPotential (t : ℝ) {N : ℕ} (u : Fin N → Vec k) : ℝ :=
∑ i, ∑ j ∈ Finset.Ioi i, gaussKernel t (u i) (u j)
/-- Proposition 2, Section 4.1.2, p. 5: the normalized counting measure `(1/N) ∑_i δ_{u_i}` of an
`N`-point configuration. -/
def normCounting {N : ℕ} (u : Fin N → Vec k) : Measure (Vec k) :=
(N : ENNReal)⁻¹ • ∑ i, Measure.dirac (u i)
/-- Definition (Weak* convergence of measures), Section 4.1.2, p. 5: `μ_n → μ` weak* if
`∫ f dμ_n → ∫ f dμ` for every continuous `f : ℝ^k → ℝ`. -/
def WeakStarTendsto (μs : ℕ → Measure (Vec k)) (μ : Measure (Vec k)) : Prop :=
∀ f : Vec k → ℝ, Continuous f →
Tendsto (fun n => ∫ x, f x ∂(μs n)) atTop (𝓝 (∫ x, f x ∂μ))
/-- Appendix A.1, eq. (5), p. 15: the confluent hypergeometric limit function
`₀F₁(; α; z) = ∑_{n ≥ 0} z^n / ((α)_n n!)`, with `(α)_n = α (α + 1) ⋯ (α + n - 1)` the rising
Pochhammer symbol. -/
def hyp0F1 (α z : ℝ) : ℝ :=
∑' n : ℕ, z ^ n / ((ascPochhammer ℝ n).eval α * (n.factorial : ℝ))
/-- Appendix A.2, eq. (12), p. 20: `U_μ(u) = ∫ exp(uᵀv / τ) dμ(v)`. -/
def expPotential (τ : ℝ) (μ : Measure (Vec k)) (u : Vec k) : ℝ :=
∫ v, Real.exp (inner ℝ u v / τ) ∂μ
/-- Appendix A.2, eq. (13), p. 20: the objective `∫ log U_μ(u) dμ(u)` of the relaxed problem. -/
def relaxedObjective (τ : ℝ) (μ : Measure (Vec k)) : ℝ :=
∫ u, Real.log (expPotential τ μ u) ∂μ
end Sphere
section Encoders
variable {n m : ℕ}
/-- Assumption, Section 3, p. 3: `p_pos` is symmetric and its marginal is `p_data`
(`p_pos(x, y) = p_pos(y, x)` and `∫ p_pos(x, y) dy = p_data(x)`), written for distributions. -/
def IsPosPairLaw (pdata : Measure (Vec n)) (ppos : Measure (Vec n × Vec n)) : Prop :=
ppos.map Prod.swap = ppos ∧ ppos.map Prod.fst = pdata
/-- Section 3, p. 3 and Section 4.2, p. 5: an encoder `f : ℝ^n → S^{m-1}` is a Borel measurable map
whose values are `ℓ₂`-normalized feature vectors. -/
def IsEncoder (f : Vec n → Vec m) : Prop :=
Measurable f ∧ ∀ x, ‖f x‖ = 1
/-- Eq. (1), Section 3, p. 3: the contrastive loss
`E_{(x,y) ∼ p_pos, x⁻ᵢ ∼ p_data i.i.d.} [-log (e^{f(x)ᵀf(y)/τ} /
(e^{f(x)ᵀf(y)/τ} + ∑_{i=1}^M e^{f(x⁻ᵢ)ᵀf(y)/τ}))]` with `M` negative samples. -/
def contrastiveLoss (pdata : Measure (Vec n)) (ppos : Measure (Vec n × Vec n))
(f : Vec n → Vec m) (τ : ℝ) (M : ℕ) : ℝ :=
∫ w, -Real.log (Real.exp (inner ℝ (f w.1.1) (f w.1.2) / τ) /
(Real.exp (inner ℝ (f w.1.1) (f w.1.2) / τ) +
∑ i, Real.exp (inner ℝ (f (w.2 i)) (f w.1.2) / τ)))
∂(ppos.prod (Measure.pi fun _ : Fin M => pdata))
/-- Eq. (2), Theorem 1, Section 4.2, p. 6: the first (alignment) term of the limit,
`-(1/τ) E_{(x,y) ∼ p_pos}[f(x)ᵀ f(y)]`. -/
def alignTerm (ppos : Measure (Vec n × Vec n)) (f : Vec n → Vec m) (τ : ℝ) : ℝ :=
-(1 / τ) * ∫ z, inner ℝ (f z.1) (f z.2) ∂ppos
/-- Eq. (2), Theorem 1, Section 4.2, p. 6: the second (uniformity) term of the limit,
`E_{x ∼ p_data}[log E_{x⁻ ∼ p_data}[e^{f(x⁻)ᵀ f(x)/τ}]]`. -/
def uniformTerm (pdata : Measure (Vec n)) (f : Vec n → Vec m) (τ : ℝ) : ℝ :=
∫ x, Real.log (∫ x', Real.exp (inner ℝ (f x') (f x) / τ) ∂pdata) ∂pdata
/-- Section 4.1.1, p. 4: the alignment loss `L_align(f; α) = E_{(x,y) ∼ p_pos} ‖f(x) - f(y)‖₂^α`,
`α > 0`. -/
def alignLoss (ppos : Measure (Vec n × Vec n)) (f : Vec n → Vec m) (α : ℝ) : ℝ :=
∫ z, ‖f z.1 - f z.2‖ ^ α ∂ppos
/-- Section 4.1.2, p. 4: the uniformity loss
`L_uniform(f; t) = log E_{x, y ∼ p_data i.i.d.}[G_t(f(x), f(y))]`, `t > 0`. -/
def uniformLoss (pdata : Measure (Vec n)) (f : Vec n → Vec m) (t : ℝ) : ℝ :=
Real.log (∫ x, ∫ y, gaussKernel t (f x) (f y) ∂pdata ∂pdata)
/-- Definition (Perfect Alignment), Section 4.2, p. 6: `f(x) = f(y)` almost surely over
`(x, y) ∼ p_pos`. -/
def PerfectlyAligned (ppos : Measure (Vec n × Vec n)) (f : Vec n → Vec m) : Prop :=
∀ᵐ z ∂ppos, f z.1 = f z.2
/-- Definition (Perfect Uniformity), Section 4.2, p. 6: the distribution of `f(x)`, `x ∼ p_data`,
is the uniform distribution `σ_{m-1}` on `S^{m-1}`. -/
def PerfectlyUniform (pdata : Measure (Vec n)) (f : Vec n → Vec m) : Prop :=
pdata.map f = sphereUnif m
end Encoders
end AlignmentUniformity
Read-back
What the Lean code literally says, in plain math · claude-opus-5-5
Ambient space. denotes the Euclidean space of real -tuples. It carries the Euclidean norm , the standard inner product , and its Borel σ-algebra. Here is any natural number, including , where . The unit sphere is ; it is empty when .
Gaussian kernel gaussKernel. For any real and any ,
There is no sign condition on . For the kernel exceeds off the diagonal, and for it is identically . The points are arbitrary and need not lie on the sphere.
Sphere probability measures IsSphereProb. For a measure on , the property holds exactly when both of the following are true:
- is a probability measure, i.e. ;
- .
When the sphere is empty, so these two conditions contradict each other and no measure has the property.
Uniform measure on the sphere sphereUnif. Write for Lebesgue measure on . The surface measure on assigns to a set the value
The measure is defined by normalising and then viewing it as a measure on all of :
The reciprocal here is taken in .
- For , is positive and finite, so is a probability measure concentrated on .
- For , and puts mass on each point.
- For , is empty and is the zero measure. The convention then makes the zero measure, which is not a probability measure.
Energy energy. For any real-valued function on and any measures on ,
This is an iterated integral: the inner integral over is taken first, then the outer over . Nothing further is assumed:
- need not be measurable, symmetric or bounded;
- need not be finite or probability measures.
Integrals follow the convention that a non-integrable function has integral . This applies to the inner integral at each fixed , and to the outer integral.
Signed energy signedEnergy. For as above and arbitrary measures ,
This is a combination of four separately computed energies, each subject to the convention that non-integrable integrals equal . It is not defined as an integral against the signed measure .
Pairwise potential pairPotential. For a real and a finite family of points ,
- The points are arbitrary: they need not lie on the sphere and may repeat.
- For or the sum is empty and equals .
Normalised counting measure normCounting. For points ,
where is the Dirac mass at . Repeated points accumulate mass. For the sum is the zero measure, and since , is the zero measure.
Weak convergence WeakStarTendsto.* A sequence of measures on converges to a measure when, for every continuous function ,
- The test functions are not required to be bounded or compactly supported.
- The measures are not required to be finite or probability measures.
- Each integral of a non-integrable is taken to be .
Hypergeometric function hyp0F1. For real and ,
where is the rising factorial.
- The term is , since and , including when .
- Division by zero yields . So if is a non-positive integer, every term with , i.e. , is rather than undefined.
- The sum is an unconditional sum of reals; if the family were not summable, the value would be .
Exponential potential expPotential. For a real , a measure on and ,
- There is no sign condition on .
- For the quotient is by the division convention. The integrand is then , and if that is finite, and otherwise.
- In general, a non-integrable integrand gives the value .
- Neither nor is restricted to the sphere.
Relaxed objective relaxedObjective. For real and a measure on ,
- Here ; in particular this applies at every point where takes its junk value .
- A non-integrable integrand gives the value .
Positive-pair law IsPosPairLaw. For a measure on and a measure on , the property holds exactly when both of the following are true:
- is invariant under the swap ;
- the first marginal of , i.e. its image under , equals .
Neither measure is required to be a probability measure or to be finite. The two measures must, however, have the same total mass.
Encoder IsEncoder. A map is an encoder when both of the following are true:
- is Borel measurable;
- for every .
When no such map exists.
Contrastive loss contrastiveLoss. The inputs are:
- measures on and on ;
- any function , not required to be an encoder or measurable;
- a real ;
- a natural number .
The loss is
The integral is over the pair drawn from together with an independent -tuple of negatives drawn from the -fold product of . Each negative term pairs with .
Edge cases:
- For the sum is empty, the ratio is and the integrand is , so the loss is .
- For every exponent is by the division convention. The integrand is then the constant .
- No sign condition is placed on .
- A non-integrable integrand gives the value .
Alignment term alignTerm. For a measure , any and real ,
- For the prefactor is , so the term is .
- A non-integrable integrand gives integral .
Uniformity term uniformTerm. For a measure , any and real ,
The usual conventions apply:
- ;
- division by gives ;
- non-integrable integrals are .
Alignment loss alignLoss. For a measure , any and any real ,
where the power is the real power.
- is not required to be positive.
- At points where , the convention gives for and .
- A non-integrable integrand gives the value .
Uniformity loss uniformLoss. For a measure , any and any real ,
- is not required to be positive.
- .
- Non-integrable integrals are .
Perfect alignment PerfectlyAligned. The property holds exactly when
It holds trivially if . The map is not required to be an encoder.
Perfect uniformity PerfectlyUniform. The property holds exactly when the image of under equals :
where is the uniform measure on the sphere defined above.
- The image measure is defined to be the zero measure when is not (almost-everywhere) measurable.
- For , is the zero measure. The condition then holds exactly when is the zero measure. For measurable , this means .
- is not separately required to be a probability measure.
Confirmed by the mission captain (proposal self-audit).
Confirmed by the moderator at approval.