darknet.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. bn_param_attr = ParamAttr(
  64. regularizer=L2Decay(float(self.norm_decay)),
  65. name=bn_name + '.scale')
  66. bn_bias_attr = ParamAttr(
  67. regularizer=L2Decay(float(self.norm_decay)),
  68. name=bn_name + '.offset')
  69. out = fluid.layers.batch_norm(
  70. input=conv,
  71. param_attr=bn_param_attr,
  72. bias_attr=bn_bias_attr,
  73. moving_mean_name=bn_name + '.mean',
  74. moving_variance_name=bn_name + '.var')
  75. # leaky relu here has `alpha` as 0.1, can not be set by
  76. # `act` param in fluid.layers.batch_norm above.
  77. if act == 'leaky':
  78. out = fluid.layers.leaky_relu(x=out, alpha=0.1)
  79. if act == 'relu':
  80. out = fluid.layers.relu(x=out)
  81. return out
  82. def _downsample(self,
  83. input,
  84. ch_out,
  85. filter_size=3,
  86. stride=2,
  87. padding=1,
  88. name=None):
  89. return self._conv_norm(
  90. input,
  91. ch_out=ch_out,
  92. filter_size=filter_size,
  93. stride=stride,
  94. padding=padding,
  95. act=self.bn_act,
  96. name=name)
  97. def basicblock(self, input, ch_out, name=None):
  98. conv1 = self._conv_norm(
  99. input,
  100. ch_out=ch_out,
  101. filter_size=1,
  102. stride=1,
  103. padding=0,
  104. act=self.bn_act,
  105. name=name + ".0")
  106. conv2 = self._conv_norm(
  107. conv1,
  108. ch_out=ch_out * 2,
  109. filter_size=3,
  110. stride=1,
  111. padding=1,
  112. act=self.bn_act,
  113. name=name + ".1")
  114. out = fluid.layers.elementwise_add(x=input, y=conv2, act=None)
  115. return out
  116. def layer_warp(self, block_func, input, ch_out, count, name=None):
  117. out = block_func(input, ch_out=ch_out, name='{}.0'.format(name))
  118. for j in six.moves.xrange(1, count):
  119. out = block_func(out, ch_out=ch_out, name='{}.{}'.format(name, j))
  120. return out
  121. def __call__(self, input):
  122. """
  123. Get the backbone of DarkNet, that is output for the 5 stages.
  124. Args:
  125. input (Variable): input variable.
  126. Returns:
  127. The last variables of each stage.
  128. """
  129. stages, block_func = self.depth_cfg[self.depth]
  130. stages = stages[0:5]
  131. conv = self._conv_norm(
  132. input=input,
  133. ch_out=32,
  134. filter_size=3,
  135. stride=1,
  136. padding=1,
  137. act=self.bn_act,
  138. name=self.prefix_name + "yolo_input")
  139. downsample_ = self._downsample(
  140. input=conv,
  141. ch_out=conv.shape[1] * 2,
  142. name=self.prefix_name + "yolo_input.downsample")
  143. blocks = []
  144. for i, stage in enumerate(stages):
  145. block = self.layer_warp(
  146. block_func=block_func,
  147. input=downsample_,
  148. ch_out=32 * 2**i,
  149. count=stage,
  150. name=self.prefix_name + "stage.{}".format(i))
  151. blocks.append(block)
  152. if i < len(stages) - 1: # do not downsaple in the last stage
  153. downsample_ = self._downsample(
  154. input=block,
  155. ch_out=block.shape[1] * 2,
  156. name=self.prefix_name + "stage.{}.downsample".format(i))
  157. if self.num_classes is not None:
  158. pool = fluid.layers.pool2d(
  159. input=blocks[-1], pool_type='avg', global_pooling=True)
  160. stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0)
  161. out = fluid.layers.fc(
  162. input=pool,
  163. size=self.num_classes,
  164. param_attr=ParamAttr(
  165. initializer=fluid.initializer.Uniform(-stdv, stdv),
  166. name='fc_weights'),
  167. bias_attr=ParamAttr(name='fc_offset'))
  168. return out
  169. return blocks