|
| 1 | +import unittest |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn |
| 5 | +import torch.nn.functional |
| 6 | +import torch.nn.functional as F |
| 7 | + |
| 8 | +from pytorch_metric_learning.losses import PNPLoss |
| 9 | + |
| 10 | +from .. import TEST_DEVICE, TEST_DTYPES |
| 11 | + |
| 12 | + |
| 13 | +class OriginalImplementationPNP(torch.nn.Module): |
| 14 | + def __init__(self, b, alpha, anneal, variant, bs, classes): |
| 15 | + super(OriginalImplementationPNP, self).__init__() |
| 16 | + self.b = b |
| 17 | + self.alpha = alpha |
| 18 | + self.anneal = anneal |
| 19 | + self.variant = variant |
| 20 | + self.batch_size = bs |
| 21 | + self.num_id = classes |
| 22 | + self.samples_per_class = int(bs / classes) |
| 23 | + |
| 24 | + mask = 1.0 - torch.eye(self.batch_size) |
| 25 | + for i in range(self.num_id): |
| 26 | + mask[ |
| 27 | + i * (self.samples_per_class) : (i + 1) * (self.samples_per_class), |
| 28 | + i * (self.samples_per_class) : (i + 1) * (self.samples_per_class), |
| 29 | + ] = 0 |
| 30 | + |
| 31 | + self.mask = mask.unsqueeze(dim=0).repeat(self.batch_size, 1, 1) |
| 32 | + |
| 33 | + def forward(self, batch): |
| 34 | + |
| 35 | + dtype, device = batch.dtype, batch.device |
| 36 | + self.mask = self.mask.type(dtype).to(device) |
| 37 | + # compute the relevance scores via cosine similarity of the CNN-produced embedding vectors |
| 38 | + |
| 39 | + sim_all = self.compute_aff(batch) |
| 40 | + |
| 41 | + sim_all_repeat = sim_all.unsqueeze(dim=1).repeat(1, self.batch_size, 1) |
| 42 | + # compute the difference matrix |
| 43 | + sim_diff = sim_all_repeat - sim_all_repeat.permute(0, 2, 1) |
| 44 | + # pass through the sigmoid and ignores the relevance score of the query to itself |
| 45 | + sim_sg = self.sigmoid(sim_diff, temp=self.anneal) * self.mask |
| 46 | + # compute the rankings,all batch |
| 47 | + sim_all_rk = torch.sum(sim_sg, dim=-1) |
| 48 | + if self.variant == "PNP-D_s": |
| 49 | + sim_all_rk = torch.log(1 + sim_all_rk) |
| 50 | + elif self.variant == "PNP-D_q": |
| 51 | + sim_all_rk = 1 / (1 + sim_all_rk) ** (self.alpha) |
| 52 | + |
| 53 | + elif self.variant == "PNP-I_u": |
| 54 | + sim_all_rk = (1 + sim_all_rk) * torch.log(1 + sim_all_rk) |
| 55 | + |
| 56 | + elif self.variant == "PNP-I_b": |
| 57 | + b = self.b |
| 58 | + sim_all_rk = 1 / b**2 * (b * sim_all_rk - torch.log(1 + b * sim_all_rk)) |
| 59 | + elif self.variant == "PNP-O": |
| 60 | + pass |
| 61 | + else: |
| 62 | + raise Exception("variantation <{}> not available!".format(self.variant)) |
| 63 | + |
| 64 | + # sum the values of the Smooth-AP for all instances in the mini-batch |
| 65 | + loss = torch.zeros(1).type(dtype).to(device) |
| 66 | + group = int(self.batch_size / self.num_id) |
| 67 | + |
| 68 | + for ind in range(self.num_id): |
| 69 | + neg_divide = torch.sum( |
| 70 | + sim_all_rk[ |
| 71 | + (ind * group) : ((ind + 1) * group), |
| 72 | + (ind * group) : ((ind + 1) * group), |
| 73 | + ] |
| 74 | + / group |
| 75 | + ) |
| 76 | + loss = loss + (neg_divide / self.batch_size) |
| 77 | + if self.variant == "PNP-D_q": |
| 78 | + return 1 - loss |
| 79 | + else: |
| 80 | + return loss |
| 81 | + |
| 82 | + def sigmoid(self, tensor, temp=1.0): |
| 83 | + """temperature controlled sigmoid |
| 84 | + takes as input a torch tensor (tensor) and passes it through a sigmoid, controlled by temperature: temp |
| 85 | + """ |
| 86 | + exponent = -tensor / temp |
| 87 | + # clamp the input tensor for stability |
| 88 | + exponent = torch.clamp(exponent, min=-50, max=50) |
| 89 | + y = 1.0 / (1.0 + torch.exp(exponent)) |
| 90 | + return y |
| 91 | + |
| 92 | + def compute_aff(self, x): |
| 93 | + """computes the affinity matrix between an input vector and itself""" |
| 94 | + return torch.mm(x, x.t()) |
| 95 | + |
| 96 | + |
| 97 | +class TestPNPLoss(unittest.TestCase): |
| 98 | + def test_pnp_loss(self): |
| 99 | + torch.manual_seed(30293) |
| 100 | + bs = 180 |
| 101 | + classes = 30 |
| 102 | + for variant in PNPLoss.VARIANTS: |
| 103 | + original_variant = { |
| 104 | + "Ds": "PNP-D_s", |
| 105 | + "Dq": "PNP-D_q", |
| 106 | + "Iu": "PNP-I_u", |
| 107 | + "Ib": "PNP-I_b", |
| 108 | + "O": "PNP-O", |
| 109 | + }[variant] |
| 110 | + b, alpha, anneal = 2, 4, 0.01 |
| 111 | + loss_func = PNPLoss(b, alpha, anneal, variant) |
| 112 | + original_loss_func = OriginalImplementationPNP( |
| 113 | + b, alpha, anneal, original_variant, bs, classes |
| 114 | + ).to(TEST_DEVICE) |
| 115 | + |
| 116 | + for dtype in TEST_DTYPES: |
| 117 | + embeddings = torch.randn( |
| 118 | + 180, 32, dtype=dtype, device=TEST_DEVICE, requires_grad=True |
| 119 | + ) |
| 120 | + labels = ( |
| 121 | + torch.tensor([[i] * (int(bs / classes)) for i in range(classes)]) |
| 122 | + .reshape(-1) |
| 123 | + .to(TEST_DEVICE) |
| 124 | + ) |
| 125 | + loss = loss_func(embeddings, labels) |
| 126 | + loss.backward() |
| 127 | + correct_loss = original_loss_func(F.normalize(embeddings, dim=-1)) |
| 128 | + |
| 129 | + rtol = 1e-2 if dtype == torch.float16 else 1e-5 |
| 130 | + self.assertTrue(torch.isclose(loss, correct_loss[0], rtol=rtol)) |
| 131 | + |
| 132 | + with self.assertRaises(ValueError): |
| 133 | + PNPLoss(b, alpha, anneal, "PNP") |
0 commit comments