Sign in

Triplet

Triplet margin loss

A loss on triples of embeddings: it asks that an anchor be closer to a positive example than to a negative example by at least a margin.

Overview

Triplet loss trains an embedding space by comparison. Each training item is a triple: an anchor, a positive that should be near it, and a negative that should be far. The loss looks at two distances from the anchor and asks only that the negative be farther than the positive by some margin. If that already holds, the triple costs nothing. If not, the loss is the amount by which it fails. No absolute distance is demanded, only the right ordering with a gap, which lets classes with different spreads coexist.

A short history

Kilian Weinberger and Lawrence Saul used a triplet constraint in their large margin nearest neighbour method in the mid 2000s. The loss became widely known through FaceNet, published in 2015 by Florian Schroff, Dmitry Kalenichenko and James Philbin at Google, which learned face embeddings where distance reflects identity. Their work also showed that the way triplets are selected matters as much as the loss.

How it works

  1. Take three batches of embeddings of shape (N, D): anchors, positives and negatives.
  2. Compute the anchor to positive distance and the anchor to negative distance for each row, Euclidean or squared according to squared. distances returns both.
  3. Compute the violation: positive distance minus negative distance plus the margin.
  4. The loss for the row is the violation if it is positive, otherwise zero.
  5. Reduce over the batch with reduction.
  6. In backward, rows that violate the margin pull the positive toward the anchor and push the negative away. Rows that satisfy it get zero gradient.

Watch out for

  • Most random triples already satisfy the margin and give no gradient. Progress depends on mining triples that still violate it.
  • Training only on the very hardest negatives can collapse every embedding to one point, where all distances are zero and the loss sits at the margin.
  • The margin is in the units of the embedding. Without normalising the embeddings, the model can meet it by scaling everything up.
  • The number of possible triples grows with the cube of the dataset size. The template scores the triples you supply. Choosing them is your job.

Use cases

When to use it

Metric learning for face recognition, person re-identification and image or text retrieval, where you can say which of two items is more similar to a third but not how similar in absolute terms.

In industry

Face recognition
FaceNet trained embeddings with triplets of two photos of one person and one photo of another, so identity can be checked by distance.
Person re-identification
Systems that match a person across different cameras train with triplet loss and hard example mining within each batch.
Visual product search
Shopping services learn embeddings in which a customer's photo of an item lies closer to the matching catalogue image than to other products.

Choosing it: what must hold

  • Labels or signals that let you form an anchor, a positive of the same identity and a negative of a different one.
  • A mining strategy that finds hard or semi-hard negatives, since most random triplets already satisfy the margin.
  • Batches built to contain several examples per identity.

When to choose something else

IfUse instead
You only have pairs labelled similar or dissimilarContrastive loss
You have large batches and want to use every other item as a negativeInfoNCE
Identities form a fixed set known in advanceSoftmax cross-entropy over identities

Math foundations

  1. The two distances

    dap=∥a−p∥2,dan=∥a−n∥2d_{ap} = \lVert a - p \rVert_2, \qquad d_{an} = \lVert a - n \rVert_2

    How far the anchor is from the positive and from the negative. With squared on, the squared distances are used in their place.

  2. The loss

    ℓ=max⁡ ⁣(0,  dap−dan+m)\ell = \max\!\big(0,\; d_{ap} - d_{an} + m\big)

    Zero when the negative is at least mm farther from the anchor than the positive. Otherwise it is the shortfall.

  3. Which triples contribute

    ℓ>0  ⟺  dan<dap+m\ell > 0 \iff d_{an} < d_{ap} + m

    A triple is easy when the negative is beyond dap+md_{ap} + m and gives zero loss. It is semi-hard when dap<dan<dap+md_{ap} < d_{an} < d_{ap} + m, and hard when the negative is closer than the positive.

  4. Gradients for an active triple

    ∂ℓ∂p=−a−pdap,∂ℓ∂n=a−ndan,∂ℓ∂a=a−pdap−a−ndan\frac{\partial \ell}{\partial p} = -\frac{a - p}{d_{ap}}, \qquad \frac{\partial \ell}{\partial n} = \frac{a - n}{d_{an}}, \qquad \frac{\partial \ell}{\partial a} = \frac{a - p}{d_{ap}} - \frac{a - n}{d_{an}}

    For Euclidean distances these are unit vectors. Following the negative gradient, the positive moves toward the anchor, the negative moves away, and the anchor does both.

  5. With squared distances

    ℓsq=max⁡ ⁣(0,  ∥a−p∥22−∥a−n∥22+m),∂ℓsq∂a=2 (n−p)\ell_{\text{sq}} = \max\!\big(0,\; \lVert a - p \rVert_2^{2} - \lVert a - n \rVert_2^{2} + m\big), \qquad \frac{\partial \ell_{\text{sq}}}{\partial a} = 2\,(n - p)

    The form used in FaceNet. The gradients are no longer unit vectors: they grow with the separation, and the anchor's gradient depends only on where the positive and negative are.

Symbols

a,p,na, p, n
the anchor, positive and negative embeddings
dapd_{ap}
distance from the anchor to the positive
dand_{an}
distance from the anchor to the negative
mm
the margin, margin in the config, default 1
ℓ\ell
the loss for one triple
ℓsq\ell_{\text{sq}}
the loss for one triple with squared distances

Worked by hand

Margin m=1m = 1 and a positive at distance dap=0.8d_{ap} = 0.8. Try three negatives, at distances 2.0, 1.2 and 0.5.

dan=2.0:max⁡(0,  0.8−2.0+1)=max⁡(0,−0.2)=0d_{an} = 2.0: \quad \max(0,\; 0.8 - 2.0 + 1) = \max(0, -0.2) = 0
dan=1.2:max⁡(0,  0.8−1.2+1)=0.6d_{an} = 1.2: \quad \max(0,\; 0.8 - 1.2 + 1) = 0.6
dan=0.5:max⁡(0,  0.8−0.5+1)=1.3d_{an} = 0.5: \quad \max(0,\; 0.8 - 0.5 + 1) = 1.3

The first negative is easy and contributes nothing. The second is semi-hard and costs 0.6. The third is hard, closer than the positive, and costs 1.3.

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 TripletLoss
from config import TripletLossConfig

loss = TripletLoss(TripletLossConfig(margin=1.0))
anchor = np.array([[0.0, 0.0]])
positive = np.array([[0.6, 0.8]])           # distance 1.0 from the anchor
negative = np.array([[0.0, 1.5]])           # distance 1.5 from the anchor
print(loss.forward(anchor, positive, negative))             # max(0, 1.0 - 1.5 + 1.0) = 0.5
g_anchor, g_positive, g_negative = loss.backward(anchor, positive, negative)
Read the implementation (64 lines)
"""Triplet margin loss: max(0, d(anchor, positive) - d(anchor, negative) + margin).

NumPy only. `forward` returns the loss, `backward` its gradients with respect to the anchor, the positive and the
negative.
"""
from __future__ import annotations

import numpy as np

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

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 TripletLoss:
    """Asks the negative to be at least `margin` farther from the anchor than the positive."""

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

    def distances(self, anchor: np.ndarray, positive: np.ndarray, negative: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """Anchor-positive and anchor-negative distances, each (N,). Squared when the config says so."""
        anchor, positive, negative = _embeddings(anchor, positive, negative)
        sq_ap, sq_an = ((anchor - positive) ** 2).sum(axis=1), ((anchor - negative) ** 2).sum(axis=1)
        if self.config.squared:
            return sq_ap, sq_an
        return np.sqrt(sq_ap + self.config.eps), np.sqrt(sq_an + self.config.eps)

    def forward(self, anchor: np.ndarray, positive: np.ndarray, negative: np.ndarray):
        """anchor, positive, negative: (N, D) embeddings. Returns a float, or (N,) for "none"."""
        d_ap, d_an = self.distances(anchor, positive, negative)
        return _reduce(np.maximum(0.0, d_ap - d_an + self.config.margin), self.config.reduction)

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

        Rows that already satisfy the margin get zero gradient. For "none" the per-row gradients are returned
        unscaled.
        """
        anchor, positive, negative = _embeddings(anchor, positive, negative)
        d_ap, d_an = self.distances(anchor, positive, negative)
        active = ((d_ap - d_an + self.config.margin) > 0).astype(float)[:, None]
        if self.config.squared:
            unit_ap, unit_an = 2.0 * (anchor - positive), 2.0 * (anchor - negative)
        else:  # derivative of a distance is the unit vector along the difference
            unit_ap, unit_an = (anchor - positive) / d_ap[:, None], (anchor - negative) / d_an[:, None]
        scale = active / len(d_ap) if self.config.reduction == "mean" else active
        return scale * (unit_ap - unit_an), scale * -unit_ap, scale * unit_an

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

Practice

Build TripletLoss(TripletLossConfig(margin=1.0, reduction="none")). Place an anchor at the origin and a positive at (0.8, 0), and try negatives at (2, 0), (1.2, 0) and (0.5, 0). Check distances, forward and the three arrays from backward against the worked example. Then set all three points equal and read the loss.

Check on learning

  1. After a few epochs, 99 percent of randomly drawn triples have zero loss. Is the embedding nearly perfect?
    A way to think about it

    Random negatives are mostly unrelated items that are easy to separate. Ask how the model does on the rare look-alike negatives that retrieval quality depends on.

  2. If every embedding collapses to the same point, what is the loss, and why might hardest-negative mining lead there?
    A way to think about it

    With all distances zero the loss equals the margin for every triple. Look at the gradient on the anchor when the negative is much closer than the positive, and where it moves things.

  3. Triplet loss constrains only the difference of two distances. Contrastive loss constrains each distance on its own. What freedom does that give triplet loss?
    A way to think about it

    A class with naturally varied members can stay spread out, provided others stay farther still. Consider what forcing every same-class pair to distance zero would do.

  4. Why are embeddings usually normalised to unit length before this loss is applied?
    A way to think about it

    On the unit sphere distances are bounded, so the margin has a fixed meaning. Otherwise doubling all embeddings doubles every distance gap and satisfies the margin without learning.

  5. With squared on, the anchor's gradient is 2(n−p)2(n - p) and does not involve the anchor's own position. What does that imply about how the anchor moves?
    A way to think about it

    Gradient descent moves the anchor in the direction p−np - n, away from the negative and toward the positive side, and that direction is the same wherever the anchor sits.