|
| 1 | +import numpy as np |
| 2 | +import torch |
| 3 | + |
| 4 | +from ..distances import LpDistance |
| 5 | +from ..utils import common_functions as c_f |
| 6 | +from ..utils import loss_and_miner_utils as lmu |
| 7 | +from .base_metric_loss_function import BaseMetricLossFunction |
| 8 | + |
| 9 | + |
| 10 | +def find_hard_negatives(dmat): |
| 11 | + """ |
| 12 | + a = A * P' |
| 13 | + A: N * ndim |
| 14 | + P: N * ndim |
| 15 | +
|
| 16 | + a1p1 a1p2 a1p3 a1p4 ... |
| 17 | + a2p1 a2p2 a2p3 a2p4 ... |
| 18 | + a3p1 a3p2 a3p3 a3p4 ... |
| 19 | + a4p1 a4p2 a4p3 a4p4 ... |
| 20 | + ... ... ... ... |
| 21 | + """ |
| 22 | + |
| 23 | + pos = dmat.diag() |
| 24 | + dmat.fill_diagonal_(np.inf) |
| 25 | + |
| 26 | + min_a, _ = torch.min(dmat, dim=0) |
| 27 | + min_p, _ = torch.min(dmat, dim=1) |
| 28 | + neg = torch.min(min_a, min_p) |
| 29 | + return pos, neg |
| 30 | + |
| 31 | + |
| 32 | +class DynamicSoftMarginLoss(BaseMetricLossFunction): |
| 33 | + r"""Loss function with dynamical margin parameter introduced in https://openaccess.thecvf.com/content_ICCV_2019/papers/Zhang_Learning_Local_Descriptors_With_a_CDF-Based_Dynamic_Soft_Margin_ICCV_2019_paper.pdf |
| 34 | +
|
| 35 | + Args: |
| 36 | + min_val: minimum significative value for `d_pos - d_neg` |
| 37 | + num_bins: number of equally spaced bins for the partition of the interval [min_val, :math:`+\infty`] |
| 38 | + momentum: weight assigned to the histogram computed from the current batch |
| 39 | + """ |
| 40 | + |
| 41 | + def __init__(self, min_val=-2.0, num_bins=10, momentum=0.01, **kwargs): |
| 42 | + super().__init__(**kwargs) |
| 43 | + c_f.assert_distance_type(self, LpDistance, normalize_embeddings=True, p=2) |
| 44 | + self.min_val = min_val |
| 45 | + self.num_bins = int(num_bins) |
| 46 | + self.delta = 2 * abs(min_val) / num_bins |
| 47 | + self.momentum = momentum |
| 48 | + self.hist_ = torch.zeros((num_bins,)) |
| 49 | + self.add_to_recordable_attributes(list_of_names=["num_bins"], is_stat=False) |
| 50 | + |
| 51 | + def compute_loss(self, embeddings, labels, indices_tuple, ref_emb, ref_labels): |
| 52 | + self.hist_ = c_f.to_device( |
| 53 | + self.hist_, tensor=embeddings, dtype=embeddings.dtype |
| 54 | + ) |
| 55 | + |
| 56 | + if labels is None: |
| 57 | + loss = self.compute_loss_without_labels( |
| 58 | + embeddings, labels, indices_tuple, ref_emb, ref_labels |
| 59 | + ) |
| 60 | + else: |
| 61 | + loss = self.compute_loss_with_labels( |
| 62 | + embeddings, labels, indices_tuple, ref_emb, ref_labels |
| 63 | + ) |
| 64 | + |
| 65 | + if len(loss) == 0: |
| 66 | + return self.zero_losses() |
| 67 | + |
| 68 | + self.update_histogram(loss) |
| 69 | + loss = self.weigh_loss(loss) |
| 70 | + loss = loss.mean() |
| 71 | + return { |
| 72 | + "loss": { |
| 73 | + "losses": loss, |
| 74 | + "indices": None, |
| 75 | + "reduction_type": "already_reduced", |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + def compute_loss_without_labels( |
| 80 | + self, embeddings, labels, indices_tuple, ref_emb, ref_labels |
| 81 | + ): |
| 82 | + mat = self.distance(embeddings, ref_emb) |
| 83 | + r, c = mat.size() |
| 84 | + |
| 85 | + d_pos = torch.zeros(max(r, c)) |
| 86 | + d_pos = c_f.to_device(d_pos, tensor=embeddings, dtype=embeddings.dtype) |
| 87 | + d_pos[: min(r, c)] = mat.diag() |
| 88 | + mat.fill_diagonal_(np.inf) |
| 89 | + |
| 90 | + min_a, min_p = torch.zeros(max(r, c)), torch.zeros( |
| 91 | + max(r, c) |
| 92 | + ) # Check for unequal number of anchors and positives |
| 93 | + min_a = c_f.to_device(min_a, tensor=embeddings, dtype=embeddings.dtype) |
| 94 | + min_p = c_f.to_device(min_p, tensor=embeddings, dtype=embeddings.dtype) |
| 95 | + min_a[:c], _ = torch.min(mat, dim=0) |
| 96 | + min_p[:r], _ = torch.min(mat, dim=1) |
| 97 | + |
| 98 | + d_neg = torch.min(min_a, min_p) |
| 99 | + return d_pos - d_neg |
| 100 | + |
| 101 | + def compute_loss_with_labels( |
| 102 | + self, embeddings, labels, indices_tuple, ref_emb, ref_labels |
| 103 | + ): |
| 104 | + anchor_idx, positive_idx, negative_idx = lmu.convert_to_triplets( |
| 105 | + indices_tuple, labels, ref_labels, t_per_anchor="all" |
| 106 | + ) # Use all instead of t_per_anchor=1 to be deterministic |
| 107 | + mat = self.distance(embeddings, ref_emb) |
| 108 | + d_pos, d_neg = mat[anchor_idx, positive_idx], mat[anchor_idx, negative_idx] |
| 109 | + return d_pos - d_neg |
| 110 | + |
| 111 | + def update_histogram(self, data): |
| 112 | + idx, alpha = torch.floor((data - self.min_val) / self.delta).to( |
| 113 | + dtype=torch.long |
| 114 | + ), torch.frac((data - self.min_val) / self.delta) |
| 115 | + momentum = self.momentum if self.hist_.sum() != 0 else 1.0 |
| 116 | + self.hist_ = torch.scatter_add( |
| 117 | + (1.0 - momentum) * self.hist_, 0, idx, momentum * (1 - alpha) |
| 118 | + ) |
| 119 | + self.hist_ = torch.scatter_add(self.hist_, 0, idx + 1, momentum * alpha) |
| 120 | + self.hist_ /= self.hist_.sum() |
| 121 | + |
| 122 | + def weigh_loss(self, data): |
| 123 | + CDF = torch.cumsum(self.hist_, 0) |
| 124 | + idx = torch.floor((data - self.min_val) / self.delta).to(dtype=torch.long) |
| 125 | + return CDF[idx] * data |
0 commit comments