darknet.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. import six
  18. import math
  19. from paddle import fluid
  20. from paddle.fluid.param_attr import ParamAttr
  21. from paddle.fluid.regularizer import L2Decay
  22. class DarkNet(object):
  23. """
  24. DarkNet, see https://pjreddie.com/darknet/yolo/
  25. Args:
  26. depth (int): network depth, currently only darknet 53 is supported
  27. norm_type (str): normalization type, 'bn' and 'sync_bn' are supported
  28. norm_decay (float): weight decay for normalization layer weights
  29. """
  30. def __init__(self,
  31. depth=53,
  32. num_classes=None,
  33. norm_type='bn',
  34. norm_decay=0.,
  35. bn_act='leaky',
  36. weight_prefix_name=''):
  37. assert depth in [53], "unsupported depth value"
  38. self.depth = depth
  39. self.num_classes = num_classes
  40. self.norm_type = norm_type
  41. self.norm_decay = norm_decay
  42. self.depth_cfg = {53: ([1, 2, 8, 8, 4], self.basicblock)}
  43. self.bn_act = bn_act
  44. self.prefix_name = weight_prefix_name
  45. def _conv_norm(self,
  46. input,
  47. ch_out,
  48. filter_size,
  49. stride,
  50. padding,
  51. act='leaky',
  52. name=None):
  53. conv = fluid.layers.conv2d(
  54. input=input,
  55. num_filters=ch_out,
  56. filter_size=filter_size,
  57. stride=stride,
  58. padding=padding,
  59. act=None,
  60. param_attr=ParamAttr(name=name + ".conv.weights"),
  61. bias_attr=False)
  62. bn_name = name + ".bn"
  63. if self.num_classes:
  64. regularizer = None
  65. else:
  66. regularizer = L2Decay(float(self.norm_decay))
  67. bn_param_attr = ParamAttr(
  68. regularizer=regularizer, name=bn_name + '.scale')
  69. bn_bias_attr = ParamAttr(
  70. regularizer=regularizer, name=bn_name + '.offset')
  71. out = fluid.layers.batch_norm(
  72. input=conv,
  73. param_attr=bn_param_attr,
  74. bias_attr=bn_bias_attr,
  75. moving_mean_name=bn_name + '.mean',
  76. moving_variance_name=bn_name + '.var')
  77. # leaky relu here has `alpha` as 0.1, can not be set by
  78. # `act` param in fluid.layers.batch_norm above.
  79. if act == 'leaky':
  80. out = fluid.layers.leaky_relu(x=out, alpha=0.1)
  81. if act == 'relu':
  82. out = fluid.layers.relu(x=out)
  83. return out
  84. def _downsample(self,
  85. input,
  86. ch_out,
  87. filter_size=3,
  88. stride=2,
  89. padding=1,
  90. name=None):
  91. return self._conv_norm(
  92. input,
  93. ch_out=ch_out,
  94. filter_size=filter_size,
  95. stride=stride,
  96. padding=padding,
  97. act=self.bn_act,
  98. name=name)
  99. def basicblock(self, input, ch_out, name=None):
  100. conv1 = self._conv_norm(
  101. input,
  102. ch_out=ch_out,
  103. filter_size=1,
  104. stride=1,
  105. padding=0,
  106. act=self.bn_act,
  107. name=name + ".0")
  108. conv2 = self._conv_norm(
  109. conv1,
  110. ch_out=ch_out * 2,
  111. filter_size=3,
  112. stride=1,
  113. padding=1,
  114. act=self.bn_act,
  115. name=name + ".1")
  116. out = fluid.layers.elementwise_add(x=input, y=conv2, act=None)
  117. return out
  118. def layer_warp(self, block_func, input, ch_out, count, name=None):
  119. out = block_func(input, ch_out=ch_out, name='{}.0'.format(name))
  120. for j in six.moves.xrange(1, count):
  121. out = block_func(out, ch_out=ch_out, name='{}.{}'.format(name, j))
  122. return out
  123. def __call__(self, input):
  124. """
  125. Get the backbone of DarkNet, that is output for the 5 stages.
  126. Args:
  127. input (Variable): input variable.
  128. Returns:
  129. The last variables of each stage.
  130. """
  131. stages, block_func = self.depth_cfg[self.depth]
  132. stages = stages[0:5]
  133. conv = self._conv_norm(
  134. input=input,
  135. ch_out=32,
  136. filter_size=3,
  137. stride=1,
  138. padding=1,
  139. act=self.bn_act,
  140. name=self.prefix_name + "yolo_input")
  141. downsample_ = self._downsample(
  142. input=conv,
  143. ch_out=conv.shape[1] * 2,
  144. name=self.prefix_name + "yolo_input.downsample")
  145. blocks = []
  146. for i, stage in enumerate(stages):
  147. block = self.layer_warp(
  148. block_func=block_func,
  149. input=downsample_,
  150. ch_out=32 * 2**i,
  151. count=stage,
  152. name=self.prefix_name + "stage.{}".format(i))
  153. blocks.append(block)
  154. if i < len(stages) - 1: # do not downsaple in the last stage
  155. downsample_ = self._downsample(
  156. input=block,
  157. ch_out=block.shape[1] * 2,
  158. name=self.prefix_name + "stage.{}.downsample".format(i))
  159. if self.num_classes is not None:
  160. pool = fluid.layers.pool2d(
  161. input=blocks[-1], pool_type='avg', global_pooling=True)
  162. stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0)
  163. out = fluid.layers.fc(
  164. input=pool,
  165. size=self.num_classes,
  166. param_attr=ParamAttr(
  167. initializer=fluid.initializer.Uniform(-stdv, stdv),
  168. name='fc_weights'),
  169. bias_attr=ParamAttr(name='fc_offset'))
  170. return out
  171. return blocks