TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Contrastive and Triplet Losses

Contrastive and Triplet Losses

Face unlock, "more like this" product search, duplicate-question detection and speaker verification share a problem that ordinary classification cannot solve: the classes at test time are people, products or questions the model has never seen. Instead of predicting a label, the model learns an embedding f(x)∈Rdf(\mathbf{x}) \in \mathbb{R}^d, a vector in which similar items are close and different ones are far apart. A new face is then recognised by its nearest stored embedding. The losses that shape such a space compare examples with each other instead of with a label: the contrastive loss works on pairs, the triplet loss on triples. This lesson implements both with their gradients and trains a small linear embedding with triplets.

Contrastive loss: pairs

Take pairs (x1,x2)(\mathbf{x}_1, \mathbf{x}_2) with a label s=1s = 1 for "same" and s=0s = 0 for "different", and let d=∥f(x1)−f(x2)∥d = \lVert f(\mathbf{x}_1) - f(\mathbf{x}_2) \rVert be the distance between their embeddings. The contrastive loss (Hadsell, Chopra and LeCun, 2006) is

ℓ=12[s d2+(1−s)max⁡(0,m−d)2]\ell = \frac{1}{2} \Big[ s \, d^2 + (1 - s) \max(0, m - d)^2 \Big]

Similar pairs are pulled together (their loss is d2d^2, zero only at d=0d = 0); dissimilar pairs are pushed apart, but only until they are at least the margin mm apart. Without the margin, the easiest way to lower the loss would be to push everything infinitely far away. The gradient with respect to the first embedding e1\mathbf{e}_1 is

∂ℓ∂e1=s (e1−e2)−(1−s)max⁡(0,m−d)e1−e2d\frac{\partial \ell}{\partial \mathbf{e}_1} = s \, (\mathbf{e}_1 - \mathbf{e}_2) - (1 - s) \max(0, m - d) \frac{\mathbf{e}_1 - \mathbf{e}_2}{d}

and the gradient for e2\mathbf{e}_2 is its negative.

python · try it yourself
import numpy as np

def contrastive(e1, e2, same, margin=1.0):
    d = np.linalg.norm(e1 - e2, axis=1)
    loss = same * d ** 2 + (1 - same) * np.maximum(0, margin - d) ** 2
    return 0.5 * np.mean(loss), d

def contrastive_grad_e1(e1, e2, same, margin=1.0):     # d loss / d e1 (e2 gets the opposite sign)
    diff = e1 - e2
    d = np.linalg.norm(diff, axis=1, keepdims=True)
    pull = same[:, None] * diff
    push = (1 - same)[:, None] * -np.maximum(0, margin - d) * diff / d
    return (pull + push) / len(same)

e1 = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [2.0, 0.0]])
e2 = np.array([[0.3, 0.4], [1.0, 1.2], [0.0, 1.6], [0.0, 0.0]])
same = np.array([1.0, 0.0, 0.0, 0.0])                  # pair 0 similar, pairs 1-3 dissimilar
loss, d = contrastive(e1, e2, same)
print("distances", np.round(d, 3), " loss", round(loss, 4))
print("pair 3 is already farther than the margin, so it adds nothing")

h, num = 1e-6, np.zeros_like(e1)
for i in range(4):
    for k in range(2):
        E = np.zeros_like(e1); E[i, k] = h
        num[i, k] = (contrastive(e1 + E, e2, same)[0] - contrastive(e1 - E, e2, same)[0]) / (2 * h)
print("gradient matches numeric:", np.allclose(contrastive_grad_e1(e1, e2, same), num, atol=1e-8))
print("gradient on e1:\n", np.round(contrastive_grad_e1(e1, e2, same), 4))
distances [0.5 0.2 0.6 2. ]  loss 0.1312
pair 3 is already farther than the margin, so it adds nothing
gradient matches numeric: True
gradient on e1:
 [[-0.075 -0.1  ]
 [ 0.     0.2  ]
 [ 0.     0.1  ]
 [ 0.     0.   ]]

The similar pair at distance 0.5 costs 0.52=0.250.5^2 = 0.25; the dissimilar pairs at 0.2 and 0.6 cost (1−0.2)2=0.64(1 - 0.2)^2 = 0.64 and (1−0.6)2=0.16(1 - 0.6)^2 = 0.16; the pair at distance 2 is already beyond the margin and costs nothing, so its gradient is zero. The total is 12⋅0.25+0.64+0.16+04=0.13125\frac{1}{2} \cdot \frac{0.25 + 0.64 + 0.16 + 0}{4} = 0.13125, printed rounded to 0.1312. The gradient rows point the way: the first pair's e1\mathbf{e}_1 moves towards e2\mathbf{e}_2 (gradient descent subtracts it), the second and third move away.

Triplet loss: an anchor, a positive, a negative

The triplet loss (used by FaceNet, Schroff et al., 2015) compares two distances at once. For an anchor aa, a positive pp of the same identity and a negative nn of another identity,

ℓ(a,p,n)=max⁡(0,  d(a,p)−d(a,n)+m)\ell(a, p, n) = \max\big(0, \; d(a, p) - d(a, n) + m\big)

It does not care about absolute distances, only that every negative is at least mm farther from the anchor than every positive. That is exactly what nearest-neighbour retrieval needs. (FaceNet uses squared distances and L2-normalised embeddings; both variants are common.)

Easy, semi-hard and hard negatives

Most random triplets are already satisfied and contribute nothing. Which triplets you train on, mining, matters more than the details of the loss:

python · try it yourself
import numpy as np

margin = 0.5
anchor   = np.array([0.0, 0.0])
positive = np.array([1.0, 0.0])                 # same identity, distance 1.0
negatives = {"n1": np.array([0.0, 2.0]),        # far away
             "n2": np.array([-1.2, 0.0]),       # a bit farther than the positive
             "n3": np.array([0.6, 0.3])}        # closer than the positive

d_ap = np.linalg.norm(anchor - positive)
for name, neg in negatives.items():
    d_an = np.linalg.norm(anchor - neg)
    loss = max(0.0, d_ap - d_an + margin)
    if d_an > d_ap + margin:  kind = "easy (loss 0, no gradient)"
    elif d_an > d_ap:         kind = "semi-hard (right order, inside the margin)"
    else:                     kind = "hard (negative closer than the positive)"
    print(f"{name}: d(a,n) {d_an:.3f}  loss {loss:.3f}  {kind}")

hardest = min(negatives, key=lambda k: np.linalg.norm(anchor - negatives[k]))
print("batch-hard mining picks", hardest)
n1: d(a,n) 2.000  loss 0.000  easy (loss 0, no gradient)
n2: d(a,n) 1.200  loss 0.300  semi-hard (right order, inside the margin)
n3: d(a,n) 0.671  loss 0.829  hard (negative closer than the positive)
batch-hard mining picks n3
  • Easy negatives (d(a,n)>d(a,p)+md(a, n) > d(a, p) + m) have zero loss and zero gradient: wasted computation.
  • Semi-hard negatives are farther than the positive but inside the margin; FaceNet trained on these.
  • Hard negatives are closer than the positive. They carry the most signal but also include mislabelled pairs and outliers, and training only on the hardest ones (batch-hard mining: for each anchor, the farthest positive and the closest negative in the batch) can collapse all embeddings to one point early in training. A common recipe: start with semi-hard or random triplets, move to harder ones later.

Training a linear embedding with triplets

Three classes live in 6 dimensions; only the first two dimensions carry the class, the other four are loud noise (σ=3\sigma = 3 against a class spread of 0.6). A random linear map WW to 2-D mixes noise and signal. Training WW with the squared-distance triplet loss on mini-batches of random triplets should teach it to look only at the signal dimensions. The gradient of ∥W(a−p)∥2\lVert W(\mathbf{a} - \mathbf{p}) \rVert^2 with respect to WW is 2W(a−p)(a−p)⊤2W(\mathbf{a} - \mathbf{p})(\mathbf{a} - \mathbf{p})^\top.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
# 3 classes in 6-D: dims 0-1 carry the class, dims 2-5 are loud noise
centres = np.array([[0, 0], [3, 0], [0, 3]], dtype=float)
def make(n):
    lab = rng.integers(0, 3, n)
    X = np.column_stack([centres[lab] + rng.normal(0, 0.6, (n, 2)), rng.normal(0, 3, (n, 4))])
    return X, lab
X_tr, y_tr = make(150)
X_te, y_te = make(300)

def sample_triplets(lab, k):
    a = rng.integers(0, len(lab), k)
    p = np.array([rng.choice(np.flatnonzero((lab == lab[i]) & (np.arange(len(lab)) != i))) for i in a])
    n = np.array([rng.choice(np.flatnonzero(lab != lab[i])) for i in a])
    return a, p, n

def triplet_loss(W, a, p, n, margin=1.0):
    dap = ((X_tr[a] - X_tr[p]) @ W.T) ** 2
    dan = ((X_tr[a] - X_tr[n]) @ W.T) ** 2
    return np.maximum(0, dap.sum(1) - dan.sum(1) + margin)

def nn_accuracy(W):                                 # 1-nearest-neighbour accuracy in embedding space
    Etr, Ete = X_tr @ W.T, X_te @ W.T
    s = (Ete ** 2).sum(1)[:, None] + (Etr ** 2).sum(1)[None, :] - 2 * Ete @ Etr.T
    return np.mean(y_tr[s.argmin(1)] == y_te)

W = rng.normal(0, 1, (2, 6))                        # embedding: 6-D input -> 2-D
W /= np.linalg.norm(W)                              # keep ||W|| = 1, else the loss can shrink by scaling
a, p, n = sample_triplets(y_tr, 2000)
print(f"before: triplet loss {triplet_loss(W, a, p, n).mean():.3f}  1-NN test accuracy {nn_accuracy(W):.3f}")
lr = 0.02
for step in range(200):
    a, p, n = sample_triplets(y_tr, 64)             # a fresh mini-batch of random triplets
    act = triplet_loss(W, a, p, n) > 0              # only violating triplets have a gradient
    dp, dn = X_tr[a[act]] - X_tr[p[act]], X_tr[a[act]] - X_tr[n[act]]
    G = 2 * W @ (dp.T @ dp - dn.T @ dn) / len(a)    # d/dW of ||W(a-p)||^2 - ||W(a-n)||^2
    W -= lr * G
    W /= np.linalg.norm(W)                          # project back onto ||W|| = 1
a, p, n = sample_triplets(y_tr, 2000)
print(f"after:  triplet loss {triplet_loss(W, a, p, n).mean():.3f}  1-NN test accuracy {nn_accuracy(W):.3f}")
print("mean |weight| on the 2 signal dims:", round(np.abs(W[:, :2]).mean(), 3),
      " on the 4 noise dims:", round(np.abs(W[:, 2:]).mean(), 3))
before: triplet loss 8.247  1-NN test accuracy 0.407
after:  triplet loss 0.071  1-NN test accuracy 0.983
mean |weight| on the 2 signal dims: 0.384  on the 4 noise dims: 0.017

After 200 steps the triplet loss falls from 8.247 to 0.071 and the 1-nearest-neighbour accuracy on 300 new points rises from 0.407 (barely above chance for three classes) to 0.983. The learned map puts almost all its weight on the two signal dimensions (mean absolute weight 0.384 against 0.017). The constraint ∥W∥=1\lVert W \rVert = 1 is a safeguard. With squared distances, scaling WW by cc multiplies d(a,n)2−d(a,p)2d(a, n)^2 - d(a, p)^2 by c2c^2, so every triplet that is already in the right order can be pushed past the fixed margin just by blowing up the embedding, without learning anything. With random triplets the hinge stops pushing once most triplets are satisfied, and the run happens to converge even without the constraint; with batch-hard mining, which always finds violators, an unconstrained WW grew without bound when we tried it. Deep networks get the same protection by L2-normalising each embedding.

When to use which

Loss Needs Good for
contrastive (pairs) "same/different" pairs verification (is this the same person?), duplicate detection
triplet identities, to build (a,p,n)(a, p, n) retrieval and re-identification, where the ranking of neighbours matters
InfoNCE / NT-Xent (one positive against many negatives with a softmax) many negatives per batch self-supervised pretraining (SimCLR, CLIP), modern retrieval

InfoNCE treats the problem as a classification of the positive among KK candidates with cross-entropy over similarity scores; it is the most common choice today. The embeddings these losses learn are evaluated with retrieval metrics (recall at kk, mean average precision), not with accuracy.

Pitfalls

  • No margin, or no normalisation. The embedding either collapses (everything at one point) or explodes. Check the spread of embeddings during training.
  • Leaking identities. Split train and test by identity (group splits), or the test measures memorised faces, not generalisation to new people.
  • Hardest negatives from the start. Label noise makes the hardest negatives unreliable; mine gradually.

Practice

  1. Anchor-positive distance 1.0, anchor-negative distance 1.3, margin 0.5. What is the triplet loss, and what kind of negative is it?
Answer

max⁡(0,1.0−1.3+0.5)=0.2\max(0, 1.0 - 1.3 + 0.5) = 0.2. The negative is farther than the positive but inside the margin: semi-hard.

  1. Why does the contrastive loss need a margin for dissimilar pairs but not a "minimum distance" for similar pairs?
Answer

Similar pairs have a natural optimum, distance 0. Pushing dissimilar pairs apart has no natural end: without a margin the loss keeps rewarding larger distances, and the embedding grows without bound. The margin says "far enough".

Test yourself

In the contrastive loss, a dissimilar pair at distance d=2d = 2 with margin m=1m = 1 contributes…

  1. 12⋅4\frac{1}{2} \cdot 4
  2. 12⋅1\frac{1}{2} \cdot 1
  3. 0
  4. a negative loss

The triplet loss is zero when…

  1. d(a,p)=0d(a, p) = 0
  2. d(a,n)≥d(a,p)+md(a, n) \ge d(a, p) + m
  3. d(a,n)=d(a,p)d(a, n) = d(a, p)
  4. d(a,p)≥md(a, p) \ge m

Why did the lesson keep ∥W∥=1\lVert W \rVert = 1 while training with squared distances?

  1. To make training faster
  2. Otherwise scaling WW up can lower the loss without learning anything useful
  3. Because the margin is 1
  4. To avoid overfitting to the test set

Face images for an embedding model must be split into training and test sets…

  1. randomly by image
  2. by identity, so test people never appear in training
  3. by image size
  4. by time of day