Binary focal loss cost.
| 212 | |
| 213 | @TASK_UTILS.register_module() |
| 214 | class BinaryFocalLossCost(FocalLossCost): |
| 215 | """Binary focal loss cost.""" |
| 216 | |
| 217 | def _focal_loss_cost(self, cls_pred: Tensor, gt_labels: Tensor) -> Tensor: |
| 218 | """ |
| 219 | Args: |
| 220 | cls_pred (Tensor): Predicted classification logits, shape |
| 221 | (num_queries, num_class). |
| 222 | gt_labels (Tensor): Label of `gt_bboxes`, shape (num_gt,). |
| 223 | |
| 224 | Returns: |
| 225 | torch.Tensor: cls_cost value with weight |
| 226 | """ |
| 227 | cls_pred = cls_pred.flatten(1) |
| 228 | gt_labels = gt_labels.flatten(1).float() |
| 229 | cls_pred = cls_pred.sigmoid() |
| 230 | neg_cost = -(1 - cls_pred + self.eps).log() * ( |
| 231 | 1 - self.alpha) * cls_pred.pow(self.gamma) |
| 232 | pos_cost = -(cls_pred + self.eps).log() * self.alpha * ( |
| 233 | 1 - cls_pred).pow(self.gamma) |
| 234 | |
| 235 | cls_cost = torch.einsum('nc,mc->nm', pos_cost, gt_labels) + \ |
| 236 | torch.einsum('nc,mc->nm', neg_cost, (1 - gt_labels)) |
| 237 | return cls_cost * self.weight |
| 238 | |
| 239 | def __call__(self, |
| 240 | pred_instances: InstanceData, |
| 241 | gt_instances: InstanceData, |
| 242 | img_meta: Optional[dict] = None, |
| 243 | **kwargs) -> Tensor: |
| 244 | """Compute match cost. |
| 245 | |
| 246 | Args: |
| 247 | pred_instances (:obj:`InstanceData`): Predicted instances which |
| 248 | must contain ``scores`` or ``masks``. |
| 249 | gt_instances (:obj:`InstanceData`): Ground truth which must contain |
| 250 | ``labels`` or ``mask``. |
| 251 | img_meta (Optional[dict]): Image information. Defaults to None. |
| 252 | |
| 253 | Returns: |
| 254 | Tensor: Match Cost matrix of shape (num_preds, num_gts). |
| 255 | """ |
| 256 | # gt_instances.text_token_mask is a repeated tensor of the same length |
| 257 | # of instances. Only gt_instances.text_token_mask[0] is useful |
| 258 | text_token_mask = torch.nonzero( |
| 259 | gt_instances.text_token_mask[0]).squeeze(-1) |
| 260 | # mask used to filter padding texts |
| 261 | # (num_query,) |
| 262 | pred_scores = pred_instances.scores_3d[:, text_token_mask] |
| 263 | # (1, real_tex_length) |
| 264 | gt_labels = gt_instances.positive_maps[:, text_token_mask] |
| 265 | return self._focal_loss_cost(pred_scores, gt_labels) |
nothing calls this directly
no outgoing calls
no test coverage detected