fn
triplet_margin_with_distance_loss
→Tensortriplet_margin_with_distance_loss(anchor: Tensor, positive: Tensor, negative: Tensor, distance_function: object | None = None, margin: float = 1.0, swap: bool = False, reduction: str = 'mean')Triplet margin loss with a user-supplied distance function.
Identical in form to triplet_margin_loss but lets the
caller plug in any binary distance callable — useful when the
embedding space is non-Euclidean (e.g., learned Mahalanobis
distances, cosine distance, or hyperbolic embeddings). When
no distance_function is supplied it defaults to the
pairwise distance, matching the reference framework
semantics.
Parameters
anchorTensorAnchor embedding of shape .
positiveTensorPositive sample embedding of the same shape.
negativeTensorNegative sample embedding of the same shape.
distance_functioncallable or None= NoneFunction
(x, y) -> Tensor returning a non-negative
distance of shape . Defaults to
pairwise distance.marginfloat= 1.0Minimum desired margin between positive and negative
distances (default
1.0).swapbool= FalseEnable the Balntas-2016 anchor-swap heuristic: replace
with
so the harder negative drives the gradient (default
False).reductionstr= 'mean'"mean" (default), "sum", or "none".Returns
TensorScalar or per-triplet tensor.
Notes
Per-triplet loss:
The Lucid module wrapper
lucid.nn.TripletMarginWithDistanceLoss forwards into
this function; both surfaces are valid entry-points.
Examples
>>> import lucid
>>> from lucid.nn.functional import (
... triplet_margin_with_distance_loss,
... pairwise_distance,
... )
>>> def manhattan(a, b):
... return pairwise_distance(a, b, p=1.0)
>>> a = lucid.tensor([[1.0, 0.0]])
>>> p = lucid.tensor([[1.0, 0.1]])
>>> n = lucid.tensor([[0.0, 1.0]])
>>> triplet_margin_with_distance_loss(a, p, n, distance_function=manhattan)
Tensor(0.2)