se_resnext_vd.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. # copyright (c) 2020 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 numpy as np
  18. import paddle
  19. from paddle import ParamAttr
  20. import paddle.nn as nn
  21. import paddle.nn.functional as F
  22. from paddle.nn import Conv2D, BatchNorm, Linear, Dropout
  23. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  24. from paddle.nn.initializer import Uniform
  25. import math
  26. __all__ = ["SE_ResNeXt50_vd_32x4d", "SE_ResNeXt50_vd_32x4d", "SENet154_vd"]
  27. class ConvBNLayer(nn.Layer):
  28. def __init__(self,
  29. num_channels,
  30. num_filters,
  31. filter_size,
  32. stride=1,
  33. groups=1,
  34. is_vd_mode=False,
  35. act=None,
  36. name=None):
  37. super(ConvBNLayer, self).__init__()
  38. self.is_vd_mode = is_vd_mode
  39. self._pool2d_avg = AvgPool2D(
  40. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  41. self._conv = Conv2D(
  42. in_channels=num_channels,
  43. out_channels=num_filters,
  44. kernel_size=filter_size,
  45. stride=stride,
  46. padding=(filter_size - 1) // 2,
  47. groups=groups,
  48. weight_attr=ParamAttr(name=name + "_weights"),
  49. bias_attr=False)
  50. bn_name = name + '_bn'
  51. self._batch_norm = BatchNorm(
  52. num_filters,
  53. act=act,
  54. param_attr=ParamAttr(name=bn_name + '_scale'),
  55. bias_attr=ParamAttr(bn_name + '_offset'),
  56. moving_mean_name=bn_name + '_mean',
  57. moving_variance_name=bn_name + '_variance')
  58. def forward(self, inputs):
  59. if self.is_vd_mode:
  60. inputs = self._pool2d_avg(inputs)
  61. y = self._conv(inputs)
  62. y = self._batch_norm(y)
  63. return y
  64. class BottleneckBlock(nn.Layer):
  65. def __init__(self,
  66. num_channels,
  67. num_filters,
  68. stride,
  69. cardinality,
  70. reduction_ratio,
  71. shortcut=True,
  72. if_first=False,
  73. name=None):
  74. super(BottleneckBlock, self).__init__()
  75. self.conv0 = ConvBNLayer(
  76. num_channels=num_channels,
  77. num_filters=num_filters,
  78. filter_size=1,
  79. act='relu',
  80. name='conv' + name + '_x1')
  81. self.conv1 = ConvBNLayer(
  82. num_channels=num_filters,
  83. num_filters=num_filters,
  84. filter_size=3,
  85. groups=cardinality,
  86. stride=stride,
  87. act='relu',
  88. name='conv' + name + '_x2')
  89. self.conv2 = ConvBNLayer(
  90. num_channels=num_filters,
  91. num_filters=num_filters * 2 if cardinality == 32 else num_filters,
  92. filter_size=1,
  93. act=None,
  94. name='conv' + name + '_x3')
  95. self.scale = SELayer(
  96. num_channels=num_filters * 2 if cardinality == 32 else num_filters,
  97. num_filters=num_filters * 2 if cardinality == 32 else num_filters,
  98. reduction_ratio=reduction_ratio,
  99. name='fc' + name)
  100. if not shortcut:
  101. self.short = ConvBNLayer(
  102. num_channels=num_channels,
  103. num_filters=num_filters * 2
  104. if cardinality == 32 else num_filters,
  105. filter_size=1,
  106. stride=1,
  107. is_vd_mode=False if if_first else True,
  108. name='conv' + name + '_prj')
  109. self.shortcut = shortcut
  110. def forward(self, inputs):
  111. y = self.conv0(inputs)
  112. conv1 = self.conv1(y)
  113. conv2 = self.conv2(conv1)
  114. scale = self.scale(conv2)
  115. if self.shortcut:
  116. short = inputs
  117. else:
  118. short = self.short(inputs)
  119. y = paddle.add(x=short, y=scale)
  120. y = F.relu(y)
  121. return y
  122. class SELayer(nn.Layer):
  123. def __init__(self, num_channels, num_filters, reduction_ratio, name=None):
  124. super(SELayer, self).__init__()
  125. self.pool2d_gap = AdaptiveAvgPool2D(1)
  126. self._num_channels = num_channels
  127. med_ch = int(num_channels / reduction_ratio)
  128. stdv = 1.0 / math.sqrt(num_channels * 1.0)
  129. self.squeeze = Linear(
  130. num_channels,
  131. med_ch,
  132. weight_attr=ParamAttr(
  133. initializer=Uniform(-stdv, stdv), name=name + "_sqz_weights"),
  134. bias_attr=ParamAttr(name=name + '_sqz_offset'))
  135. self.relu = nn.ReLU()
  136. stdv = 1.0 / math.sqrt(med_ch * 1.0)
  137. self.excitation = Linear(
  138. med_ch,
  139. num_filters,
  140. weight_attr=ParamAttr(
  141. initializer=Uniform(-stdv, stdv), name=name + "_exc_weights"),
  142. bias_attr=ParamAttr(name=name + '_exc_offset'))
  143. self.sigmoid = nn.Sigmoid()
  144. def forward(self, input):
  145. pool = self.pool2d_gap(input)
  146. pool = paddle.squeeze(pool, axis=[2, 3])
  147. squeeze = self.squeeze(pool)
  148. squeeze = self.relu(squeeze)
  149. excitation = self.excitation(squeeze)
  150. excitation = self.sigmoid(excitation)
  151. excitation = paddle.unsqueeze(excitation, axis=[2, 3])
  152. out = paddle.multiply(input, excitation)
  153. return out
  154. class ResNeXt(nn.Layer):
  155. def __init__(self, layers=50, class_dim=1000, cardinality=32):
  156. super(ResNeXt, self).__init__()
  157. self.layers = layers
  158. self.cardinality = cardinality
  159. self.reduction_ratio = 16
  160. supported_layers = [50, 101, 152]
  161. assert layers in supported_layers, \
  162. "supported layers are {} but input layer is {}".format(
  163. supported_layers, layers)
  164. supported_cardinality = [32, 64]
  165. assert cardinality in supported_cardinality, \
  166. "supported cardinality is {} but input cardinality is {}" \
  167. .format(supported_cardinality, cardinality)
  168. if layers == 50:
  169. depth = [3, 4, 6, 3]
  170. elif layers == 101:
  171. depth = [3, 4, 23, 3]
  172. elif layers == 152:
  173. depth = [3, 8, 36, 3]
  174. num_channels = [128, 256, 512, 1024]
  175. num_filters = [128, 256, 512,
  176. 1024] if cardinality == 32 else [256, 512, 1024, 2048]
  177. self.conv1_1 = ConvBNLayer(
  178. num_channels=3,
  179. num_filters=64,
  180. filter_size=3,
  181. stride=2,
  182. act='relu',
  183. name="conv1_1")
  184. self.conv1_2 = ConvBNLayer(
  185. num_channels=64,
  186. num_filters=64,
  187. filter_size=3,
  188. stride=1,
  189. act='relu',
  190. name="conv1_2")
  191. self.conv1_3 = ConvBNLayer(
  192. num_channels=64,
  193. num_filters=128,
  194. filter_size=3,
  195. stride=1,
  196. act='relu',
  197. name="conv1_3")
  198. self.pool2d_max = MaxPool2D(kernel_size=3, stride=2, padding=1)
  199. self.block_list = []
  200. n = 1 if layers == 50 or layers == 101 else 3
  201. for block in range(len(depth)):
  202. n += 1
  203. shortcut = False
  204. for i in range(depth[block]):
  205. bottleneck_block = self.add_sublayer(
  206. 'bb_%d_%d' % (block, i),
  207. BottleneckBlock(
  208. num_channels=num_channels[block] if i == 0 else
  209. num_filters[block] * int(64 // self.cardinality),
  210. num_filters=num_filters[block],
  211. stride=2 if i == 0 and block != 0 else 1,
  212. cardinality=self.cardinality,
  213. reduction_ratio=self.reduction_ratio,
  214. shortcut=shortcut,
  215. if_first=block == 0,
  216. name=str(n) + '_' + str(i + 1)))
  217. self.block_list.append(bottleneck_block)
  218. shortcut = True
  219. self.pool2d_avg = AdaptiveAvgPool2D(1)
  220. self.pool2d_avg_channels = num_channels[-1] * 2
  221. stdv = 1.0 / math.sqrt(self.pool2d_avg_channels * 1.0)
  222. self.out = Linear(
  223. self.pool2d_avg_channels,
  224. class_dim,
  225. weight_attr=ParamAttr(
  226. initializer=Uniform(-stdv, stdv), name="fc6_weights"),
  227. bias_attr=ParamAttr(name="fc6_offset"))
  228. def forward(self, inputs):
  229. y = self.conv1_1(inputs)
  230. y = self.conv1_2(y)
  231. y = self.conv1_3(y)
  232. y = self.pool2d_max(y)
  233. for block in self.block_list:
  234. y = block(y)
  235. y = self.pool2d_avg(y)
  236. y = paddle.reshape(y, shape=[-1, self.pool2d_avg_channels])
  237. y = self.out(y)
  238. return y
  239. def SE_ResNeXt50_vd_32x4d(**args):
  240. model = ResNeXt(layers=50, cardinality=32, **args)
  241. return model
  242. def SE_ResNeXt101_vd_32x4d(**args):
  243. model = ResNeXt(layers=101, cardinality=32, **args)
  244. return model
  245. def SENet154_vd(**args):
  246. model = ResNeXt(layers=152, cardinality=64, **args)
  247. return model