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
- Take two batches of embeddings and , and a label for each pair: 1 for similar, 0 for dissimilar.
- Compute the Euclidean distance between the two embeddings of each pair. A small
epsunder the square root keeps the gradient defined at distance zero. - For a similar pair the loss is .
- For a dissimilar pair the loss is , where is the margin.
- Reduce over the batch with
reduction. - In
backward, similar pairs get a pull along , dissimilar pairs inside the margin get a push, and the gradient for is the negative of the one for .
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
| If | Use instead |
|---|---|
| You can form anchor, positive and negative triples and care about relative distance | Triplet loss |
| You have large batches and want every other item in the batch to act as a negative | InfoNCE |
| Every example has a class label from a fixed set | Softmax cross-entropy |
Math foundations
Distance between the pair
The straight-line distance between the two embeddings. The whole loss is a function of this one number.
The loss for one pair
The label selects one term. Similar pairs pay for any distance. Dissimilar pairs pay only for being closer than the margin .
Gradient for a similar pair
A pull toward in proportion to the separation, like a spring. It shrinks to zero as the pair meets.
Gradient for a dissimilar pair
A push directly away from , strongest when the points nearly coincide and zero once the distance reaches . Beyond the margin the gradient is zero.
The two sides mirror each other
The loss depends only on , so whatever moves one way moves the other.
Symbols
- the two embeddings of a pair, each of dimension D
- the Euclidean distance between them
- the pair label: 1 for similar, 0 for dissimilar
- the margin,
marginin the config, default 1 - the loss for one pair
- the embedding dimension
Worked by hand
A pair at distance with margin . Compute the loss if the pair is similar, then if it is dissimilar.
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 apartRead 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
- 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.
- 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.
- 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.
- 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 . The other only compares two distances from a shared anchor. Think about which is more tolerant of varied classes.