Upload ProDiff/Experiments/trajectory_exp_may_data_TKY_len3_ddpm_20250724-100624/code_snapshot/loss.py with huggingface_hub
Browse files
ProDiff/Experiments/trajectory_exp_may_data_TKY_len3_ddpm_20250724-100624/code_snapshot/loss.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class ContrastiveLoss(nn.Module):
|
| 7 |
+
"""Contrastive loss function.
|
| 8 |
+
|
| 9 |
+
Encourages 'anchor' to be close to 'positive' samples and far from 'negative' samples.
|
| 10 |
+
"""
|
| 11 |
+
def __init__(self, margin=1.0):
|
| 12 |
+
"""Initializes ContrastiveLoss.
|
| 13 |
+
|
| 14 |
+
Args:
|
| 15 |
+
margin (float, optional): The margin for the loss. Defaults to 1.0.
|
| 16 |
+
"""
|
| 17 |
+
super(ContrastiveLoss, self).__init__()
|
| 18 |
+
self.margin = margin
|
| 19 |
+
|
| 20 |
+
def forward(self, anchor, positive, negative):
|
| 21 |
+
"""Computes the contrastive loss.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
anchor (torch.Tensor): Embeddings of the anchor samples.
|
| 25 |
+
positive (torch.Tensor): Embeddings of the positive samples.
|
| 26 |
+
negative (torch.Tensor): Embeddings of the negative samples.
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
torch.Tensor: The mean contrastive loss.
|
| 30 |
+
"""
|
| 31 |
+
pos_dist = F.pairwise_distance(anchor, positive)
|
| 32 |
+
neg_dist = F.pairwise_distance(anchor, negative)
|
| 33 |
+
# Loss = max(0, pos_dist - neg_dist + margin)
|
| 34 |
+
loss = torch.mean(F.relu(pos_dist - neg_dist + self.margin))
|
| 35 |
+
return loss
|