quaterion.loss.triplet_loss module

class TripletLoss(margin: float | None = 0.5, distance_metric_name: Distance | None = Distance.COSINE, mining: str | None = 'hard', soft: bool | None = False)[source]

Bases: GroupLoss

Implements Triplet Loss as defined in

It supports batch-all, batch-hard and batch-semihard strategies for online triplet mining.

  • margin – Margin value to push negative examples apart.

  • distance_metric_name – Name of the distance function, e.g., Distance.

  • mining – Triplet mining strategy. One of “all”, “hard”, “semi_hard”.

  • soft – If True, use soft margin variant of Hard Triplet Loss. Ignored in all other cases.

forward(embeddings: Tensor, groups: LongTensor) Tensor[source]

Calculates Triplet Loss with specified embeddings and labels.

  • embeddings – shape: (batch_size, vector_length) - Batch of embeddings.

  • groups – shape: (batch_size,) - Batch of labels associated with embeddings


torch.Tensor – Scalar loss value.


Config used in saving and loading purposes.

Config object has to be JSON-serializable.


Dict[str, Any] – JSON-serializable dict of params

xbm_loss(embeddings: Tensor, groups: LongTensor, memory_embeddings: Tensor, memory_groups: LongTensor) Tensor[source]

Implement XBM loss computation for this loss.

  • embeddings – shape: (batch_size, vector_length) - Output embeddings from the encoder.

  • groups – shape: (batch_size,) - Group ids associated with embeddings.

  • memory_embeddings – shape: (memory_buffer_size, vector_length) - Embeddings stored in a ring buffer

  • memory_groups – shape: (memory_buffer_size,) - Groups ids associated with memory_embeddings


Tensor – zero-size tensor, XBM loss value.

training: bool


Learn more about Qdrant vector search project and ecosystem

Discover Qdrant

Similarity Learning

Explore practical problem solving with Similarity Learning

Learn Similarity Learning


Find people dealing with similar problems and get answers to your questions

Join Community