ssd_head.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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. import paddle
  15. import paddle.nn as nn
  16. import paddle.nn.functional as F
  17. from ppdet.core.workspace import register
  18. from paddle.regularizer import L2Decay
  19. from paddle import ParamAttr
  20. from ..layers import AnchorGeneratorSSD
  21. class SepConvLayer(nn.Layer):
  22. def __init__(self,
  23. in_channels,
  24. out_channels,
  25. kernel_size=3,
  26. padding=1,
  27. conv_decay=0.):
  28. super(SepConvLayer, self).__init__()
  29. self.dw_conv = nn.Conv2D(
  30. in_channels=in_channels,
  31. out_channels=in_channels,
  32. kernel_size=kernel_size,
  33. stride=1,
  34. padding=padding,
  35. groups=in_channels,
  36. weight_attr=ParamAttr(regularizer=L2Decay(conv_decay)),
  37. bias_attr=False)
  38. self.bn = nn.BatchNorm2D(
  39. in_channels,
  40. weight_attr=ParamAttr(regularizer=L2Decay(0.)),
  41. bias_attr=ParamAttr(regularizer=L2Decay(0.)))
  42. self.pw_conv = nn.Conv2D(
  43. in_channels=in_channels,
  44. out_channels=out_channels,
  45. kernel_size=1,
  46. stride=1,
  47. padding=0,
  48. weight_attr=ParamAttr(regularizer=L2Decay(conv_decay)),
  49. bias_attr=False)
  50. def forward(self, x):
  51. x = self.dw_conv(x)
  52. x = F.relu6(self.bn(x))
  53. x = self.pw_conv(x)
  54. return x
  55. class SSDExtraHead(nn.Layer):
  56. def __init__(self,
  57. in_channels=256,
  58. out_channels=([256, 512], [256, 512], [128, 256], [128, 256],
  59. [128, 256]),
  60. strides=(2, 2, 2, 1, 1),
  61. paddings=(1, 1, 1, 0, 0)):
  62. super(SSDExtraHead, self).__init__()
  63. self.convs = nn.LayerList()
  64. for out_channel, stride, padding in zip(out_channels, strides,
  65. paddings):
  66. self.convs.append(
  67. self._make_layers(in_channels, out_channel[0], out_channel[1],
  68. stride, padding))
  69. in_channels = out_channel[-1]
  70. def _make_layers(self, c_in, c_hidden, c_out, stride_3x3, padding_3x3):
  71. return nn.Sequential(
  72. nn.Conv2D(c_in, c_hidden, 1),
  73. nn.ReLU(),
  74. nn.Conv2D(c_hidden, c_out, 3, stride_3x3, padding_3x3), nn.ReLU())
  75. def forward(self, x):
  76. out = [x]
  77. for conv_layer in self.convs:
  78. out.append(conv_layer(out[-1]))
  79. return out
  80. @register
  81. class SSDHead(nn.Layer):
  82. """
  83. SSDHead
  84. Args:
  85. num_classes (int): Number of classes
  86. in_channels (list): Number of channels per input feature
  87. anchor_generator (dict): Configuration of 'AnchorGeneratorSSD' instance
  88. kernel_size (int): Conv kernel size
  89. padding (int): Conv padding
  90. use_sepconv (bool): Use SepConvLayer if true
  91. conv_decay (float): Conv regularization coeff
  92. loss (object): 'SSDLoss' instance
  93. use_extra_head (bool): If use ResNet34 as baskbone, you should set `use_extra_head`=True
  94. """
  95. __shared__ = ['num_classes']
  96. __inject__ = ['anchor_generator', 'loss']
  97. def __init__(self,
  98. num_classes=80,
  99. in_channels=(512, 1024, 512, 256, 256, 256),
  100. anchor_generator=AnchorGeneratorSSD().__dict__,
  101. kernel_size=3,
  102. padding=1,
  103. use_sepconv=False,
  104. conv_decay=0.,
  105. loss='SSDLoss',
  106. use_extra_head=False):
  107. super(SSDHead, self).__init__()
  108. # add background class
  109. self.num_classes = num_classes + 1
  110. self.in_channels = in_channels
  111. self.anchor_generator = anchor_generator
  112. self.loss = loss
  113. self.use_extra_head = use_extra_head
  114. if self.use_extra_head:
  115. self.ssd_extra_head = SSDExtraHead()
  116. self.in_channels = [256, 512, 512, 256, 256, 256]
  117. if isinstance(anchor_generator, dict):
  118. self.anchor_generator = AnchorGeneratorSSD(**anchor_generator)
  119. self.num_priors = self.anchor_generator.num_priors
  120. self.box_convs = []
  121. self.score_convs = []
  122. for i, num_prior in enumerate(self.num_priors):
  123. box_conv_name = "boxes{}".format(i)
  124. if not use_sepconv:
  125. box_conv = self.add_sublayer(
  126. box_conv_name,
  127. nn.Conv2D(
  128. in_channels=self.in_channels[i],
  129. out_channels=num_prior * 4,
  130. kernel_size=kernel_size,
  131. padding=padding))
  132. else:
  133. box_conv = self.add_sublayer(
  134. box_conv_name,
  135. SepConvLayer(
  136. in_channels=self.in_channels[i],
  137. out_channels=num_prior * 4,
  138. kernel_size=kernel_size,
  139. padding=padding,
  140. conv_decay=conv_decay))
  141. self.box_convs.append(box_conv)
  142. score_conv_name = "scores{}".format(i)
  143. if not use_sepconv:
  144. score_conv = self.add_sublayer(
  145. score_conv_name,
  146. nn.Conv2D(
  147. in_channels=self.in_channels[i],
  148. out_channels=num_prior * self.num_classes,
  149. kernel_size=kernel_size,
  150. padding=padding))
  151. else:
  152. score_conv = self.add_sublayer(
  153. score_conv_name,
  154. SepConvLayer(
  155. in_channels=self.in_channels[i],
  156. out_channels=num_prior * self.num_classes,
  157. kernel_size=kernel_size,
  158. padding=padding,
  159. conv_decay=conv_decay))
  160. self.score_convs.append(score_conv)
  161. @classmethod
  162. def from_config(cls, cfg, input_shape):
  163. return {'in_channels': [i.channels for i in input_shape], }
  164. def forward(self, feats, image, gt_bbox=None, gt_class=None):
  165. if self.use_extra_head:
  166. assert len(feats) == 1, \
  167. ("If you set use_extra_head=True, backbone feature "
  168. "list length should be 1.")
  169. feats = self.ssd_extra_head(feats[0])
  170. box_preds = []
  171. cls_scores = []
  172. for feat, box_conv, score_conv in zip(feats, self.box_convs,
  173. self.score_convs):
  174. box_pred = box_conv(feat)
  175. box_pred = paddle.transpose(box_pred, [0, 2, 3, 1])
  176. box_pred = paddle.reshape(box_pred, [0, -1, 4])
  177. box_preds.append(box_pred)
  178. cls_score = score_conv(feat)
  179. cls_score = paddle.transpose(cls_score, [0, 2, 3, 1])
  180. cls_score = paddle.reshape(cls_score, [0, -1, self.num_classes])
  181. cls_scores.append(cls_score)
  182. prior_boxes = self.anchor_generator(feats, image)
  183. if self.training:
  184. return self.get_loss(box_preds, cls_scores, gt_bbox, gt_class,
  185. prior_boxes)
  186. else:
  187. return (box_preds, cls_scores), prior_boxes
  188. def get_loss(self, boxes, scores, gt_bbox, gt_class, prior_boxes):
  189. return self.loss(boxes, scores, gt_bbox, gt_class, prior_boxes)