yolo_loss.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import paddle
  18. from paddle import fluid
  19. try:
  20. from collections.abc import Sequence
  21. except Exception:
  22. from collections import Sequence
  23. class YOLOv3Loss(object):
  24. """
  25. Combined loss for YOLOv3 network
  26. Args:
  27. batch_size (int): training batch size
  28. ignore_thresh (float): threshold to ignore confidence loss
  29. label_smooth (bool): whether to use label smoothing
  30. use_fine_grained_loss (bool): whether use fine grained YOLOv3 loss
  31. instead of fluid.layers.yolov3_loss
  32. """
  33. def __init__(self,
  34. batch_size=8,
  35. ignore_thresh=0.7,
  36. label_smooth=True,
  37. use_fine_grained_loss=False,
  38. iou_loss=None,
  39. iou_aware_loss=None,
  40. downsample=[32, 16, 8],
  41. scale_x_y=1.,
  42. match_score=False):
  43. self._batch_size = batch_size
  44. self._ignore_thresh = ignore_thresh
  45. self._label_smooth = label_smooth
  46. self._use_fine_grained_loss = use_fine_grained_loss
  47. self._iou_loss = iou_loss
  48. self._iou_aware_loss = iou_aware_loss
  49. self.downsample = downsample
  50. self.scale_x_y = scale_x_y
  51. self.match_score = match_score
  52. def __call__(self, outputs, gt_box, gt_label, gt_score, targets, anchors,
  53. anchor_masks, mask_anchors, num_classes, prefix_name):
  54. if self._use_fine_grained_loss:
  55. return self._get_fine_grained_loss(
  56. outputs, targets, gt_box, self._batch_size, num_classes,
  57. mask_anchors, self._ignore_thresh)
  58. else:
  59. losses = []
  60. for i, output in enumerate(outputs):
  61. scale_x_y = self.scale_x_y if not isinstance(
  62. self.scale_x_y, Sequence) else self.scale_x_y[i]
  63. anchor_mask = anchor_masks[i]
  64. if paddle.__version__ < '1.8.4' and paddle.__version__ != '0.0.0':
  65. loss = fluid.layers.yolov3_loss(
  66. x=output,
  67. gt_box=gt_box,
  68. gt_label=gt_label,
  69. gt_score=gt_score,
  70. anchors=anchors,
  71. anchor_mask=anchor_mask,
  72. class_num=num_classes,
  73. ignore_thresh=self._ignore_thresh,
  74. downsample_ratio=self.downsample[i],
  75. use_label_smooth=self._label_smooth,
  76. name=prefix_name + "yolo_loss" + str(i))
  77. else:
  78. loss = fluid.layers.yolov3_loss(
  79. x=output,
  80. gt_box=gt_box,
  81. gt_label=gt_label,
  82. gt_score=gt_score,
  83. anchors=anchors,
  84. anchor_mask=anchor_mask,
  85. class_num=num_classes,
  86. ignore_thresh=self._ignore_thresh,
  87. downsample_ratio=self.downsample[i],
  88. use_label_smooth=self._label_smooth,
  89. scale_x_y=scale_x_y,
  90. name=prefix_name + "yolo_loss" + str(i))
  91. losses.append(fluid.layers.reduce_mean(loss))
  92. return {'loss': sum(losses)}
  93. def _get_fine_grained_loss(self,
  94. outputs,
  95. targets,
  96. gt_box,
  97. batch_size,
  98. num_classes,
  99. mask_anchors,
  100. ignore_thresh,
  101. eps=1.e-10):
  102. """
  103. Calculate fine grained YOLOv3 loss
  104. Args:
  105. outputs ([Variables]): List of Variables, output of backbone stages
  106. targets ([Variables]): List of Variables, The targets for yolo
  107. loss calculatation.
  108. gt_box (Variable): The ground-truth boudding boxes.
  109. batch_size (int): The training batch size
  110. num_classes (int): class num of dataset
  111. mask_anchors ([[float]]): list of anchors in each output layer
  112. ignore_thresh (float): prediction bbox overlap any gt_box greater
  113. than ignore_thresh, objectness loss will
  114. be ignored.
  115. Returns:
  116. Type: dict
  117. xy_loss (Variable): YOLOv3 (x, y) coordinates loss
  118. wh_loss (Variable): YOLOv3 (w, h) coordinates loss
  119. obj_loss (Variable): YOLOv3 objectness score loss
  120. cls_loss (Variable): YOLOv3 classification loss
  121. """
  122. assert len(outputs) == len(targets), \
  123. "YOLOv3 output layer number not equal target number"
  124. loss_xys, loss_whs, loss_objs, loss_clss = [], [], [], []
  125. if self._iou_loss is not None:
  126. loss_ious = []
  127. if self._iou_aware_loss is not None:
  128. loss_iou_awares = []
  129. for i, (output, target,
  130. anchors) in enumerate(zip(outputs, targets, mask_anchors)):
  131. downsample = self.downsample[i]
  132. an_num = len(anchors) // 2
  133. if self._iou_aware_loss is not None:
  134. ioup, output = self._split_ioup(output, an_num, num_classes)
  135. x, y, w, h, obj, cls = self._split_output(output, an_num,
  136. num_classes)
  137. tx, ty, tw, th, tscale, tobj, tcls = self._split_target(target)
  138. tscale_tobj = tscale * tobj
  139. scale_x_y = self.scale_x_y if not isinstance(
  140. self.scale_x_y, Sequence) else self.scale_x_y[i]
  141. if (abs(scale_x_y - 1.0) < eps):
  142. loss_x = fluid.layers.sigmoid_cross_entropy_with_logits(
  143. x, tx) * tscale_tobj
  144. loss_x = fluid.layers.reduce_sum(loss_x, dim=[1, 2, 3])
  145. loss_y = fluid.layers.sigmoid_cross_entropy_with_logits(
  146. y, ty) * tscale_tobj
  147. loss_y = fluid.layers.reduce_sum(loss_y, dim=[1, 2, 3])
  148. else:
  149. dx = scale_x_y * fluid.layers.sigmoid(x) - 0.5 * (scale_x_y -
  150. 1.0)
  151. dy = scale_x_y * fluid.layers.sigmoid(y) - 0.5 * (scale_x_y -
  152. 1.0)
  153. loss_x = fluid.layers.abs(dx - tx) * tscale_tobj
  154. loss_x = fluid.layers.reduce_sum(loss_x, dim=[1, 2, 3])
  155. loss_y = fluid.layers.abs(dy - ty) * tscale_tobj
  156. loss_y = fluid.layers.reduce_sum(loss_y, dim=[1, 2, 3])
  157. # NOTE: we refined loss function of (w, h) as L1Loss
  158. loss_w = fluid.layers.abs(w - tw) * tscale_tobj
  159. loss_w = fluid.layers.reduce_sum(loss_w, dim=[1, 2, 3])
  160. loss_h = fluid.layers.abs(h - th) * tscale_tobj
  161. loss_h = fluid.layers.reduce_sum(loss_h, dim=[1, 2, 3])
  162. if self._iou_loss is not None:
  163. loss_iou = self._iou_loss(x, y, w, h, tx, ty, tw, th, anchors,
  164. downsample, self._batch_size,
  165. scale_x_y)
  166. loss_iou = loss_iou * tscale_tobj
  167. loss_iou = fluid.layers.reduce_sum(loss_iou, dim=[1, 2, 3])
  168. loss_ious.append(fluid.layers.reduce_mean(loss_iou))
  169. if self._iou_aware_loss is not None:
  170. loss_iou_aware = self._iou_aware_loss(
  171. ioup, x, y, w, h, tx, ty, tw, th, anchors, downsample,
  172. self._batch_size, scale_x_y)
  173. loss_iou_aware = loss_iou_aware * tobj
  174. loss_iou_aware = fluid.layers.reduce_sum(
  175. loss_iou_aware, dim=[1, 2, 3])
  176. loss_iou_awares.append(
  177. fluid.layers.reduce_mean(loss_iou_aware))
  178. loss_obj_pos, loss_obj_neg = self._calc_obj_loss(
  179. output, obj, tobj, gt_box, self._batch_size, anchors,
  180. num_classes, downsample, self._ignore_thresh, scale_x_y)
  181. loss_cls = fluid.layers.sigmoid_cross_entropy_with_logits(cls,
  182. tcls)
  183. loss_cls = fluid.layers.elementwise_mul(loss_cls, tobj, axis=0)
  184. loss_cls = fluid.layers.reduce_sum(loss_cls, dim=[1, 2, 3, 4])
  185. loss_xys.append(fluid.layers.reduce_mean(loss_x + loss_y))
  186. loss_whs.append(fluid.layers.reduce_mean(loss_w + loss_h))
  187. loss_objs.append(
  188. fluid.layers.reduce_mean(loss_obj_pos + loss_obj_neg))
  189. loss_clss.append(fluid.layers.reduce_mean(loss_cls))
  190. losses_all = {
  191. "loss_xy": fluid.layers.sum(loss_xys),
  192. "loss_wh": fluid.layers.sum(loss_whs),
  193. "loss_obj": fluid.layers.sum(loss_objs),
  194. "loss_cls": fluid.layers.sum(loss_clss),
  195. }
  196. if self._iou_loss is not None:
  197. losses_all["loss_iou"] = fluid.layers.sum(loss_ious)
  198. if self._iou_aware_loss is not None:
  199. losses_all["loss_iou_aware"] = fluid.layers.sum(loss_iou_awares)
  200. return losses_all
  201. def _split_ioup(self, output, an_num, num_classes):
  202. """
  203. Split output feature map to output, predicted iou
  204. along channel dimension
  205. """
  206. ioup = fluid.layers.slice(output, axes=[1], starts=[0], ends=[an_num])
  207. ioup = fluid.layers.sigmoid(ioup)
  208. oriout = fluid.layers.slice(
  209. output,
  210. axes=[1],
  211. starts=[an_num],
  212. ends=[an_num * (num_classes + 6)])
  213. return (ioup, oriout)
  214. def _split_output(self, output, an_num, num_classes):
  215. """
  216. Split output feature map to x, y, w, h, objectness, classification
  217. along channel dimension
  218. """
  219. x = fluid.layers.strided_slice(
  220. output,
  221. axes=[1],
  222. starts=[0],
  223. ends=[output.shape[1]],
  224. strides=[5 + num_classes])
  225. y = fluid.layers.strided_slice(
  226. output,
  227. axes=[1],
  228. starts=[1],
  229. ends=[output.shape[1]],
  230. strides=[5 + num_classes])
  231. w = fluid.layers.strided_slice(
  232. output,
  233. axes=[1],
  234. starts=[2],
  235. ends=[output.shape[1]],
  236. strides=[5 + num_classes])
  237. h = fluid.layers.strided_slice(
  238. output,
  239. axes=[1],
  240. starts=[3],
  241. ends=[output.shape[1]],
  242. strides=[5 + num_classes])
  243. obj = fluid.layers.strided_slice(
  244. output,
  245. axes=[1],
  246. starts=[4],
  247. ends=[output.shape[1]],
  248. strides=[5 + num_classes])
  249. clss = []
  250. stride = output.shape[1] // an_num
  251. for m in range(an_num):
  252. clss.append(
  253. fluid.layers.slice(
  254. output,
  255. axes=[1],
  256. starts=[stride * m + 5],
  257. ends=[stride * m + 5 + num_classes]))
  258. cls = fluid.layers.transpose(
  259. fluid.layers.stack(
  260. clss, axis=1), perm=[0, 1, 3, 4, 2])
  261. return (x, y, w, h, obj, cls)
  262. def _split_target(self, target):
  263. """
  264. split target to x, y, w, h, objectness, classification
  265. along dimension 2
  266. target is in shape [N, an_num, 6 + class_num, H, W]
  267. """
  268. tx = target[:, :, 0, :, :]
  269. ty = target[:, :, 1, :, :]
  270. tw = target[:, :, 2, :, :]
  271. th = target[:, :, 3, :, :]
  272. tscale = target[:, :, 4, :, :]
  273. tobj = target[:, :, 5, :, :]
  274. tcls = fluid.layers.transpose(
  275. target[:, :, 6:, :, :], perm=[0, 1, 3, 4, 2])
  276. tcls.stop_gradient = True
  277. return (tx, ty, tw, th, tscale, tobj, tcls)
  278. def _calc_obj_loss(self, output, obj, tobj, gt_box, batch_size, anchors,
  279. num_classes, downsample, ignore_thresh, scale_x_y):
  280. # A prediction bbox overlap any gt_bbox over ignore_thresh,
  281. # objectness loss will be ignored, process as follows:
  282. # 1. get pred bbox, which is same with YOLOv3 infer mode, use yolo_box here
  283. # NOTE: img_size is set as 1.0 to get noramlized pred bbox
  284. bbox, prob = fluid.layers.yolo_box(
  285. x=output,
  286. img_size=fluid.layers.ones(
  287. shape=[batch_size, 2], dtype="int32"),
  288. anchors=anchors,
  289. class_num=num_classes,
  290. conf_thresh=0.,
  291. downsample_ratio=downsample,
  292. clip_bbox=False,
  293. scale_x_y=scale_x_y)
  294. # 2. split pred bbox and gt bbox by sample, calculate IoU between pred bbox
  295. # and gt bbox in each sample
  296. if batch_size > 1:
  297. preds = fluid.layers.split(bbox, batch_size, dim=0)
  298. gts = fluid.layers.split(gt_box, batch_size, dim=0)
  299. else:
  300. preds = [bbox]
  301. gts = [gt_box]
  302. probs = [prob]
  303. ious = []
  304. for pred, gt in zip(preds, gts):
  305. def box_xywh2xyxy(box):
  306. x = box[:, 0]
  307. y = box[:, 1]
  308. w = box[:, 2]
  309. h = box[:, 3]
  310. return fluid.layers.stack(
  311. [
  312. x - w / 2.,
  313. y - h / 2.,
  314. x + w / 2.,
  315. y + h / 2.,
  316. ], axis=1)
  317. pred = fluid.layers.squeeze(pred, axes=[0])
  318. gt = box_xywh2xyxy(fluid.layers.squeeze(gt, axes=[0]))
  319. ious.append(fluid.layers.iou_similarity(pred, gt))
  320. iou = fluid.layers.stack(ious, axis=0)
  321. # 3. Get iou_mask by IoU between gt bbox and prediction bbox,
  322. # Get obj_mask by tobj(holds gt_score), calculate objectness loss
  323. max_iou = fluid.layers.reduce_max(iou, dim=-1)
  324. iou_mask = fluid.layers.cast(max_iou <= ignore_thresh, dtype="float32")
  325. if self.match_score:
  326. max_prob = fluid.layers.reduce_max(prob, dim=-1)
  327. iou_mask = iou_mask * fluid.layers.cast(
  328. max_prob <= 0.25, dtype="float32")
  329. output_shape = fluid.layers.shape(output)
  330. an_num = len(anchors) // 2
  331. iou_mask = fluid.layers.reshape(iou_mask, (-1, an_num, output_shape[2],
  332. output_shape[3]))
  333. iou_mask.stop_gradient = True
  334. # NOTE: tobj holds gt_score, obj_mask holds object existence mask
  335. obj_mask = fluid.layers.cast(tobj > 0., dtype="float32")
  336. obj_mask.stop_gradient = True
  337. # For positive objectness grids, objectness loss should be calculated
  338. # For negative objectness grids, objectness loss is calculated only iou_mask == 1.0
  339. loss_obj = fluid.layers.sigmoid_cross_entropy_with_logits(obj,
  340. obj_mask)
  341. loss_obj_pos = fluid.layers.reduce_sum(loss_obj * tobj, dim=[1, 2, 3])
  342. loss_obj_neg = fluid.layers.reduce_sum(
  343. loss_obj * (1.0 - obj_mask) * iou_mask, dim=[1, 2, 3])
  344. return loss_obj_pos, loss_obj_neg