rec_resnet_31.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. """
  15. This code is refer from:
  16. https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/layers/conv_layer.py
  17. https://github.com/open-mmlab/mmocr/blob/main/mmocr/models/textrecog/backbones/resnet31_ocr.py
  18. """
  19. from __future__ import absolute_import
  20. from __future__ import division
  21. from __future__ import print_function
  22. import paddle
  23. from paddle import ParamAttr
  24. import paddle.nn as nn
  25. import paddle.nn.functional as F
  26. import numpy as np
  27. __all__ = ["ResNet31"]
  28. def conv3x3(in_channel, out_channel, stride=1, conv_weight_attr=None):
  29. return nn.Conv2D(
  30. in_channel,
  31. out_channel,
  32. kernel_size=3,
  33. stride=stride,
  34. padding=1,
  35. weight_attr=conv_weight_attr,
  36. bias_attr=False)
  37. class BasicBlock(nn.Layer):
  38. expansion = 1
  39. def __init__(self, in_channels, channels, stride=1, downsample=False, conv_weight_attr=None, bn_weight_attr=None):
  40. super().__init__()
  41. self.conv1 = conv3x3(in_channels, channels, stride,
  42. conv_weight_attr=conv_weight_attr)
  43. self.bn1 = nn.BatchNorm2D(channels, weight_attr=bn_weight_attr)
  44. self.relu = nn.ReLU()
  45. self.conv2 = conv3x3(channels, channels,
  46. conv_weight_attr=conv_weight_attr)
  47. self.bn2 = nn.BatchNorm2D(channels, weight_attr=bn_weight_attr)
  48. self.downsample = downsample
  49. if downsample:
  50. self.downsample = nn.Sequential(
  51. nn.Conv2D(
  52. in_channels,
  53. channels * self.expansion,
  54. 1,
  55. stride,
  56. weight_attr=conv_weight_attr,
  57. bias_attr=False),
  58. nn.BatchNorm2D(channels * self.expansion, weight_attr=bn_weight_attr))
  59. else:
  60. self.downsample = nn.Sequential()
  61. self.stride = stride
  62. def forward(self, x):
  63. residual = x
  64. out = self.conv1(x)
  65. out = self.bn1(out)
  66. out = self.relu(out)
  67. out = self.conv2(out)
  68. out = self.bn2(out)
  69. if self.downsample:
  70. residual = self.downsample(x)
  71. out += residual
  72. out = self.relu(out)
  73. return out
  74. class ResNet31(nn.Layer):
  75. '''
  76. Args:
  77. in_channels (int): Number of channels of input image tensor.
  78. layers (list[int]): List of BasicBlock number for each stage.
  79. channels (list[int]): List of out_channels of Conv2d layer.
  80. out_indices (None | Sequence[int]): Indices of output stages.
  81. last_stage_pool (bool): If True, add `MaxPool2d` layer to last stage.
  82. init_type (None | str): the config to control the initialization.
  83. '''
  84. def __init__(self,
  85. in_channels=3,
  86. layers=[1, 2, 5, 3],
  87. channels=[64, 128, 256, 256, 512, 512, 512],
  88. out_indices=None,
  89. last_stage_pool=False,
  90. init_type=None):
  91. super(ResNet31, self).__init__()
  92. assert isinstance(in_channels, int)
  93. assert isinstance(last_stage_pool, bool)
  94. self.out_indices = out_indices
  95. self.last_stage_pool = last_stage_pool
  96. conv_weight_attr = None
  97. bn_weight_attr = None
  98. if init_type is not None:
  99. support_dict = ['KaimingNormal']
  100. assert init_type in support_dict, Exception(
  101. "resnet31 only support {}".format(support_dict))
  102. conv_weight_attr = nn.initializer.KaimingNormal()
  103. bn_weight_attr = ParamAttr(initializer=nn.initializer.Uniform(), learning_rate=1)
  104. # conv 1 (Conv Conv)
  105. self.conv1_1 = nn.Conv2D(
  106. in_channels, channels[0], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr)
  107. self.bn1_1 = nn.BatchNorm2D(channels[0], weight_attr=bn_weight_attr)
  108. self.relu1_1 = nn.ReLU()
  109. self.conv1_2 = nn.Conv2D(
  110. channels[0], channels[1], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr)
  111. self.bn1_2 = nn.BatchNorm2D(channels[1], weight_attr=bn_weight_attr)
  112. self.relu1_2 = nn.ReLU()
  113. # conv 2 (Max-pooling, Residual block, Conv)
  114. self.pool2 = nn.MaxPool2D(
  115. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  116. self.block2 = self._make_layer(channels[1], channels[2], layers[0],
  117. conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr)
  118. self.conv2 = nn.Conv2D(
  119. channels[2], channels[2], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr)
  120. self.bn2 = nn.BatchNorm2D(channels[2], weight_attr=bn_weight_attr)
  121. self.relu2 = nn.ReLU()
  122. # conv 3 (Max-pooling, Residual block, Conv)
  123. self.pool3 = nn.MaxPool2D(
  124. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  125. self.block3 = self._make_layer(channels[2], channels[3], layers[1],
  126. conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr)
  127. self.conv3 = nn.Conv2D(
  128. channels[3], channels[3], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr)
  129. self.bn3 = nn.BatchNorm2D(channels[3], weight_attr=bn_weight_attr)
  130. self.relu3 = nn.ReLU()
  131. # conv 4 (Max-pooling, Residual block, Conv)
  132. self.pool4 = nn.MaxPool2D(
  133. kernel_size=(2, 1), stride=(2, 1), padding=0, ceil_mode=True)
  134. self.block4 = self._make_layer(channels[3], channels[4], layers[2],
  135. conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr)
  136. self.conv4 = nn.Conv2D(
  137. channels[4], channels[4], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr)
  138. self.bn4 = nn.BatchNorm2D(channels[4], weight_attr=bn_weight_attr)
  139. self.relu4 = nn.ReLU()
  140. # conv 5 ((Max-pooling), Residual block, Conv)
  141. self.pool5 = None
  142. if self.last_stage_pool:
  143. self.pool5 = nn.MaxPool2D(
  144. kernel_size=2, stride=2, padding=0, ceil_mode=True)
  145. self.block5 = self._make_layer(channels[4], channels[5], layers[3],
  146. conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr)
  147. self.conv5 = nn.Conv2D(
  148. channels[5], channels[5], kernel_size=3, stride=1, padding=1, weight_attr=conv_weight_attr)
  149. self.bn5 = nn.BatchNorm2D(channels[5], weight_attr=bn_weight_attr)
  150. self.relu5 = nn.ReLU()
  151. self.out_channels = channels[-1]
  152. def _make_layer(self, input_channels, output_channels, blocks, conv_weight_attr=None, bn_weight_attr=None):
  153. layers = []
  154. for _ in range(blocks):
  155. downsample = None
  156. if input_channels != output_channels:
  157. downsample = nn.Sequential(
  158. nn.Conv2D(
  159. input_channels,
  160. output_channels,
  161. kernel_size=1,
  162. stride=1,
  163. weight_attr=conv_weight_attr,
  164. bias_attr=False),
  165. nn.BatchNorm2D(output_channels, weight_attr=bn_weight_attr))
  166. layers.append(
  167. BasicBlock(
  168. input_channels, output_channels, downsample=downsample,
  169. conv_weight_attr=conv_weight_attr, bn_weight_attr=bn_weight_attr))
  170. input_channels = output_channels
  171. return nn.Sequential(*layers)
  172. def forward(self, x):
  173. x = self.conv1_1(x)
  174. x = self.bn1_1(x)
  175. x = self.relu1_1(x)
  176. x = self.conv1_2(x)
  177. x = self.bn1_2(x)
  178. x = self.relu1_2(x)
  179. outs = []
  180. for i in range(4):
  181. layer_index = i + 2
  182. pool_layer = getattr(self, f'pool{layer_index}')
  183. block_layer = getattr(self, f'block{layer_index}')
  184. conv_layer = getattr(self, f'conv{layer_index}')
  185. bn_layer = getattr(self, f'bn{layer_index}')
  186. relu_layer = getattr(self, f'relu{layer_index}')
  187. if pool_layer is not None:
  188. x = pool_layer(x)
  189. x = block_layer(x)
  190. x = conv_layer(x)
  191. x = bn_layer(x)
  192. x = relu_layer(x)
  193. outs.append(x)
  194. if self.out_indices is not None:
  195. return tuple([outs[i] for i in self.out_indices])
  196. return x