yolo.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # Copyright (c) 2019 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. from collections import OrderedDict
  18. from paddle import fluid
  19. from ppdet.experimental import mixed_precision_global_state
  20. from ppdet.core.workspace import register
  21. __all__ = ['YOLOv3', 'YOLOv4']
  22. @register
  23. class YOLOv3(object):
  24. """
  25. YOLOv3 network, see https://arxiv.org/abs/1804.02767
  26. Args:
  27. backbone (object): an backbone instance
  28. yolo_head (object): an `YOLOv3Head` instance
  29. """
  30. __category__ = 'architecture'
  31. __inject__ = ['backbone', 'yolo_head']
  32. __shared__ = ['use_fine_grained_loss']
  33. def __init__(self,
  34. backbone,
  35. yolo_head='YOLOv3Head',
  36. use_fine_grained_loss=False):
  37. super(YOLOv3, self).__init__()
  38. self.backbone = backbone
  39. self.yolo_head = yolo_head
  40. self.use_fine_grained_loss = use_fine_grained_loss
  41. def build(self, feed_vars, mode='train', exclude_nms=False):
  42. im = feed_vars['image']
  43. mixed_precision_enabled = mixed_precision_global_state() is not None
  44. # cast inputs to FP16
  45. if mixed_precision_enabled:
  46. im = fluid.layers.cast(im, 'float16')
  47. body_feats = self.backbone(im)
  48. if isinstance(body_feats, OrderedDict):
  49. body_feat_names = list(body_feats.keys())
  50. body_feats = [body_feats[name] for name in body_feat_names]
  51. # cast features back to FP32
  52. if mixed_precision_enabled:
  53. body_feats = [fluid.layers.cast(v, 'float32') for v in body_feats]
  54. if mode == 'train':
  55. gt_bbox = feed_vars['gt_bbox']
  56. gt_class = feed_vars['gt_class']
  57. gt_score = feed_vars['gt_score']
  58. # Get targets for splited yolo loss calculation
  59. num_output_layer = len(self.yolo_head.anchor_masks)
  60. targets = []
  61. for i in range(num_output_layer):
  62. k = 'target{}'.format(i)
  63. if k in feed_vars:
  64. targets.append(feed_vars[k])
  65. loss = self.yolo_head.get_loss(body_feats, gt_bbox, gt_class,
  66. gt_score, targets)
  67. total_loss = fluid.layers.sum(list(loss.values()))
  68. loss.update({'loss': total_loss})
  69. return loss
  70. else:
  71. im_size = feed_vars['im_size']
  72. # exclude_nms only for benchmark, postprocess(NMS) is not needed
  73. return self.yolo_head.get_prediction(
  74. body_feats, im_size, exclude_nms=exclude_nms)
  75. def _inputs_def(self, image_shape, num_max_boxes):
  76. im_shape = [None] + image_shape
  77. # yapf: disable
  78. inputs_def = {
  79. 'image': {'shape': im_shape, 'dtype': 'float32', 'lod_level': 0},
  80. 'im_size': {'shape': [None, 2], 'dtype': 'int32', 'lod_level': 0},
  81. 'im_id': {'shape': [None, 1], 'dtype': 'int64', 'lod_level': 0},
  82. 'gt_bbox': {'shape': [None, num_max_boxes, 4], 'dtype': 'float32', 'lod_level': 0},
  83. 'gt_class': {'shape': [None, num_max_boxes], 'dtype': 'int32', 'lod_level': 0},
  84. 'gt_score': {'shape': [None, num_max_boxes], 'dtype': 'float32', 'lod_level': 0},
  85. 'is_difficult': {'shape': [None, num_max_boxes],'dtype': 'int32', 'lod_level': 0},
  86. }
  87. # yapf: enable
  88. if self.use_fine_grained_loss:
  89. # yapf: disable
  90. num_output_layer = len(self.yolo_head.anchor_masks)
  91. targets_def = {}
  92. for i in range(num_output_layer):
  93. targets_def['target{}'.format(i)] = {'shape': [None, 3, None, None, None], 'dtype': 'float32', 'lod_level': 0}
  94. # yapf: enable
  95. downsample = 32
  96. for k, mask in zip(targets_def.keys(), self.yolo_head.anchor_masks):
  97. targets_def[k]['shape'][1] = len(mask)
  98. targets_def[k]['shape'][2] = 6 + self.yolo_head.num_classes
  99. targets_def[k]['shape'][3] = image_shape[
  100. -2] // downsample if image_shape[-2] else None
  101. targets_def[k]['shape'][4] = image_shape[
  102. -1] // downsample if image_shape[-1] else None
  103. downsample //= 2
  104. inputs_def.update(targets_def)
  105. return inputs_def
  106. def build_inputs(
  107. self,
  108. image_shape=[3, None, None],
  109. fields=['image', 'gt_bbox', 'gt_class', 'gt_score'], # for train
  110. num_max_boxes=50,
  111. use_dataloader=True,
  112. iterable=False):
  113. inputs_def = self._inputs_def(image_shape, num_max_boxes)
  114. # if fields has im_size, this is in eval/infer mode, fine grained loss
  115. # will be disabled for YOLOv3 architecture do not calculate loss in
  116. # eval/infer mode.
  117. if 'im_size' not in fields and self.use_fine_grained_loss:
  118. num_output_layer = len(self.yolo_head.anchor_masks)
  119. fields.extend(
  120. ['target{}'.format(i) for i in range(num_output_layer)])
  121. feed_vars = OrderedDict([(key, fluid.data(
  122. name=key,
  123. shape=inputs_def[key]['shape'],
  124. dtype=inputs_def[key]['dtype'],
  125. lod_level=inputs_def[key]['lod_level'])) for key in fields])
  126. loader = fluid.io.DataLoader.from_generator(
  127. feed_list=list(feed_vars.values()),
  128. capacity=16,
  129. use_double_buffer=True,
  130. iterable=iterable) if use_dataloader else None
  131. return feed_vars, loader
  132. def train(self, feed_vars):
  133. return self.build(feed_vars, mode='train')
  134. def eval(self, feed_vars):
  135. return self.build(feed_vars, mode='test')
  136. def test(self, feed_vars, exclude_nms=False):
  137. return self.build(feed_vars, mode='test', exclude_nms=exclude_nms)
  138. @register
  139. class YOLOv4(YOLOv3):
  140. """
  141. YOLOv4 network, see https://arxiv.org/abs/2004.10934
  142. Args:
  143. backbone (object): an backbone instance
  144. yolo_head (object): an `YOLOv4Head` instance
  145. """
  146. __category__ = 'architecture'
  147. __inject__ = ['backbone', 'yolo_head']
  148. __shared__ = ['use_fine_grained_loss']
  149. def __init__(self,
  150. backbone,
  151. yolo_head='YOLOv4Head',
  152. use_fine_grained_loss=False):
  153. super(YOLOv4, self).__init__(
  154. backbone=backbone,
  155. yolo_head=yolo_head,
  156. use_fine_grained_loss=use_fine_grained_loss)