Sign in

Contrastive

Contrastive loss (pairwise margin)

A loss on pairs of embeddings: it pulls similar pairs together and pushes dissimilar pairs apart until they are at least a margin away.

Overview

An embedding model maps inputs to points in space, and the aim is for distance to mean dissimilarity. Contrastive loss trains this with labelled pairs. For a pair marked similar, the loss is the squared distance, so the two points are pulled together like the ends of a spring. For a pair marked dissimilar, the loss is positive only while the points are closer than a chosen margin, and it pushes them apart until they clear it. Beyond the margin a dissimilar pair costs nothing, so the model does not waste effort separating points that are already far apart.

A short history

Sumit Chopra, Raia Hadsell and Yann LeCun introduced this loss in 2005 for face verification, and Hadsell, Chopra and LeCun developed it further in the 2006 paper 'Dimensionality Reduction by Learning an Invariant Mapping'. It trains the siamese networks that Bromley and colleagues had proposed in 1993 for signature verification. The loss made it possible to learn a distance that works for classes never seen in training.

How it works

  1. Take two batches of embeddings aa and bb, and a label for each pair: 1 for similar, 0 for dissimilar.
  2. Compute the Euclidean distance dd between the two embeddings of each pair. A small eps under the square root keeps the gradient defined at distance zero.
  3. For a similar pair the loss is 12d2\tfrac{1}{2} d^{2}.
  4. For a dissimilar pair the loss is 12max⁡(0,m−d)2\tfrac{1}{2}\max(0, m - d)^{2}, where mm is the margin.
  5. Reduce over the batch with reduction.
  6. In backward, similar pairs get a pull along a−ba - b, dissimilar pairs inside the margin get a push, and the gradient for bb is the negative of the one for aa.

Watch out for

  • If every pair is similar, or the margin is ignored, mapping all inputs to one point gives zero loss. Dissimilar pairs are what prevent this collapse.
  • The margin is measured in embedding units. If embeddings are not normalised, the model can satisfy the margin by scaling everything up, without learning better structure.
  • Most random dissimilar pairs are already beyond the margin and give zero gradient. Training slows unless harder pairs are selected.
  • The template scores the pairs you give it. Choosing which pairs to form, and mining hard ones, is left to you.

Use cases

When to use it

Siamese networks for verification and similarity search, such as face or signature matching and duplicate detection, when the training data comes as pairs labelled same or different.

In industry

Identity verification
Face and signature verification systems train a siamese network on pairs labelled same or different, then compare a new sample to an enrolled one by distance.
Duplicate detection
Question and listing sites train on pairs marked duplicate or not, so near-identical posts land close together in the embedding space.
Document processing
Systems that match scanned forms or invoices to known templates learn an embedding from pairs of matching and non-matching pages.

Choosing it: what must hold

  • Pairs of examples labelled similar or dissimilar, or a reliable way to generate such pairs.
  • A margin chosen to suit the scale of the embedding distances.
  • A strategy for finding informative dissimilar pairs, since most random pairs are already far apart.

When to choose something else

IfUse instead
You can form anchor, positive and negative triples and care about relative distanceTriplet loss
You have large batches and want every other item in the batch to act as a negativeInfoNCE
Every example has a class label from a fixed setSoftmax cross-entropy

Math foundations

  1. Distance between the pair

    d=∥a−b∥2=∑k=1D(ak−bk)2d = \lVert a - b \rVert_2 = \sqrt{\sum_{k=1}^{D} (a_k - b_k)^{2}}

    The straight-line distance between the two embeddings. The whole loss is a function of this one number.

  2. The loss for one pair

    ℓ=12 y d2+12 (1−y) max⁡(0,  m−d)2\ell = \tfrac{1}{2}\,y\,d^{2} + \tfrac{1}{2}\,(1 - y)\,\max(0,\; m - d)^{2}

    The label selects one term. Similar pairs pay for any distance. Dissimilar pairs pay only for being closer than the margin mm.

  3. Gradient for a similar pair

    ∂ℓ∂a=a−b(y=1)\frac{\partial \ell}{\partial a} = a - b \qquad (y = 1)

    A pull toward bb in proportion to the separation, like a spring. It shrinks to zero as the pair meets.

  4. Gradient for a dissimilar pair

    ∂ℓ∂a=− (m−d) a−bd(y=0,  d<m)\frac{\partial \ell}{\partial a} = -\,(m - d)\,\frac{a - b}{d} \qquad (y = 0,\; d < m)

    A push directly away from bb, strongest when the points nearly coincide and zero once the distance reaches mm. Beyond the margin the gradient is zero.

  5. The two sides mirror each other

    ∂ℓ∂b=− ∂ℓ∂a\frac{\partial \ell}{\partial b} = -\,\frac{\partial \ell}{\partial a}

    The loss depends only on a−ba - b, so whatever moves aa one way moves bb the other.

Symbols

a,ba, b
the two embeddings of a pair, each of dimension D
dd
the Euclidean distance between them
yy
the pair label: 1 for similar, 0 for dissimilar
mm
the margin, margin in the config, default 1
ℓ\ell
the loss for one pair
DD
the embedding dimension

Worked by hand

A pair at distance d=0.6d = 0.6 with margin m=1m = 1. Compute the loss if the pair is similar, then if it is dissimilar.

y=1:ℓ=12×0.62=0.18y = 1: \quad \ell = \tfrac{1}{2} \times 0.6^{2} = 0.18
y=0:ℓ=12×(1−0.6)2=12×0.16=0.08y = 0: \quad \ell = \tfrac{1}{2} \times (1 - 0.6)^{2} = \tfrac{1}{2} \times 0.16 = 0.08
y=0,  d=1.3:ℓ=12×max⁡(0,−0.3)2=0y = 0,\; d = 1.3: \quad \ell = \tfrac{1}{2} \times \max(0, -0.3)^{2} = 0

At distance 0.6 a similar pair costs 0.18 and a dissimilar pair costs 0.08. A dissimilar pair at 1.3 is past the margin and costs nothing.

Visual example

Loading the example.

Try this

  • Move across the curve: the height is what the model is charged.
  • Move each control and watch which part of the curve it changes.

Code sample

import numpy as np
from impl import ContrastiveLoss
from config import ContrastiveLossConfig

loss = ContrastiveLoss(ContrastiveLossConfig(margin=1.0))
a = np.array([[0.0, 0.0], [0.0, 0.0]])      # first embedding of each pair
b = np.array([[0.3, 0.4], [0.3, 0.4]])      # second embedding, distance 0.5 in both pairs
label = np.array([1, 0])                    # pair 0 is similar, pair 1 is dissimilar
print(loss.forward(a, b, label))            # (0.5 * 0.25 + 0.5 * 0.25) / 2 = 0.125
g_a, g_b = loss.backward(a, b, label)       # pair 0 is pulled together, pair 1 pushed apart
Read the implementation (64 lines)
"""Contrastive loss on pairs of embeddings: 0.5 * y * d^2 + 0.5 * (1 - y) * max(0, margin - d)^2.

NumPy only. `forward` returns the loss, `backward` its gradients with respect to both embeddings.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import ContrastiveLossConfig
except ImportError:  # run from the template's own folder
    from config import ContrastiveLossConfig

def _embeddings(*arrays) -> list:
    """All inputs as float arrays of one shape (N, D). Raises ValueError otherwise."""
    out = [np.asarray(a, dtype=float) for a in arrays]
    if out[0].ndim != 2 or any(a.shape != out[0].shape for a in out):
        raise ValueError(f"embeddings must all have one shape (N, D), got {[a.shape for a in out]}")
    return out

def _reduce(per_row: np.ndarray, reduction: str):
    """Reduce one loss value per row: "mean" and "sum" give a float, "none" returns the (N,) array."""
    if reduction == "mean":
        return float(per_row.mean())
    return float(per_row.sum()) if reduction == "sum" else per_row


class ContrastiveLoss:
    """Pulls similar pairs together and pushes dissimilar pairs at least `margin` apart."""

    def __init__(self, config: ContrastiveLossConfig | None = None) -> None:
        self.config = config or ContrastiveLossConfig()

    def _prepare(self, a, b, label) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Difference a - b (N, D), distance d (N,) and the label as floats (N,)."""
        a, b = _embeddings(a, b)
        label = np.asarray(label, dtype=float)
        if label.shape != (a.shape[0],) or not np.isin(label, (0.0, 1.0)).all():
            raise ValueError("label must have shape (N,) and hold only 0 (dissimilar) and 1 (similar)")
        diff = a - b
        return diff, np.sqrt((diff**2).sum(axis=1) + self.config.eps), label

    def forward(self, a: np.ndarray, b: np.ndarray, label: np.ndarray):
        """a, b: (N, D) embeddings of the two sides of each pair. label: (N,), 1 = similar, 0 = dissimilar.
        Returns a float, or (N,) for "none"."""
        _, dist, label = self._prepare(a, b, label)
        gap = np.maximum(0.0, self.config.margin - dist)
        return _reduce(0.5 * label * dist**2 + 0.5 * (1.0 - label) * gap**2, self.config.reduction)

    def backward(self, a: np.ndarray, b: np.ndarray, label: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Gradients of the reduced loss with respect to a and b, each (N, D).

        Similar pair: (a - b). Dissimilar pair inside the margin: -(margin - d) * (a - b) / d. The gradient
        for b is the negative of the one for a. For "none" the per-row gradients are returned unscaled.
        """
        diff, dist, label = self._prepare(a, b, label)
        gap = np.maximum(0.0, self.config.margin - dist)
        coeff = label - (1.0 - label) * gap / dist  # multiplies (a - b) in both cases
        g_a = coeff[:, None] * diff
        if self.config.reduction == "mean":
            g_a = g_a / len(label)
        return g_a, -g_a

    __call__ = forward
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
6, run with python3 -m unittest -v

Practice

Build ContrastiveLoss(ContrastiveLossConfig(margin=1.0, reduction="none")). Make three pairs in two dimensions at distances 0.2, 0.6 and 1.3, label them all dissimilar, and inspect forward and backward. Then relabel them similar and compare which pairs receive a gradient.

Check on learning

  1. Why is the dissimilar term cut off at the margin instead of rewarding ever larger distances?
    A way to think about it

    Think about what an unbounded reward would do: the model could lower the loss forever by inflating all distances. A cut-off turns the goal into far enough.

  2. Suppose the training set contains only similar pairs. What embedding minimises the loss, and is it useful?
    A way to think about it

    Find the function that makes every distance zero. Then ask what it tells you about two inputs that are in fact different.

  3. After some training, 95 percent of dissimilar pairs give zero loss. Is training nearly done?
    A way to think about it

    Zero loss on random pairs says little about the hard ones. Consider how often a random pair is a near-duplicate that the model still confuses.

  4. How does contrastive loss differ from triplet loss in what it asks of the embedding space?
    A way to think about it

    One sets absolute targets: similar at distance zero, dissimilar beyond mm. The other only compares two distances from a shared anchor. Think about which is more tolerant of varied classes.