loss.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Loss functions
  4. """
  5. import torch
  6. import torch.nn as nn
  7. from utils.metrics import bbox_iou
  8. from utils.torch_utils import de_parallel
  9. def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
  10. # return positive, negative label smoothing BCE targets
  11. return 1.0 - 0.5 * eps, 0.5 * eps
  12. class BCEBlurWithLogitsLoss(nn.Module):
  13. # BCEwithLogitLoss() with reduced missing label effects.
  14. def __init__(self, alpha=0.05):
  15. super().__init__()
  16. self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
  17. self.alpha = alpha
  18. def forward(self, pred, true):
  19. loss = self.loss_fcn(pred, true)
  20. pred = torch.sigmoid(pred) # prob from logits
  21. dx = pred - true # reduce only missing label effects
  22. # dx = (pred - true).abs() # reduce missing label and false label effects
  23. alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
  24. loss *= alpha_factor
  25. return loss.mean()
  26. class FocalLoss(nn.Module):
  27. # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
  28. def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
  29. super().__init__()
  30. self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
  31. self.gamma = gamma
  32. self.alpha = alpha
  33. self.reduction = loss_fcn.reduction
  34. self.loss_fcn.reduction = 'none' # required to apply FL to each element
  35. def forward(self, pred, true):
  36. loss = self.loss_fcn(pred, true)
  37. # p_t = torch.exp(-loss)
  38. # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
  39. # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
  40. pred_prob = torch.sigmoid(pred) # prob from logits
  41. p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
  42. alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
  43. modulating_factor = (1.0 - p_t) ** self.gamma
  44. loss *= alpha_factor * modulating_factor
  45. if self.reduction == 'mean':
  46. return loss.mean()
  47. elif self.reduction == 'sum':
  48. return loss.sum()
  49. else: # 'none'
  50. return loss
  51. class QFocalLoss(nn.Module):
  52. # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
  53. def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
  54. super().__init__()
  55. self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
  56. self.gamma = gamma
  57. self.alpha = alpha
  58. self.reduction = loss_fcn.reduction
  59. self.loss_fcn.reduction = 'none' # required to apply FL to each element
  60. def forward(self, pred, true):
  61. loss = self.loss_fcn(pred, true)
  62. pred_prob = torch.sigmoid(pred) # prob from logits
  63. alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
  64. modulating_factor = torch.abs(true - pred_prob) ** self.gamma
  65. loss *= alpha_factor * modulating_factor
  66. if self.reduction == 'mean':
  67. return loss.mean()
  68. elif self.reduction == 'sum':
  69. return loss.sum()
  70. else: # 'none'
  71. return loss
  72. class ComputeLoss:
  73. sort_obj_iou = False
  74. # Compute losses
  75. def __init__(self, model, autobalance=False):
  76. device = next(model.parameters()).device # get save_models device
  77. h = model.hyp # hyperparameters
  78. # Define criteria
  79. BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
  80. BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
  81. # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
  82. self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
  83. # Focal loss
  84. g = h['fl_gamma'] # focal loss gamma
  85. if g > 0:
  86. BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
  87. m = de_parallel(model).model[-1] # Detect() module
  88. self.balance = {3: [4.0, 1.0, 0.4]}.get(m.nl, [4.0, 1.0, 0.25, 0.06, 0.02]) # P3-P7
  89. self.ssi = list(m.stride).index(16) if autobalance else 0 # stride 16 index
  90. self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
  91. self.na = m.na # number of anchors
  92. self.nc = m.nc # number of classes
  93. self.nl = m.nl # number of layers
  94. self.anchors = m.anchors
  95. self.device = device
  96. def __call__(self, p, targets): # predictions, targets
  97. lcls = torch.zeros(1, device=self.device) # class loss
  98. lbox = torch.zeros(1, device=self.device) # box loss
  99. lobj = torch.zeros(1, device=self.device) # object loss
  100. tcls, tbox, indices, anchors = self.build_targets(p, targets) # targets
  101. # Losses
  102. for i, pi in enumerate(p): # layer index, layer predictions
  103. b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
  104. tobj = torch.zeros(pi.shape[:4], dtype=pi.dtype, device=self.device) # target obj
  105. n = b.shape[0] # number of targets
  106. if n:
  107. # pxy, pwh, _, pcls = pi[b, a, gj, gi].tensor_split((2, 4, 5), dim=1) # faster, requires torch 1.8.0
  108. pxy, pwh, _, pcls = pi[b, a, gj, gi].split((2, 2, 1, self.nc), 1) # target-subset of predictions
  109. # Regression
  110. pxy = pxy.sigmoid() * 2 - 0.5
  111. pwh = (pwh.sigmoid() * 2) ** 2 * anchors[i]
  112. pbox = torch.cat((pxy, pwh), 1) # predicted box
  113. iou = bbox_iou(pbox, tbox[i], CIoU=True).squeeze() # iou(prediction, target)
  114. lbox += (1.0 - iou).mean() # iou loss
  115. # Objectness
  116. iou = iou.detach().clamp(0).type(tobj.dtype)
  117. if self.sort_obj_iou:
  118. j = iou.argsort()
  119. b, a, gj, gi, iou = b[j], a[j], gj[j], gi[j], iou[j]
  120. if self.gr < 1:
  121. iou = (1.0 - self.gr) + self.gr * iou
  122. tobj[b, a, gj, gi] = iou # iou ratio
  123. # Classification
  124. if self.nc > 1: # cls loss (only if multiple classes)
  125. t = torch.full_like(pcls, self.cn, device=self.device) # targets
  126. t[range(n), tcls[i]] = self.cp
  127. lcls += self.BCEcls(pcls, t) # BCE
  128. # Append targets to text file
  129. # with open('targets.txt', 'a') as file:
  130. # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
  131. obji = self.BCEobj(pi[..., 4], tobj)
  132. lobj += obji * self.balance[i] # obj loss
  133. if self.autobalance:
  134. self.balance[i] = self.balance[i] * 0.9999 + 0.0001 / obji.detach().item()
  135. if self.autobalance:
  136. self.balance = [x / self.balance[self.ssi] for x in self.balance]
  137. lbox *= self.hyp['box']
  138. lobj *= self.hyp['obj']
  139. lcls *= self.hyp['cls']
  140. bs = tobj.shape[0] # batch size
  141. return (lbox + lobj + lcls) * bs, torch.cat((lbox, lobj, lcls)).detach()
  142. def build_targets(self, p, targets):
  143. # Build targets for compute_loss(), input targets(image,class,x,y,w,h)
  144. na, nt = self.na, targets.shape[0] # number of anchors, targets
  145. tcls, tbox, indices, anch = [], [], [], []
  146. gain = torch.ones(7, device=self.device) # normalized to gridspace gain
  147. ai = torch.arange(na, device=self.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
  148. targets = torch.cat((targets.repeat(na, 1, 1), ai[..., None]), 2) # append anchor indices
  149. g = 0.5 # bias
  150. off = torch.tensor(
  151. [
  152. [0, 0],
  153. [1, 0],
  154. [0, 1],
  155. [-1, 0],
  156. [0, -1], # j,k,l,m
  157. # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
  158. ],
  159. device=self.device).float() * g # offsets
  160. for i in range(self.nl):
  161. anchors, shape = self.anchors[i], p[i].shape
  162. gain[2:6] = torch.tensor(shape)[[3, 2, 3, 2]] # xyxy gain
  163. # Match targets to anchors
  164. t = targets * gain # shape(3,n,7)
  165. if nt:
  166. # Matches
  167. r = t[..., 4:6] / anchors[:, None] # wh ratio
  168. j = torch.max(r, 1 / r).max(2)[0] < self.hyp['anchor_t'] # compare
  169. # j = wh_iou(anchors, t[:, 4:6]) > save_models.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
  170. t = t[j] # filter
  171. # Offsets
  172. gxy = t[:, 2:4] # grid xy
  173. gxi = gain[[2, 3]] - gxy # inverse
  174. j, k = ((gxy % 1 < g) & (gxy > 1)).T
  175. l, m = ((gxi % 1 < g) & (gxi > 1)).T
  176. j = torch.stack((torch.ones_like(j), j, k, l, m))
  177. t = t.repeat((5, 1, 1))[j]
  178. offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
  179. else:
  180. t = targets[0]
  181. offsets = 0
  182. # Define
  183. bc, gxy, gwh, a = t.chunk(4, 1) # (image, class), grid xy, grid wh, anchors
  184. a, (b, c) = a.long().view(-1), bc.long().T # anchors, image, class
  185. gij = (gxy - offsets).long()
  186. gi, gj = gij.T # grid indices
  187. # Append
  188. indices.append((b, a, gj.clamp_(0, shape[2] - 1), gi.clamp_(0, shape[3] - 1))) # image, anchor, grid
  189. tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
  190. anch.append(anchors[a]) # anchors
  191. tcls.append(c) # class
  192. return tcls, tbox, indices, anch