Algorithm Search⌘K

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.

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
Properties
randomizednot exactofflineiterativenot supervised
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 NN sentences x1,…,xNx_1, \ldots, x_N and an encoder ff with dropout. Let hi=f(xi)h_i = f(x_i) under one dropout mask and hi+=f(xi)h^+_i = f(x_i) under a second, independent mask. In the supervised form, hi+h^+_i is the vector of a sentence that the premise xix_i entails, and a hard negative hi−h^-_i 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 τ>0\tau > 0, the loss for sentence ii is

ℓi=−log⁡ecos⁡(hi,hi+)/τ∑j=1Necos⁡(hi,hj+)/τ+∑j=1Necos⁡(hi,hj−)/τ,\ell_i = -\log \frac{e^{\cos(h_i, h^+_i)/\tau}}{\sum_{j=1}^{N} e^{\cos(h_i, h^+_j)/\tau} + \sum_{j=1}^{N} e^{\cos(h_i, h^-_j)/\tau}},

and the batch loss is the mean of the ℓi\ell_i. The second sum is absent in the unsupervised form. The other sentences of the batch serve as the negatives of sentence ii, so no negative sampling step is needed.

The algorithm

  1. SIMCSE-LOSS(h_1 .. h_N, h+_1 .. h+_N, τ, optional h-_1 .. h-_N)
  2. 1N ← the number of sentences in the batch
  3. 2for i ← 1 to N do
  4. 3z_ij ← cos(h_i, h+_j) / τ for j ← 1 to N
  5. 4if hard negatives are given then z'_ij ← cos(h_i, h-_j) / τ for j ← 1 to N
  6. 5lz_i ← LOG-SUM-EXP(z_i1 .. z_iN, z'_i1 .. z'_iN); ℓ_i ← lz_i - z_ii
  7. 6loss ← (ℓ_1 + ... + ℓ_N) / N
  8. 7for each pair i, j do p_ij ← exp(z_ij - lz_i)
  9. 8g ← (p_ij - [i = j]) / (N τ)
  10. 9∇h_i ← ∇h_i + g · ∂cos(h_i, h+_j) / ∂h_i
  11. 10∇h+_j ← ∇h+_j + g · ∂cos(h_i, h+_j) / ∂h+_j
  12. 11return loss, ∇h, ∇h+, ∇h-

Each row ii is a softmax classification over NN (or 2N2N) candidates whose correct class is j=ij = i. 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 g′=pij′/(Nτ)g' = p'_{ij} / (N \tau), where pij′=exp⁡(zij′−lzi)p'_{ij} = \exp(z'_{ij} - lz_i), and with no [i=j][i = j] term, since it is never the correct class. The cosine gradient is ∂cos⁡(a,b)/∂a=b/(∥a∥∥b∥)−cos⁡(a,b) a/∥a∥2\partial \cos(a, b) / \partial a = b / (\|a\| \|b\|) - \cos(a, b)\, a / \|a\|^2.

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 τ=0.05\tau = 0.05.

Example

Take N=2N = 2 and vectors in two dimensions, written for this page: h1=(1,0)h_1 = (1, 0), h2=(0,1)h_2 = (0, 1), h1+=(1,1)h^+_1 = (1, 1) and h2+=(−1,1)h^+_2 = (-1, 1), with τ=0.5\tau = 0.5 and no hard negatives. With c=1/2=0.7071c = 1/\sqrt{2} = 0.7071, the cosines are:

h1+h^+_1 h2+h^+_2
h1h_1 cc −c-c
h2h_2 cc cc

Row 1 has the logits (1.4142,−1.4142)(1.4142, -1.4142). The positive wins with p11=0.9442p_{11} = 0.9442, and ℓ1=log⁡(1+e−2.8284)=0.0574\ell_1 = \log(1 + e^{-2.8284}) = 0.0574. Row 2 has the logits (1.4142,1.4142)(1.4142, 1.4142): the twin is no closer than the other sentence, so p21=p22=0.5p_{21} = p_{22} = 0.5 and ℓ2=log⁡2=0.6931\ell_2 = \log 2 = 0.6931. The batch loss is 0.37530.3753.

The gradient with respect to h2h_2 is (0.7071,0)(0.7071, 0). A step against it moves h2h_2 toward negative xx, which is toward its twin h2+h^+_2 and away from h1+h^+_1. The gradient with respect to h1h_1 is exactly 0 here: both cosine gradients at h1h_1 point along (0,1)(0, 1), and their weights g11=−0.0558g_{11} = -0.0558 and g12=0.0558g_{12} = 0.0558 cancel. With τ=0.05\tau = 0.05 instead, ℓ1\ell_1 falls to about 5×10−135 \times 10^{-13} while ℓ2\ell_2 stays log⁡2\log 2, so the loss is 0.34660.3466: 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 ℓi\ell_i with respect to the logit zijz_{ij} is pij−[i=j]p_{ij} - [i = j], as for any softmax cross-entropy, and the chain rule through zij=cos⁡(hi,hj+)/τz_{ij} = \cos(h_i, h^+_j)/\tau gives lines L8 to L10. The tests compare this gradient with central differences.

Two more facts follow. Each ℓi\ell_i 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 N≥1N \ge 1 sentences. The vectors hih_i, hi+h^+_i and, when hard negatives are given, hi−h^-_i are nonzero vectors of Rd\mathbb{R}^d. The temperature is τ>0\tau > 0. Write sij=cos⁡(hi,hj+)s_{ij} = \cos(h_i, h^+_j) and sij′=cos⁡(hi,hj−)s'_{ij} = \cos(h_i, h^-_j), so that zij=sij/τz_{ij} = s_{ij} / \tau and zij′=sij′/τz'_{ij} = s'_{ij} / \tau. The loss of the paper is

L=1N∑i=1Nℓi,ℓi=−log⁡eziiZi,Zi=∑j=1Nezij+∑j=1Nezij′,L = \frac{1}{N} \sum_{i=1}^{N} \ell_i, \qquad \ell_i = -\log \frac{e^{z_{ii}}}{Z_i}, \qquad Z_i = \sum_{j=1}^{N} e^{z_{ij}} + \sum_{j=1}^{N} e^{z'_{ij}},

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 LL.

Proof. For a finite list x1,…,xmx_1, \ldots, x_m with maximum MM, log⁡∑kexk=M+log⁡∑kexk−M\log \sum_k e^{x_k} = M + \log \sum_k e^{x_k - M}, because exk=eMexk−Me^{x_k} = e^M e^{x_k - M}. The helper log_sum computes the right side, so line L5 sets lzi=log⁡Zilz_i = \log Z_i. Then ℓi=−log⁡ezii+log⁡Zi=lzi−zii\ell_i = -\log e^{z_{ii}} + \log Z_i = lz_i - z_{ii}, 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 1/τ1 / \tau. □\square

Lemma 2 (the gradient of the cosine). For nonzero a,ba, b with c=cos⁡(a,b)c = \cos(a, b),

∂c∂a=b∥a∥∥b∥−ca∥a∥2,\frac{\partial c}{\partial a} = \frac{b}{\|a\| \|b\|} - c \frac{a}{\|a\|^2},

and the same with aa and bb swapped. This gradient is orthogonal to aa.

Proof. c=(a⋅b)∥a∥−1∥b∥−1c = (a \cdot b) \|a\|^{-1} \|b\|^{-1}, and ∂∥a∥/∂a=a/∥a∥\partial \|a\| / \partial a = a / \|a\|. The product rule gives b∥a∥−1∥b∥−1−(a⋅b)∥a∥−2∥b∥−1a/∥a∥b \|a\|^{-1} \|b\|^{-1} - (a \cdot b) \|a\|^{-2} \|b\|^{-1} a / \|a\|, which is the formula. Its inner product with aa is (a⋅b)/(∥a∥∥b∥)−c=0(a \cdot b) / (\|a\| \|b\|) - c = 0. □\square

Lemma 3 (the gradient with respect to the logits). ∂ℓi/∂zij=pij−[i=j]\partial \ell_i / \partial z_{ij} = p_{ij} - [i = j] and ∂ℓi/∂zij′=pij′\partial \ell_i / \partial z'_{ij} = p'_{ij}, where pij=ezij/Zip_{ij} = e^{z_{ij}} / Z_i and pij′=ezij′/Zip'_{ij} = e^{z'_{ij}} / Z_i. The row ii of the logits does not enter ℓk\ell_k for k≠ik \ne i.

Proof. ℓi=log⁡Zi−zii\ell_i = \log Z_i - z_{ii}. The derivative of log⁡Zi\log Z_i with respect to zijz_{ij} is ezij/Zie^{z_{ij}} / Z_i, and the derivative of ziiz_{ii} is [i=j][i = j]. The same holds for zij′z'_{ij}, which never equals ziiz_{ii}. The second statement holds because ℓk\ell_k uses only zkjz_{kj} and zkj′z'_{kj}. □\square

Theorem. Lines L7 to L11, with the hard-negative terms of the code, return ∂L/∂hi\partial L / \partial h_i, ∂L/∂hj+\partial L / \partial h^+_j and ∂L/∂hj−\partial L / \partial h^-_j exactly.

Proof. Line L7 computes exp⁡(zij−lzi)=ezij/Zi=pij\exp(z_{ij} - lz_i) = e^{z_{ij}} / Z_i = p_{ij} by Lemma 1, and the code computes pij′p'_{ij} the same way. By Lemma 3 and zij=sij/τz_{ij} = s_{ij} / \tau,

∂L∂sij=pij−[i=j]Nτ,∂L∂sij′=pij′Nτ.\frac{\partial L}{\partial s_{ij}} = \frac{p_{ij} - [i = j]}{N \tau}, \qquad \frac{\partial L}{\partial s'_{ij}} = \frac{p'_{ij}}{N \tau}.

The first is the value gg of line L8, and the second is the value g2 of the code. The vector hih_i enters only the similarities sijs_{ij} and sij′s'_{ij} of row ii, the vector hj+h^+_j only the similarities sijs_{ij} of column jj, and hj−h^-_j only the sij′s'_{ij} of column jj. By the chain rule,

∂L∂hi=∑j∂L∂sij∂sij∂hi+∑j∂L∂sij′∂sij′∂hi,∂L∂hj+=∑i∂L∂sij∂sij∂hj+,\frac{\partial L}{\partial h_i} = \sum_j \frac{\partial L}{\partial s_{ij}} \frac{\partial s_{ij}}{\partial h_i} + \sum_j \frac{\partial L}{\partial s'_{ij}} \frac{\partial s'_{ij}}{\partial h_i}, \qquad \frac{\partial L}{\partial h^+_j} = \sum_i \frac{\partial L}{\partial s_{ij}} \frac{\partial s_{ij}}{\partial h^+_j},

and the same for hj−h^-_j. Lines L9 and L10 add exactly these terms, with the cosine gradients of Lemma 2, once for each pair (i,j)(i, j). The accumulators start at 0, so after the loop they hold the sums. Line L11 returns them. ■\blacksquare

Consequences used by the tests.

  • ℓi=log⁡(1+∑j≠iezij−zii+∑jezij′−zii)≥0\ell_i = \log(1 + \sum_{j \ne i} e^{z_{ij} - z_{ii}} + \sum_j e^{z'_{ij} - z_{ii}}) \ge 0. Since every cosine is in [−1,1][-1, 1], each difference zij−ziiz_{ij} - z_{ii} is at least −2/τ-2 / \tau, so without hard negatives ℓi≥log⁡(1+(N−1)e−2/τ)\ell_i \ge \log(1 + (N - 1) e^{-2/\tau}).
  • For N=1N = 1 and no hard negatives, Z1=ez11Z_1 = e^{z_{11}}, so L=0L = 0, p11=1p_{11} = 1 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 hi=hi+h_i = h^+_i are orthonormal, then zii=1/τz_{ii} = 1 / \tau, zij=0z_{ij} = 0 for i≠ji \ne j, and L=log⁡(1+(N−1)e−1/τ)L = \log(1 + (N - 1) e^{-1/\tau}).

Complexity

The model is the real-RAM. For the loss and the gradient, with the encoder outputs given:

  • Logits. Lines L2 to L4 compute N2N^2 cosines (or 2N22N^2), each in O(d)O(d) time: O(N2d)O(N^2 d).
  • Gradient. Lines L7 to L10 do O(d)O(d) work for each pair: O(N2d)O(N^2 d).
  • Space. O(N2)O(N^2) for the logits and O(Nd)O(N d) 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 10610^6 sentences from English Wikipedia.
  • In-batch negatives. The number of negatives per sentence is N−1N - 1 (or 2N−12N - 1 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 τ\tau sharpens the softmax and puts the weight on the hardest negatives. The paper reports τ=0.05\tau = 0.05 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 ∥f(x)−f(x+)∥2\|f(x) - f(x^+)\|^2 over positive pairs, and the uniformity is log⁡\log of the mean of e−2∥f(x)−f(y)∥2e^{-2\|f(x) - f(y)\|^2} 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 hh and h+h^+ 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 nn sentences needs nn 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, hi=hi+h_i = h^+_i, 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 2N2N sentences or as two calls.
  • Duplicate sentences in a batch. If xi=xjx_i = x_j, the vector hj+h^+_j is a false negative for row ii. Remove duplicates before batching.
  • Plain exponentials. With cosines in [−1,1][-1, 1] and τ=0.05\tau = 0.05, the largest logit is 20, which double precision holds. For τ\tau below about 1/7091/709, or with dot products instead of cosines, eze^{z} overflows. Use line L5.
  • Mean and sum. Line L6 takes the mean over the batch. A sum makes the gradient grow with NN, 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.

nlslog.pyI0RawGitHub
# 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

  1. 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
  2. Wang and Isola 2020, the definitions of the alignment and uniformity measures
  3. van den Oord, Li and Vinyals 2018, the InfoNCE loss
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example