resnet.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # Copyright (c) 2022 NVIDIA Corporation. 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 math
  15. import paddle
  16. from paddle import ParamAttr
  17. import paddle.nn as nn
  18. from paddle.nn import Conv2D, BatchNorm, Linear
  19. from paddle.nn import AdaptiveAvgPool2D, MaxPool2D, AvgPool2D
  20. from paddle.nn.initializer import Uniform, Constant, KaimingNormal
  21. MODELS = ["ResNet50"]
  22. __all__ = MODELS
  23. class ConvBNLayer(nn.Layer):
  24. def __init__(self,
  25. num_channels,
  26. num_filters,
  27. filter_size,
  28. stride=1,
  29. groups=1,
  30. act=None,
  31. lr_mult=1.0,
  32. data_format="NCHW",
  33. bn_weight_decay=True):
  34. super().__init__()
  35. self.act = act
  36. self.avg_pool = AvgPool2D(
  37. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  38. self.conv = Conv2D(
  39. in_channels=num_channels,
  40. out_channels=num_filters,
  41. kernel_size=filter_size,
  42. stride=stride,
  43. padding=(filter_size - 1) // 2,
  44. groups=groups,
  45. weight_attr=ParamAttr(
  46. learning_rate=lr_mult, initializer=KaimingNormal()),
  47. bias_attr=False,
  48. data_format=data_format)
  49. self.bn = BatchNorm(
  50. num_filters,
  51. param_attr=ParamAttr(
  52. learning_rate=lr_mult,
  53. regularizer=None
  54. if bn_weight_decay else paddle.regularizer.L2Decay(0.0),
  55. initializer=Constant(1.0)),
  56. bias_attr=ParamAttr(
  57. learning_rate=lr_mult,
  58. regularizer=None
  59. if bn_weight_decay else paddle.regularizer.L2Decay(0.0),
  60. initializer=Constant(0.0)),
  61. data_layout=data_format)
  62. self.relu = nn.ReLU()
  63. def forward(self, x):
  64. x = self.conv(x)
  65. x = self.bn(x)
  66. if self.act:
  67. x = self.relu(x)
  68. return x
  69. class BottleneckBlock(nn.Layer):
  70. def __init__(self,
  71. num_channels,
  72. num_filters,
  73. stride,
  74. shortcut=True,
  75. lr_mult=1.0,
  76. data_format="NCHW",
  77. bn_weight_decay=True):
  78. super().__init__()
  79. self.conv0 = ConvBNLayer(
  80. num_channels=num_channels,
  81. num_filters=num_filters,
  82. filter_size=1,
  83. act="relu",
  84. lr_mult=lr_mult,
  85. data_format=data_format,
  86. bn_weight_decay=bn_weight_decay)
  87. self.conv1 = ConvBNLayer(
  88. num_channels=num_filters,
  89. num_filters=num_filters,
  90. filter_size=3,
  91. stride=stride,
  92. act="relu",
  93. lr_mult=lr_mult,
  94. data_format=data_format,
  95. bn_weight_decay=bn_weight_decay)
  96. self.conv2 = ConvBNLayer(
  97. num_channels=num_filters,
  98. num_filters=num_filters * 4,
  99. filter_size=1,
  100. act=None,
  101. lr_mult=lr_mult,
  102. data_format=data_format,
  103. bn_weight_decay=bn_weight_decay)
  104. if not shortcut:
  105. self.short = ConvBNLayer(
  106. num_channels=num_channels,
  107. num_filters=num_filters * 4,
  108. filter_size=1,
  109. stride=stride,
  110. lr_mult=lr_mult,
  111. data_format=data_format,
  112. bn_weight_decay=bn_weight_decay)
  113. self.relu = nn.ReLU()
  114. self.shortcut = shortcut
  115. def forward(self, x):
  116. identity = x
  117. x = self.conv0(x)
  118. x = self.conv1(x)
  119. x = self.conv2(x)
  120. if self.shortcut:
  121. short = identity
  122. else:
  123. short = self.short(identity)
  124. x = paddle.add(x=x, y=short)
  125. x = self.relu(x)
  126. return x
  127. class ResNet(nn.Layer):
  128. def __init__(self,
  129. class_num=1000,
  130. data_format="NCHW",
  131. input_image_channel=3,
  132. use_pure_fp16=False,
  133. bn_weight_decay=True):
  134. super().__init__()
  135. self.class_num = class_num
  136. self.num_filters = [64, 128, 256, 512]
  137. self.block_depth = [3, 4, 6, 3]
  138. self.num_channels = [64, 256, 512, 1024]
  139. self.channels_mult = 1 if self.num_channels[-1] == 256 else 4
  140. self.use_pure_fp16 = use_pure_fp16
  141. self.stem_cfg = {
  142. #num_channels, num_filters, filter_size, stride
  143. "vb": [[input_image_channel, 64, 7, 2]],
  144. }
  145. self.stem = nn.Sequential(* [
  146. ConvBNLayer(
  147. num_channels=in_c,
  148. num_filters=out_c,
  149. filter_size=k,
  150. stride=s,
  151. act="relu",
  152. data_format=data_format,
  153. bn_weight_decay=bn_weight_decay)
  154. for in_c, out_c, k, s in self.stem_cfg['vb']
  155. ])
  156. self.max_pool = MaxPool2D(
  157. kernel_size=3, stride=2, padding=1, data_format=data_format)
  158. block_list = []
  159. for block_idx in range(len(self.block_depth)):
  160. shortcut = False
  161. for i in range(self.block_depth[block_idx]):
  162. block_list.append(
  163. BottleneckBlock(
  164. num_channels=self.num_channels[block_idx] if i == 0
  165. else self.num_filters[block_idx] * self.channels_mult,
  166. num_filters=self.num_filters[block_idx],
  167. stride=2 if i == 0 and block_idx != 0 else 1,
  168. shortcut=shortcut,
  169. data_format=data_format,
  170. bn_weight_decay=bn_weight_decay))
  171. shortcut = True
  172. self.blocks = nn.Sequential(*block_list)
  173. self.avg_pool = AdaptiveAvgPool2D(1, data_format=data_format)
  174. self.flatten = nn.Flatten()
  175. self.avg_pool_channels = self.num_channels[-1] * 2
  176. stdv = 1.0 / math.sqrt(self.avg_pool_channels * 1.0)
  177. self.fc = Linear(
  178. self.avg_pool_channels,
  179. self.class_num,
  180. weight_attr=ParamAttr(initializer=Uniform(-stdv, stdv)))
  181. def forward(self, x):
  182. if self.use_pure_fp16:
  183. with paddle.static.amp.fp16_guard():
  184. x = self.stem(x)
  185. x = self.max_pool(x)
  186. x = self.blocks(x)
  187. x = self.avg_pool(x)
  188. x = self.flatten(x)
  189. x = self.fc(x)
  190. else:
  191. x = self.stem(x)
  192. x = self.max_pool(x)
  193. x = self.blocks(x)
  194. x = self.avg_pool(x)
  195. x = self.flatten(x)
  196. x = self.fc(x)
  197. return x
  198. def ResNet50(**kwargs):
  199. model = ResNet(**kwargs)
  200. return model