loss.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. import torch
  2. import torch.nn as nn
  3. import torch.nn.functional as F
  4. from ..general import xywh2xyxy
  5. from ..loss import FocalLoss, smooth_BCE
  6. from ..metrics import bbox_iou
  7. from ..torch_utils import de_parallel
  8. from .general import crop_mask
  9. class ComputeLoss:
  10. # Compute losses
  11. def __init__(self, model, autobalance=False, overlap=False):
  12. self.sort_obj_iou = False
  13. self.overlap = overlap
  14. device = next(model.parameters()).device # get model device
  15. h = model.hyp # hyperparameters
  16. self.device = device
  17. # Define criteria
  18. BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
  19. BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
  20. # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
  21. self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
  22. # Focal loss
  23. g = h['fl_gamma'] # focal loss gamma
  24. if g > 0:
  25. BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
  26. m = de_parallel(model).model[-1] # Detect() module
  27. self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
  28. self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
  29. self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
  30. self.na = m.na # number of anchors
  31. self.nc = m.nc # number of classes
  32. self.nl = m.nl # number of layers
  33. self.nm = m.nm # number of masks
  34. self.anchors = m.anchors
  35. self.device = device
  36. def __call__(self, preds, targets, masks): # predictions, targets, model
  37. p, proto = preds
  38. bs, nm, mask_h, mask_w = proto.shape # batch size, number of masks, mask height, mask width
  39. lcls = torch.zeros(1, device=self.device)
  40. lbox = torch.zeros(1, device=self.device)
  41. lobj = torch.zeros(1, device=self.device)
  42. lseg = torch.zeros(1, device=self.device)
  43. tcls, tbox, indices, anchors, tidxs, xywhn = self.build_targets(p, targets) # targets
  44. # Losses
  45. for i, pi in enumerate(p): # layer index, layer predictions
  46. b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
  47. tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
  48. n = b.shape[0] # number of targets
  49. if n:
  50. pxy, pwh, _, pcls, pmask = pi[b, a, gj, gi].split((2, 2, 1, self.nc, nm), 1) # subset of predictions
  51. # Box regression
  52. pxy = pxy.sigmoid() * 2 - 0.5
  53. pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
  54. pbox = torch.cat((pxy, pwh), 1) # predicted box
  55. iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
  56. lbox += (1.0 - iou).mean() # iou loss
  57. # Objectness
  58. iou = iou.detach().clamp(0).type(tobj.dtype)
  59. if self.sort_obj_iou:
  60. j = iou.argsort()
  61. b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
  62. if self.gr < 1:
  63. iou = (1.0 - self.gr) + self.gr * iou
  64. tobj[b, a, gj, gi] = iou # iou ratio
  65. # Classification
  66. if self.nc > 1: # cls loss (only if multiple classes)
  67. t = torch.full_like(pcls, self.cn, device=self.device) # targets
  68. t[range(n), tcls[i]] = self.cp
  69. lcls += self.BCEcls(pcls, t) # BCE
  70. # Mask regression
  71. if tuple(masks.shape[-2:]) != (mask_h, mask_w): # downsample
  72. masks = F.interpolate(masks[None], (mask_h, mask_w), mode="nearest")[0]
  73. marea = xywhn[i][:, 2:].prod(1) # mask width, height normalized
  74. mxyxy = xywh2xyxy(xywhn[i] * torch.tensor([mask_w, mask_h, mask_w, mask_h], device=self.device))
  75. for bi in b.unique():
  76. j = b == bi # matching index
  77. if self.overlap:
  78. mask_gti = torch.where(masks[bi][None] == tidxs[i][j].view(-1, 1, 1), 1.0, 0.0)
  79. else:
  80. mask_gti = masks[tidxs[i]][j]
  81. lseg += self.single_mask_loss(mask_gti, pmask[j], proto[bi], mxyxy[j], marea[j])
  82. obji = self.BCEobj(pi[..., 4], tobj)
  83. lobj += obji * self.balance[i] # obj loss
  84. if self.autobalance:
  85. self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
  86. if self.autobalance:
  87. self.balance = [x / self.balance[self.ssi] for x in self.balance]
  88. lbox *= self.hyp["box"]
  89. lobj *= self.hyp["obj"]
  90. lcls *= self.hyp["cls"]
  91. lseg *= self.hyp["box"] / bs
  92. loss = lbox + lobj + lcls + lseg
  93. return loss * bs, torch.cat((lbox, lseg, lobj, lcls)).detach()
  94. def single_mask_loss(self, gt_mask, pred, proto, xyxy, area):
  95. # Mask loss for one image
  96. pred_mask = (pred @ proto.view(self.nm, -1)).view(-1, *proto.shape[1:]) # (n,32) @ (32,80,80) -> (n,80,80)
  97. loss = F.binary_cross_entropy_with_logits(pred_mask, gt_mask, reduction="none")
  98. return (crop_mask(loss, xyxy).mean(dim=(1, 2)) / area).mean()
  99. def build_targets(self, p, targets):
  100. # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
  101. na, nt = self.na, targets.shape[0] # number of anchors, targets
  102. tcls, tbox, indices, anch, tidxs, xywhn = [], [], [], [], [], []
  103. gain = torch.ones(8, device=self.device) # normalized to gridspace gain
  104. ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
  105. if self.overlap:
  106. batch = p[0].shape[0]
  107. ti = []
  108. for i in range(batch):
  109. num = (targets[:, 0] == i).sum() # find number of targets of each image
  110. ti.append(torch.arange(num, device=self.device).float().view(1, num).repeat(na, 1) + 1) # (na, num)
  111. ti = torch.cat(ti, 1) # (na, nt)
  112. else:
  113. ti = torch.arange(nt, device=self.device).float().view(1, nt).repeat(na, 1)
  114. targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None], ti[..., None]), 2) # append anchor indices
  115. g = 0.5 # bias
  116. off = torch.tensor(
  117. [
  118. [0, 0],
  119. [1, 0],
  120. [0, 1],
  121. [-1, 0],
  122. [0, -1], # j,k,l,m
  123. # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
  124. ],
  125. device=self.device).float() * g # offsets
  126. for i in range(self.nl):
  127. anchors, shape = self.anchors[i], p[i].shape
  128. gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
  129. # Match targets to anchors
  130. t = targets * gain # shape(3,n,7)
  131. if nt:
  132. # Matches
  133. r = t[..., 4:6] / anchors[:, None] # wh ratio
  134. j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
  135. # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
  136. t = t[j] # filter
  137. # Offsets
  138. gxy = t[:, 2:4] # grid xy
  139. gxi = gain[[2, 3]] - gxy # inverse
  140. j, k = ((gxy % 1 < g) & (gxy > 1)).T
  141. l, m = ((gxi % 1 < g) & (gxi > 1)).T
  142. j = torch.stack((torch.ones_like(j), j, k, l, m))
  143. t = t.repeat((5, 1, 1))[j]
  144. offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
  145. else:
  146. t = targets[0]
  147. offsets = 0
  148. # Define
  149. bc, gxy, gwh, at = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
  150. (a, tidx), (b, c) = at.long().T, bc.long().T # anchors, image, class
  151. gij = (gxy - offsets).long()
  152. gi, gj = gij.T # grid indices
  153. # Append
  154. indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
  155. tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
  156. anch.append(anchors[a]) # anchors
  157. tcls.append(c) # class
  158. tidxs.append(tidx)
  159. xywhn.append(torch.cat((gxy, gwh), 1) / gain[2:6]) # xywh normalized
  160. return tcls, tbox, indices, anch, tidxs, xywhn