Algorithmresearch
SimCSE
Also called simple contrastive sentence embeddings.
Train sentence encoders by a contrastive loss in which the positive for a sentence is the same sentence passed again under a new dropout mask.
- Solves
- Sentence embedding
- Time
- O(n^2 d) worst
- Space
- O(n^2 + n d) extra
- Where
- d = the width of the sentence vectors; n = the number of sentences in the batch
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterativenot supervised
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tianyu Gao, Xingcheng Yao, Danqi Chen, 2021
SimCSE fine-tunes a pretrained encoder such as BERT so that its sentence vectors solve the sentence embedding problem well. It passes each sentence of a batch through the encoder twice. Dropout picks a new random mask each time, so the two vectors differ a little, and the loss asks each vector to be closer in cosine similarity to its own twin than to the vectors of the other sentences of the batch. The loss is a cross-entropy over a softmax of scaled cosines, known as InfoNCE; the value of the method for downstream tasks is a measurement, not a theorem.
In plain words
A model that turns sentences into vectors should put sentences with the same meaning close together and spread all the other sentences apart. Labeled pairs of paraphrases are expensive, so SimCSE makes its own pairs. It reads the same sentence twice, and each time it switches off a different random tenth of the network. The two results are almost the same, but not quite, so they make a natural pair. Then it plays a matching game inside each batch: for each sentence it must find its twin among all the second copies. The training makes this game easy to win. To win, the model must keep twins close and push different sentences away from each other, which is what a good sentence vector needs.
The problem
The input of one training step is a batch of sentences and an encoder with dropout. Let under one dropout mask and under a second, independent mask. In the supervised form, is the vector of a sentence that the premise entails, and a hard negative is the vector of a sentence that contradicts it. The output is the loss and its gradient with respect to every vector, which backpropagation then passes into the encoder.
With the temperature , the loss for sentence is
and the batch loss is the mean of the . The second sum is absent in the unsupervised form. The other sentences of the batch serve as the negatives of sentence , so no negative sampling step is needed.
The algorithm
SIMCSE-LOSS(h_1 .. h_N, h+_1 .. h+_N, τ, optional h-_1 .. h-_N)- 1
N ← the number of sentences in the batch - 2
for i ← 1 to N do - 3
z_ij ← cos(h_i, h+_j) / τ for j ← 1 to N - 4
if hard negatives are given then z'_ij ← cos(h_i, h-_j) / τ for j ← 1 to N - 5
lz_i ← LOG-SUM-EXP(z_i1 .. z_iN, z'_i1 .. z'_iN); ℓ_i ← lz_i - z_ii - 6
loss ← (ℓ_1 + ... + ℓ_N) / N - 7
for each pair i, j do p_ij ← exp(z_ij - lz_i) - 8
g ← (p_ij - [i = j]) / (N τ) - 9
∇h_i ← ∇h_i + g · ∂cos(h_i, h+_j) / ∂h_i - 10
∇h+_j ← ∇h+_j + g · ∂cos(h_i, h+_j) / ∂h+_j - 11
return loss, ∇h, ∇h+, ∇h-
Each row is a softmax classification over (or ) candidates whose correct class is . Line L5 uses the log-sum-exp trick, so line L7 never takes the exponential of a positive number. A hard negative adds the same two updates with , where , and with no term, since it is never the correct class. The cosine gradient is .
In training, line L1 runs on the encoder outputs of a batch that holds each sentence twice. The paper uses BERT or RoBERTa, the [CLS] vector with a small MLP on top during unsupervised training (the MLP is removed at test time), the standard dropout rate of 0.1 and .
Example
Take and vectors in two dimensions, written for this page: , , and , with and no hard negatives. With , the cosines are:
Row 1 has the logits . The positive wins with , and . Row 2 has the logits : the twin is no closer than the other sentence, so and . The batch loss is .
The gradient with respect to is . A step against it moves toward negative , which is toward its twin and away from . The gradient with respect to is exactly 0 here: both cosine gradients at point along , and their weights and cancel. With instead, falls to about while stays , so the loss is : a small temperature puts nearly all the weight on the rows that are still wrong.
Correctness
Two exact statements hold, and the proof below gives both. First, lines L1 to L6 compute the loss of equations 1 and 5 of the paper: log-sum-exp is an identity, not an approximation. Second, lines L7 to L11 return its exact gradient. The derivative of with respect to the logit is , as for any softmax cross-entropy, and the chain rule through gives lines L8 to L10. The tests compare this gradient with central differences.
Two more facts follow. Each is at least 0, and it is 0 only in the limit where the positive takes all the weight. Each gradient is orthogonal to its own vector, so the loss depends only on the directions of the vectors, not on their lengths.
That the trained vectors are good sentence vectors is not a theorem. It is a measurement, given below.
Proof: The SimCSE loss is computed exactly in log space and its gradient is exactfull
We use the pseudocode of the page. The batch has sentences. The vectors , and, when hard negatives are given, are nonzero vectors of . The temperature is . Write and , so that and . The loss of the paper is
where the second sum is absent when there are no hard negatives (equation 1 of Gao, Yao and Chen 2021 without it, equation 5 with it).
Lemma 1 (the loss). Lines L1 to L6 return .
Proof. For a finite list with maximum , , because . The helper log_sum computes the right side, so line L5 sets . Then , which is what line L5 stores, and line L6 takes the mean. Every exponent in the right side is at most 0, so no term overflows, whatever the size of .
Lemma 2 (the gradient of the cosine). For nonzero with ,
and the same with and swapped. This gradient is orthogonal to .
Proof. , and . The product rule gives , which is the formula. Its inner product with is .
Lemma 3 (the gradient with respect to the logits). and , where and . The row of the logits does not enter for .
Proof. . The derivative of with respect to is , and the derivative of is . The same holds for , which never equals . The second statement holds because uses only and .
Theorem. Lines L7 to L11, with the hard-negative terms of the code, return , and exactly.
Proof. Line L7 computes by Lemma 1, and the code computes the same way. By Lemma 3 and ,
The first is the value of line L8, and the second is the value g2 of the code. The vector enters only the similarities and of row , the vector only the similarities of column , and only the of column . By the chain rule,
and the same for . Lines L9 and L10 add exactly these terms, with the cosine gradients of Lemma 2, once for each pair . The accumulators start at 0, so after the loop they hold the sums. Line L11 returns them.
Consequences used by the tests.
- . Since every cosine is in , each difference is at least , so without hard negatives .
- For and no hard negatives, , so , and every gradient is 0.
- Each gradient is a sum of cosine gradients of Lemma 2 taken at the same vector, so it is orthogonal to that vector. The loss does not change when a vector is multiplied by a positive number, since the cosines do not change.
- If the are orthonormal, then , for , and .
Complexity
The model is the real-RAM. For the loss and the gradient, with the encoder outputs given:
- Logits. Lines L2 to L4 compute cosines (or ), each in time: .
- Gradient. Lines L7 to L10 do work for each pair: .
- Space. for the logits and for the gradients.
In training, the two forward passes of the encoder and the backward pass dominate this cost. Each sentence goes through the encoder twice, so a step of unsupervised SimCSE costs about twice a plain fine-tuning step on the same batch. The training time itself is a measurement on given hardware.
Properties
- Unsupervised form. It needs only raw sentences. The paper trains on sentences from English Wikipedia.
- In-batch negatives. The number of negatives per sentence is (or with hard negatives). It grows with the batch at no extra encoder cost.
- Scale invariance. The loss uses only cosines, so it ignores the length of each vector.
- Temperature. A small sharpens the softmax and puts the weight on the hardest negatives. The paper reports as the best of the values it tried, a measurement.
- Alignment and uniformity. With the measures of Wang and Isola 2020, the alignment is the mean of over positive pairs, and the uniformity is of the mean of over all pairs, both on unit vectors. The paper measures that dropout noise keeps the alignment good while training makes the uniformity better. It also argues, through a limit with many negatives, that the loss flattens the singular value spectrum of the embedding matrix and so works against anisotropy.
Variants and improvements
- Supervised SimCSE. The positive is an entailment hypothesis and the hard negative is a contradiction hypothesis of the same premise, taken from the SNLI and MultiNLI data sets of natural language inference, about 314,000 triples. This is equation 5 of the paper.
- Discrete augmentations. Cropping, word deletion, synonym replacement and masked-word replacement make the second view instead of dropout. On the STS-B development set the paper measures all of them below dropout alone.
- Symmetric loss. SimCLR and many later papers add the same loss with the roles of and swapped. SimCSE uses one direction.
- Later variants. DiffCSE (Chuang et al. 2022) adds a replaced-token detection task, and ESimCSE (Wu et al. 2022) repeats words to change the length of the second view and keeps a queue of earlier batches as extra negatives.
- Retrieval. The same in-batch softmax trains the question and passage encoders of dense passage retrieval, with labeled pairs instead of dropout pairs.
When to use it
Use unsupervised SimCSE to adapt a pretrained encoder to sentence similarity when only unlabeled text in the target domain is at hand. Use the supervised form when entailment pairs or other paraphrase pairs exist. In the measurements of the paper, with BERT-base, the average Spearman correlation over seven semantic textual similarity tasks is 76.25 for the unsupervised form and 81.57 for the supervised form. Like Sentence-BERT, it gives one vector per sentence, so a search over sentences needs encoder passes. For a quick baseline with no training, an average of word vectors or SIF is cheaper.
Pitfalls
- The same mask twice. If both passes use the same dropout mask, or if the encoder is in evaluation mode, , and the loss only pushes sentences apart. The paper measures a large drop in quality for this case and for no dropout at all. Run both passes in training mode, as one batch of sentences or as two calls.
- Duplicate sentences in a batch. If , the vector is a false negative for row . Remove duplicates before batching.
- Plain exponentials. With cosines in and , the largest logit is 20, which double precision holds. For below about , or with dot products instead of cosines, overflows. Use line L5.
- Mean and sum. Line L6 takes the mean over the batch. A sum makes the gradient grow with , which changes the right learning rate.
- Small batches. With few negatives the task is too easy and the uniformity gains are small. The batch size is a tuned value; the paper reports it with the learning rate for each model.
Implementations
The code takes the two encoder outputs (and the hard negatives, when given) as given and implements the loss, its exact gradient and the alignment and uniformity measures; it does not train an encoder. It uses the log-sum-exp of the shared log-space helper of this area.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
simcse.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simcse/. The authors are listed in prov/355PND.jsonl.
"""The SimCSE contrastive loss and its gradient.
The code takes the encoder outputs as given: H holds the N sentence vectors
of a batch under one dropout mask, Hp the same N sentences under a second
dropout mask (unsupervised SimCSE) or their entailment partners (supervised
SimCSE), and Hn, when given, one hard negative per sentence (the
contradiction hypotheses of supervised SimCSE). It implements the loss of
Gao, Yao and Chen 2021 (their equations 1 and 5) and its exact gradient with
respect to every vector. It does not train an encoder.
The loss is in nats. Matrices are lists of rows.
"""
import math
from typing import List, Optional, Sequence, Tuple
from nlslog import log_sum
Vector = List[float]
Matrix = List[List[float]]
def dot(a: Sequence[float], b: Sequence[float]) -> float:
return math.fsum(x * y for x, y in zip(a, b))
def norm(a: Sequence[float]) -> float:
return math.sqrt(dot(a, a))
def cosine(a: Sequence[float], b: Sequence[float]) -> float:
"""The cosine a.b / (|a| |b|). Raise ValueError for a zero vector."""
na, nb = norm(a), norm(b)
if na == 0 or nb == 0:
raise ValueError("the cosine of a zero vector is not defined")
return dot(a, b) / (na * nb)
def cosine_grad(a: Sequence[float], b: Sequence[float]) -> Tuple[Vector, Vector]:
"""The gradients of cos(a, b) with respect to a and to b.
d cos / d a = b / (|a| |b|) - cos(a, b) a / |a|^2, and the same with a
and b swapped.
"""
na, nb = norm(a), norm(b)
c = dot(a, b) / (na * nb)
ga = [y / (na * nb) - c * x / (na * na) for x, y in zip(a, b)]
gb = [x / (na * nb) - c * y / (nb * nb) for x, y in zip(a, b)]
return ga, gb
def similarity_matrix(H: Matrix, P: Matrix) -> Matrix:
"""The N x M matrix of cosines cos(H[i], P[j])."""
return [[cosine(h, p) for p in P] for h in H]
def _check(H: Matrix, Hp: Matrix, Hn: Optional[Matrix], tau: float) -> None:
if not H:
raise ValueError("the batch is empty")
if len(Hp) != len(H) or (Hn is not None and len(Hn) != len(H)):
raise ValueError("H, Hp and Hn must have one row per sentence")
if not tau > 0:
raise ValueError("the temperature must be positive")
def simcse_loss_and_grad(
H: Matrix, Hp: Matrix, tau: float = 0.05, Hn: Optional[Matrix] = None
) -> Tuple[float, Matrix, Matrix, Optional[Matrix]]:
"""Return (loss, dL/dH, dL/dHp, dL/dHn) for one batch.
loss = (1/N) sum_i [ log_sum_j (z_ij, z'_ij) - z_ii ] with
z_ij = cos(h_i, hp_j) / tau and z'_ij = cos(h_i, hn_j) / tau. The other
rows of the batch are the negatives of row i (in-batch negatives).
Cost: O(N^2 d) time and O(N^2 + N d) space.
"""
_check(H, Hp, Hn, tau)
n = len(H) # @line L1
z = [[0.0] * n for _ in range(n)]
zn = [[0.0] * n for _ in range(n)] if Hn is not None else None
log_z = [0.0] * n
losses = [0.0] * n
for i in range(n): # @line L2
for j in range(n): # @line L3
z[i][j] = cosine(H[i], Hp[j]) / tau
row = list(z[i])
if zn is not None: # @line L4
for j in range(n):
zn[i][j] = cosine(H[i], Hn[j]) / tau
row += zn[i]
log_z[i] = log_sum(row) # @line L5
losses[i] = log_z[i] - z[i][i]
loss = math.fsum(losses) / n # @line L6
d = len(H[0])
gH = [[0.0] * d for _ in range(n)]
gP = [[0.0] * d for _ in range(n)]
gN = [[0.0] * d for _ in range(n)] if Hn is not None else None
for i in range(n):
for j in range(n):
p_ij = math.exp(z[i][j] - log_z[i]) # @line L7
g = (p_ij - (1.0 if i == j else 0.0)) / (n * tau) # @line L8
ga, gb = cosine_grad(H[i], Hp[j])
for k in range(d):
gH[i][k] += g * ga[k] # @line L9
gP[j][k] += g * gb[k] # @line L10
if zn is not None:
g2 = math.exp(zn[i][j] - log_z[i]) / (n * tau)
ga, gb = cosine_grad(H[i], Hn[j])
for k in range(d):
gH[i][k] += g2 * ga[k]
gN[j][k] += g2 * gb[k]
return loss, gH, gP, gN # @line L11
def simcse_loss(H: Matrix, Hp: Matrix, tau: float = 0.05, Hn: Optional[Matrix] = None) -> float:
"""The SimCSE loss alone, in nats."""
return simcse_loss_and_grad(H, Hp, tau, Hn)[0]
def simcse_loss_direct(H: Matrix, Hp: Matrix, tau: float = 0.05, Hn: Optional[Matrix] = None) -> float:
"""The same loss by the formula of the paper, with plain exp and no log-sum-exp.
It overflows for a small tau (exp of more than about 709). Use it only to
check simcse_loss.
"""
_check(H, Hp, Hn, tau)
n = len(H)
total = 0.0
for i in range(n):
den = sum(math.exp(cosine(H[i], Hp[j]) / tau) for j in range(n))
if Hn is not None:
den += sum(math.exp(cosine(H[i], Hn[j]) / tau) for j in range(n))
total += -math.log(math.exp(cosine(H[i], Hp[i]) / tau) / den)
return total / n
def alignment(H: Matrix, Hp: Matrix) -> float:
"""The alignment of Wang and Isola 2020: the mean of |f(x) - f(x+)|^2 over the pairs.
The vectors are normalized to unit length first, as in the paper.
"""
total = 0.0
for h, p in zip(H, Hp):
nh, np_ = norm(h), norm(p)
total += math.fsum((x / nh - y / np_) ** 2 for x, y in zip(h, p))
return total / len(H)
def uniformity(H: Matrix, t: float = 2.0) -> float:
"""The uniformity of Wang and Isola 2020: log of the mean of exp(-t |f(x) - f(y)|^2) over distinct pairs.
The vectors are normalized to unit length first. Lower is more uniform.
"""
units = [[x / norm(h) for x in h] for h in H]
terms = []
for i in range(len(units)):
for j in range(i + 1, len(units)):
sq = math.fsum((a - b) ** 2 for a, b in zip(units[i], units[j]))
terms.append(-t * sq)
if not terms:
raise ValueError("uniformity needs at least two vectors")
return log_sum(terms) - math.log(len(terms))
test_simcse.py 206 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/simcse/. The authors are listed in prov/355PND.jsonl.
import math
import random
import pytest
from simcse import (
alignment,
cosine,
cosine_grad,
simcse_loss,
simcse_loss_and_grad,
simcse_loss_direct,
uniformity,
)
def rand_matrix(rng, n, d):
return [[rng.gauss(0.0, 1.0) for _ in range(d)] for _ in range(n)]
def noisy_copy(rng, H, sigma):
return [[x + rng.gauss(0.0, sigma) for x in row] for row in H]
def numeric_grad(f, M, h=1e-6):
g = []
for i in range(len(M)):
row = []
for k in range(len(M[i])):
old = M[i][k]
M[i][k] = old + h
up = f()
M[i][k] = old - h
down = f()
M[i][k] = old
row.append((up - down) / (2 * h))
g.append(row)
return g
def assert_close_matrix(A, B, tol):
for ra, rb in zip(A, B):
for x, y in zip(ra, rb):
assert abs(x - y) <= tol, (x, y)
def test_page_example():
H = [[1.0, 0.0], [0.0, 1.0]]
Hp = [[1.0, 1.0], [-1.0, 1.0]]
tau = 0.5
c = 1 / math.sqrt(2)
# z_11 = c / tau, z_12 = -c / tau, z_21 = z_22 = c / tau.
l1 = math.log(math.exp(c / tau) + math.exp(-c / tau)) - c / tau
l2 = math.log(2 * math.exp(c / tau)) - c / tau
assert l2 == pytest.approx(math.log(2), abs=1e-12)
assert simcse_loss(H, Hp, tau) == pytest.approx((l1 + l2) / 2, abs=1e-12)
assert simcse_loss(H, Hp, tau) == pytest.approx(0.3753, abs=1e-4)
def test_matches_direct_formula():
rng = random.Random(1)
for tau in (1.0, 0.5, 0.05):
H = rand_matrix(rng, 5, 4)
Hp = noisy_copy(rng, H, 0.3)
Hn = rand_matrix(rng, 5, 4)
assert simcse_loss(H, Hp, tau) == pytest.approx(simcse_loss_direct(H, Hp, tau), rel=1e-12)
assert simcse_loss(H, Hp, tau, Hn) == pytest.approx(simcse_loss_direct(H, Hp, tau, Hn), rel=1e-12)
def test_small_temperature_overflows_without_log_space():
rng = random.Random(2)
H = rand_matrix(rng, 4, 3)
Hp = noisy_copy(rng, H, 0.1)
with pytest.raises(OverflowError):
simcse_loss_direct(H, Hp, 1e-3)
loss = simcse_loss(H, Hp, 1e-3)
assert math.isfinite(loss) and loss >= 0
@pytest.mark.parametrize("tau", [0.5, 0.05])
@pytest.mark.parametrize("hard", [False, True])
def test_gradient_against_central_differences(tau, hard):
rng = random.Random(3)
H = rand_matrix(rng, 4, 3)
Hp = noisy_copy(rng, H, 0.5)
Hn = rand_matrix(rng, 4, 3) if hard else None
_, gH, gP, gN = simcse_loss_and_grad(H, Hp, tau, Hn)
def f():
return simcse_loss(H, Hp, tau, Hn)
assert_close_matrix(gH, numeric_grad(f, H), 1e-5)
assert_close_matrix(gP, numeric_grad(f, Hp), 1e-5)
if hard:
assert_close_matrix(gN, numeric_grad(f, Hn), 1e-5)
else:
assert gN is None
def test_cosine_gradient():
rng = random.Random(4)
a = [rng.gauss(0, 1) for _ in range(5)]
b = [rng.gauss(0, 1) for _ in range(5)]
ga, gb = cosine_grad(a, b)
h = 1e-6
for k in range(5):
ap = list(a)
am = list(a)
ap[k] += h
am[k] -= h
assert ga[k] == pytest.approx((cosine(ap, b) - cosine(am, b)) / (2 * h), abs=1e-7)
bp = list(b)
bm = list(b)
bp[k] += h
bm[k] -= h
assert gb[k] == pytest.approx((cosine(a, bp) - cosine(a, bm)) / (2 * h), abs=1e-7)
# The cosine does not change along a, so its gradient is orthogonal to a.
assert math.fsum(x * y for x, y in zip(ga, a)) == pytest.approx(0.0, abs=1e-12)
def test_gradient_is_orthogonal_to_each_vector():
rng = random.Random(5)
H = rand_matrix(rng, 6, 4)
Hp = noisy_copy(rng, H, 0.2)
_, gH, gP, _ = simcse_loss_and_grad(H, Hp, 0.05)
for row, g in zip(H + Hp, gH + gP):
assert math.fsum(x * y for x, y in zip(row, g)) == pytest.approx(0.0, abs=1e-9)
def test_scale_invariance():
rng = random.Random(6)
H = rand_matrix(rng, 5, 3)
Hp = noisy_copy(rng, H, 0.3)
scaled = [[3.0 * x for x in row] for row in H]
assert simcse_loss(scaled, Hp) == pytest.approx(simcse_loss(H, Hp), rel=1e-12)
def test_single_sentence_has_zero_loss():
loss, gH, gP, _ = simcse_loss_and_grad([[1.0, 2.0]], [[0.5, -1.0]], 0.05)
assert loss == pytest.approx(0.0, abs=1e-15)
assert all(abs(x) < 1e-15 for x in gH[0] + gP[0])
@pytest.mark.parametrize("n", [2, 3, 4])
def test_orthonormal_batch_closed_form(n):
tau = 0.05
E = [[1.0 if i == k else 0.0 for k in range(4)] for i in range(n)]
expected = math.log(1 + (n - 1) * math.exp(-1 / tau))
assert simcse_loss(E, E, tau) == pytest.approx(expected, rel=1e-9)
def test_loss_is_at_least_the_identical_pair_bound():
rng = random.Random(7)
for _ in range(50):
n = rng.randint(2, 6)
H = rand_matrix(rng, n, 3)
Hp = noisy_copy(rng, H, 0.4)
tau = rng.choice([0.05, 0.1, 1.0])
# Each row has z_ii <= 1/tau and z_ij >= -1/tau, so l_i >= log(1 + (n - 1) exp(-2/tau)).
bound = math.log(1 + (n - 1) * math.exp(-2 / tau))
assert simcse_loss(H, Hp, tau) >= bound - 1e-12
def test_hard_negatives_raise_the_loss():
rng = random.Random(8)
H = rand_matrix(rng, 5, 4)
Hp = noisy_copy(rng, H, 0.3)
Hn = rand_matrix(rng, 5, 4)
assert simcse_loss(H, Hp, 0.05, Hn) > simcse_loss(H, Hp, 0.05)
def test_gradient_steps_lower_the_loss():
rng = random.Random(9)
H = rand_matrix(rng, 6, 4)
Hp = noisy_copy(rng, H, 1.0)
tau = 0.1
before = simcse_loss(H, Hp, tau)
for _ in range(20):
_, gH, gP, _ = simcse_loss_and_grad(H, Hp, tau)
H = [[x - 0.05 * g for x, g in zip(r, gr)] for r, gr in zip(H, gH)]
Hp = [[x - 0.05 * g for x, g in zip(r, gr)] for r, gr in zip(Hp, gP)]
assert simcse_loss(H, Hp, tau) < before
def test_alignment_and_uniformity_hand_values():
assert alignment([[1.0, 0.0]], [[2.0, 0.0]]) == pytest.approx(0.0)
assert alignment([[1.0, 0.0]], [[0.0, 3.0]]) == pytest.approx(2.0)
assert uniformity([[1.0, 0.0], [-1.0, 0.0]]) == pytest.approx(-8.0)
square = [[1.0, 0.0], [0.0, 1.0], [-1.0, 0.0], [0.0, -1.0]]
# Four pairs at squared distance 2 and two at 4.
expected = math.log((4 * math.exp(-4) + 2 * math.exp(-8)) / 6)
assert uniformity(square) == pytest.approx(expected)
def test_bad_input():
with pytest.raises(ValueError):
simcse_loss([], [])
with pytest.raises(ValueError):
simcse_loss([[1.0]], [[1.0], [2.0]])
with pytest.raises(ValueError):
simcse_loss([[1.0]], [[1.0]], tau=0.0)
with pytest.raises(ValueError):
cosine([0.0, 0.0], [1.0, 0.0])
History
The InfoNCE loss comes from contrastive predictive coding (van den Oord, Li and Vinyals 2018). SimCLR (Chen et al. 2020) used it with in-batch negatives on two augmented views of each image. For sentences, earlier work made the second view by editing the text or took it from labeled pairs. Gao, Yao and Chen 2021 showed at EMNLP that the dropout noise already in the encoder is enough to make the two views, and that it beats the discrete edits they tried. The paper became a standard baseline for sentence vectors, and many later methods change only the way they build the positive and negative pairs.
References
- Tianyu Gao, Xingcheng Yao and Danqi Chen, SimCSE, simple contrastive learning of sentence embeddings, Proceedings of EMNLP 2021, pages 6894 to 6910, equation 1 (the unsupervised loss), equation 5 (the loss with hard negatives), the comparison of dropout with discrete augmentations, and the analysis by alignment and uniformity
- Wang and Isola 2020, the definitions of the alignment and uniformity measures
- van den Oord, Li and Vinyals 2018, the InfoNCE loss
- Jacob Devlin, Ming-Wei Chang, Kenton Lee and Kristina Toutanova, BERT, pre-training of deep bidirectional transformers for language understanding, NAACL-HLT 2019, the encoder that SimCSE fine-tunes, and its dropout of 0.1
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 355PND Edit this page History Report an error Markdown