|
| 1 | +import unittest |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn.functional as F |
| 5 | + |
| 6 | +from pytorch_metric_learning.losses import SmoothAPLoss |
| 7 | + |
| 8 | +from .. import TEST_DEVICE, TEST_DTYPES |
| 9 | + |
| 10 | +HYPERPARAMETERS = { |
| 11 | + "temp": 0.01, |
| 12 | + "batch_size": 60, |
| 13 | + "num_id": 6, |
| 14 | + "feat_dims": 256, |
| 15 | +} |
| 16 | +TEST_SEEDS = [42, 1234, 5642, 9999, 3459] |
| 17 | + |
| 18 | + |
| 19 | +# Original implementation of the SmoothAP loss taken from: |
| 20 | +# https://github.com/Andrew-Brown1/Smooth_AP/blob/master/src/Smooth_AP_loss.py |
| 21 | +def sigmoid(tensor, temp=1.0): |
| 22 | + """temperature controlled sigmoid |
| 23 | +
|
| 24 | + takes as input a torch tensor (tensor) and passes it through a sigmoid, controlled by temperature: temp |
| 25 | + """ |
| 26 | + exponent = -tensor / temp |
| 27 | + # clamp the input tensor for stability |
| 28 | + exponent = torch.clamp(exponent, min=-50, max=50) |
| 29 | + y = 1.0 / (1.0 + torch.exp(exponent)) |
| 30 | + return y |
| 31 | + |
| 32 | + |
| 33 | +def compute_aff(x): |
| 34 | + """computes the affinity matrix between an input vector and itself""" |
| 35 | + return torch.mm(x, x.t()) |
| 36 | + |
| 37 | + |
| 38 | +class SmoothAP(torch.nn.Module): |
| 39 | + """PyTorch implementation of the Smooth-AP loss. |
| 40 | +
|
| 41 | + implementation of the Smooth-AP loss. Takes as input the mini-batch of CNN-produced feature embeddings and returns |
| 42 | + the value of the Smooth-AP loss. The mini-batch must be formed of a defined number of classes. Each class must |
| 43 | + have the same number of instances represented in the mini-batch and must be ordered sequentially by class. |
| 44 | +
|
| 45 | + e.g. the labels for a mini-batch with batch size 9, and 3 represented classes (A,B,C) must look like: |
| 46 | +
|
| 47 | + labels = ( A, A, A, B, B, B, C, C, C) |
| 48 | +
|
| 49 | + (the order of the classes however does not matter) |
| 50 | +
|
| 51 | + For each instance in the mini-batch, the loss computes the Smooth-AP when it is used as the query and the rest of the |
| 52 | + mini-batch is used as the retrieval set. The positive set is formed of the other instances in the batch from the |
| 53 | + same class. The loss returns the average Smooth-AP across all instances in the mini-batch. |
| 54 | +
|
| 55 | + Args: |
| 56 | + anneal : float |
| 57 | + the temperature of the sigmoid that is used to smooth the ranking function. A low value of the temperature |
| 58 | + results in a steep sigmoid, that tightly approximates the heaviside step function in the ranking function. |
| 59 | + batch_size : int |
| 60 | + the batch size being used during training. |
| 61 | + num_id : int |
| 62 | + the number of different classes that are represented in the batch. |
| 63 | + feat_dims : int |
| 64 | + the dimension of the input feature embeddings |
| 65 | +
|
| 66 | + Shape: |
| 67 | + - Input (preds): (batch_size, feat_dims) (must be a cuda torch float tensor) |
| 68 | + - Output: scalar |
| 69 | +
|
| 70 | + Examples:: |
| 71 | +
|
| 72 | + >>> loss = SmoothAP(0.01, 60, 6, 256) |
| 73 | + >>> input = torch.randn(60, 256, requires_grad=True).to("cuda:0") |
| 74 | + >>> output = loss(input) |
| 75 | + >>> output.backward() |
| 76 | + """ |
| 77 | + |
| 78 | + def __init__(self, anneal, batch_size, num_id, feat_dims): |
| 79 | + """ |
| 80 | + Parameters |
| 81 | + ---------- |
| 82 | + anneal : float |
| 83 | + the temperature of the sigmoid that is used to smooth the ranking function |
| 84 | + batch_size : int |
| 85 | + the batch size being used |
| 86 | + num_id : int |
| 87 | + the number of different classes that are represented in the batch |
| 88 | + feat_dims : int |
| 89 | + the dimension of the input feature embeddings |
| 90 | + """ |
| 91 | + super(SmoothAP, self).__init__() |
| 92 | + |
| 93 | + assert batch_size % num_id == 0 |
| 94 | + |
| 95 | + self.anneal = anneal |
| 96 | + self.batch_size = batch_size |
| 97 | + self.num_id = num_id |
| 98 | + self.feat_dims = feat_dims |
| 99 | + |
| 100 | + def forward(self, preds): |
| 101 | + """Forward pass for all input predictions: preds - (batch_size x feat_dims)""" |
| 102 | + |
| 103 | + # ------ differentiable ranking of all retrieval set ------ |
| 104 | + # compute the mask which ignores the relevance score of the query to itself |
| 105 | + mask = 1.0 - torch.eye(self.batch_size) |
| 106 | + mask = mask.unsqueeze(dim=0).repeat(self.batch_size, 1, 1) |
| 107 | + # compute the relevance scores via cosine similarity of the CNN-produced embedding vectors |
| 108 | + sim_all = compute_aff(preds) |
| 109 | + sim_all_repeat = sim_all.unsqueeze(dim=1).repeat(1, self.batch_size, 1) |
| 110 | + # compute the difference matrix |
| 111 | + sim_diff = sim_all_repeat - sim_all_repeat.permute(0, 2, 1) |
| 112 | + # pass through the sigmoid |
| 113 | + sim_sg = sigmoid(sim_diff, temp=self.anneal) * mask.to(TEST_DEVICE) |
| 114 | + # compute the rankings |
| 115 | + sim_all_rk = torch.sum(sim_sg, dim=-1) + 1 |
| 116 | + |
| 117 | + # ------ differentiable ranking of only positive set in retrieval set ------ |
| 118 | + # compute the mask which only gives non-zero weights to the positive set |
| 119 | + xs = preds.view(self.num_id, int(self.batch_size / self.num_id), self.feat_dims) |
| 120 | + pos_mask = 1.0 - torch.eye(int(self.batch_size / self.num_id)) |
| 121 | + pos_mask = ( |
| 122 | + pos_mask.unsqueeze(dim=0) |
| 123 | + .unsqueeze(dim=0) |
| 124 | + .repeat(self.num_id, int(self.batch_size / self.num_id), 1, 1) |
| 125 | + ) |
| 126 | + |
| 127 | + # compute the relevance scores |
| 128 | + sim_pos = torch.bmm(xs, xs.permute(0, 2, 1)) |
| 129 | + sim_pos_repeat = sim_pos.unsqueeze(dim=2).repeat( |
| 130 | + 1, 1, int(self.batch_size / self.num_id), 1 |
| 131 | + ) |
| 132 | + # compute the difference matrix |
| 133 | + sim_pos_diff = sim_pos_repeat - sim_pos_repeat.permute(0, 1, 3, 2) |
| 134 | + # pass through the sigmoid |
| 135 | + sim_pos_sg = sigmoid(sim_pos_diff, temp=self.anneal) * pos_mask.to(TEST_DEVICE) |
| 136 | + # compute the rankings of the positive set |
| 137 | + sim_pos_rk = torch.sum(sim_pos_sg, dim=-1) + 1 |
| 138 | + |
| 139 | + # sum the values of the Smooth-AP for all instances in the mini-batch |
| 140 | + ap = torch.zeros(1).to(TEST_DEVICE) |
| 141 | + group = int(self.batch_size / self.num_id) |
| 142 | + for ind in range(self.num_id): |
| 143 | + pos_divide = torch.sum( |
| 144 | + sim_pos_rk[ind] |
| 145 | + / ( |
| 146 | + sim_all_rk[ |
| 147 | + (ind * group) : ((ind + 1) * group), |
| 148 | + (ind * group) : ((ind + 1) * group), |
| 149 | + ] |
| 150 | + ) |
| 151 | + ) |
| 152 | + ap = ap + ((pos_divide / group) / self.batch_size) |
| 153 | + |
| 154 | + return 1 - ap |
| 155 | + |
| 156 | + |
| 157 | +class TestSmoothAPLoss(unittest.TestCase): |
| 158 | + def test_smooth_ap_loss(self): |
| 159 | + for dtype in TEST_DTYPES: |
| 160 | + for seed in TEST_SEEDS: |
| 161 | + torch.manual_seed(seed) |
| 162 | + loss = SmoothAP( |
| 163 | + HYPERPARAMETERS["temp"], |
| 164 | + HYPERPARAMETERS["batch_size"], |
| 165 | + HYPERPARAMETERS["num_id"], |
| 166 | + HYPERPARAMETERS["feat_dims"], |
| 167 | + ) |
| 168 | + rand_tensor = ( |
| 169 | + torch.randn( |
| 170 | + HYPERPARAMETERS["batch_size"], |
| 171 | + HYPERPARAMETERS["feat_dims"], |
| 172 | + requires_grad=True, |
| 173 | + ) |
| 174 | + .to(TEST_DEVICE) |
| 175 | + .to(dtype) |
| 176 | + ) |
| 177 | + # The original code uses a model that normalizes the output vector |
| 178 | + input_ = F.normalize(rand_tensor, p=2.0, dim=-1) |
| 179 | + output = loss(input_) |
| 180 | + |
| 181 | + loss2 = SmoothAPLoss(temperature=HYPERPARAMETERS["temp"]) |
| 182 | + # The original code assumes the label is in this format |
| 183 | + labels = [] |
| 184 | + for i in range( |
| 185 | + HYPERPARAMETERS["batch_size"] // HYPERPARAMETERS["num_id"] |
| 186 | + ): |
| 187 | + labels.extend([i for _ in range(HYPERPARAMETERS["num_id"])]) |
| 188 | + |
| 189 | + labels = torch.tensor(labels) |
| 190 | + output2 = loss2.forward(rand_tensor, labels) |
| 191 | + self.assertTrue(torch.isclose(output, output2)) |
0 commit comments