densenet.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. # copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
  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 ParamAttr
  19. import paddle.nn as nn
  20. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  21. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  22. from paddle.nn.initializer import Uniform
  23. import math
  24. __all__ = [
  25. "DenseNet121", "DenseNet161", "DenseNet169", "DenseNet201", "DenseNet264"
  26. ]
  27. class BNACConvLayer(nn.Layer):
  28. def __init__(self,
  29. num_channels,
  30. num_filters,
  31. filter_size,
  32. stride=1,
  33. pad=0,
  34. groups=1,
  35. act="relu",
  36. name=None):
  37. super(BNACConvLayer, self).__init__()
  38. self._batch_norm = BatchNorm(
  39. num_channels,
  40. act=act,
  41. param_attr=ParamAttr(name=name + '_bn_scale'),
  42. bias_attr=ParamAttr(name + '_bn_offset'),
  43. moving_mean_name=name + '_bn_mean',
  44. moving_variance_name=name + '_bn_variance')
  45. self._conv = Conv2D(
  46. in_channels=num_channels,
  47. out_channels=num_filters,
  48. kernel_size=filter_size,
  49. stride=stride,
  50. padding=pad,
  51. groups=groups,
  52. weight_attr=ParamAttr(name=name + "_weights"),
  53. bias_attr=False)
  54. def forward(self, input):
  55. y = self._batch_norm(input)
  56. y = self._conv(y)
  57. return y
  58. class DenseLayer(nn.Layer):
  59. def __init__(self, num_channels, growth_rate, bn_size, dropout, name=None):
  60. super(DenseLayer, self).__init__()
  61. self.dropout = dropout
  62. self.bn_ac_func1 = BNACConvLayer(
  63. num_channels=num_channels,
  64. num_filters=bn_size * growth_rate,
  65. filter_size=1,
  66. pad=0,
  67. stride=1,
  68. name=name + "_x1")
  69. self.bn_ac_func2 = BNACConvLayer(
  70. num_channels=bn_size * growth_rate,
  71. num_filters=growth_rate,
  72. filter_size=3,
  73. pad=1,
  74. stride=1,
  75. name=name + "_x2")
  76. if dropout:
  77. self.dropout_func = Dropout(p=dropout, mode="downscale_in_infer")
  78. def forward(self, input):
  79. conv = self.bn_ac_func1(input)
  80. conv = self.bn_ac_func2(conv)
  81. if self.dropout:
  82. conv = self.dropout_func(conv)
  83. conv = paddle.concat([input, conv], axis=1)
  84. return conv
  85. class DenseBlock(nn.Layer):
  86. def __init__(self,
  87. num_channels,
  88. num_layers,
  89. bn_size,
  90. growth_rate,
  91. dropout,
  92. name=None):
  93. super(DenseBlock, self).__init__()
  94. self.dropout = dropout
  95. self.dense_layer_func = []
  96. pre_channel = num_channels
  97. for layer in range(num_layers):
  98. self.dense_layer_func.append(
  99. self.add_sublayer(
  100. "{}_{}".format(name, layer + 1),
  101. DenseLayer(
  102. num_channels=pre_channel,
  103. growth_rate=growth_rate,
  104. bn_size=bn_size,
  105. dropout=dropout,
  106. name=name + '_' + str(layer + 1))))
  107. pre_channel = pre_channel + growth_rate
  108. def forward(self, input):
  109. conv = input
  110. for func in self.dense_layer_func:
  111. conv = func(conv)
  112. return conv
  113. class TransitionLayer(nn.Layer):
  114. def __init__(self, num_channels, num_output_features, name=None):
  115. super(TransitionLayer, self).__init__()
  116. self.conv_ac_func = BNACConvLayer(
  117. num_channels=num_channels,
  118. num_filters=num_output_features,
  119. filter_size=1,
  120. pad=0,
  121. stride=1,
  122. name=name)
  123. self.pool2d_avg = AvgPool2D(kernel_size=2, stride=2, padding=0)
  124. def forward(self, input):
  125. y = self.conv_ac_func(input)
  126. y = self.pool2d_avg(y)
  127. return y
  128. class ConvBNLayer(nn.Layer):
  129. def __init__(self,
  130. num_channels,
  131. num_filters,
  132. filter_size,
  133. stride=1,
  134. pad=0,
  135. groups=1,
  136. act="relu",
  137. name=None):
  138. super(ConvBNLayer, self).__init__()
  139. self._conv = Conv2D(
  140. in_channels=num_channels,
  141. out_channels=num_filters,
  142. kernel_size=filter_size,
  143. stride=stride,
  144. padding=pad,
  145. groups=groups,
  146. weight_attr=ParamAttr(name=name + "_weights"),
  147. bias_attr=False)
  148. self._batch_norm = BatchNorm(
  149. num_filters,
  150. act=act,
  151. param_attr=ParamAttr(name=name + '_bn_scale'),
  152. bias_attr=ParamAttr(name + '_bn_offset'),
  153. moving_mean_name=name + '_bn_mean',
  154. moving_variance_name=name + '_bn_variance')
  155. def forward(self, input):
  156. y = self._conv(input)
  157. y = self._batch_norm(y)
  158. return y
  159. class DenseNet(nn.Layer):
  160. def __init__(self, layers=60, bn_size=4, dropout=0, class_dim=1000):
  161. super(DenseNet, self).__init__()
  162. supported_layers = [121, 161, 169, 201, 264]
  163. assert layers in supported_layers, \
  164. "supported layers are {} but input layer is {}".format(
  165. supported_layers, layers)
  166. densenet_spec = {
  167. 121: (64, 32, [6, 12, 24, 16]),
  168. 161: (96, 48, [6, 12, 36, 24]),
  169. 169: (64, 32, [6, 12, 32, 32]),
  170. 201: (64, 32, [6, 12, 48, 32]),
  171. 264: (64, 32, [6, 12, 64, 48])
  172. }
  173. num_init_features, growth_rate, block_config = densenet_spec[layers]
  174. self.conv1_func = ConvBNLayer(
  175. num_channels=3,
  176. num_filters=num_init_features,
  177. filter_size=7,
  178. stride=2,
  179. pad=3,
  180. act='relu',
  181. name="conv1")
  182. self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1)
  183. self.block_config = block_config
  184. self.dense_block_func_list = []
  185. self.transition_func_list = []
  186. pre_num_channels = num_init_features
  187. num_features = num_init_features
  188. for i, num_layers in enumerate(block_config):
  189. self.dense_block_func_list.append(
  190. self.add_sublayer(
  191. "db_conv_{}".format(i + 2),
  192. DenseBlock(
  193. num_channels=pre_num_channels,
  194. num_layers=num_layers,
  195. bn_size=bn_size,
  196. growth_rate=growth_rate,
  197. dropout=dropout,
  198. name='conv' + str(i + 2))))
  199. num_features = num_features + num_layers * growth_rate
  200. pre_num_channels = num_features
  201. if i != len(block_config) - 1:
  202. self.transition_func_list.append(
  203. self.add_sublayer(
  204. "tr_conv{}_blk".format(i + 2),
  205. TransitionLayer(
  206. num_channels=pre_num_channels,
  207. num_output_features=num_features // 2,
  208. name='conv' + str(i + 2) + "_blk")))
  209. pre_num_channels = num_features // 2
  210. num_features = num_features // 2
  211. self.batch_norm = BatchNorm(
  212. num_features,
  213. act="relu",
  214. param_attr=ParamAttr(name='conv5_blk_bn_scale'),
  215. bias_attr=ParamAttr(name='conv5_blk_bn_offset'),
  216. moving_mean_name='conv5_blk_bn_mean',
  217. moving_variance_name='conv5_blk_bn_variance')
  218. self.pool2d_avg = AdaptiveAvgPool2D(1)
  219. stdv = 1.0 / math.sqrt(num_features * 1.0)
  220. self.out = Linear(
  221. num_features,
  222. class_dim,
  223. weight_attr=ParamAttr(
  224. initializer=Uniform(-stdv, stdv), name="fc_weights"),
  225. bias_attr=ParamAttr(name="fc_offset"))
  226. def forward(self, input):
  227. conv = self.conv1_func(input)
  228. conv = self.pool2d_max(conv)
  229. for i, num_layers in enumerate(self.block_config):
  230. conv = self.dense_block_func_list[i](conv)
  231. if i != len(self.block_config) - 1:
  232. conv = self.transition_func_list[i](conv)
  233. conv = self.batch_norm(conv)
  234. y = self.pool2d_avg(conv)
  235. y = paddle.flatten(y, start_axis=1, stop_axis=-1)
  236. y = self.out(y)
  237. return y
  238. def DenseNet121(**args):
  239. model = DenseNet(layers=121, **args)
  240. return model
  241. def DenseNet161(**args):
  242. model = DenseNet(layers=161, **args)
  243. return model
  244. def DenseNet169(**args):
  245. model = DenseNet(layers=169, **args)
  246. return model
  247. def DenseNet201(**args):
  248. model = DenseNet(layers=201, **args)
  249. return model
  250. def DenseNet264(**args):
  251. model = DenseNet(layers=264, **args)
  252. return model