DetResNetvd.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4. import logging
  5. import os
  6. import torch
  7. from torch import nn
  8. from torchocr.networks.CommonModules import HSwish
  9. class ConvBNACT(nn.Module):
  10. def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, act=None):
  11. super().__init__()
  12. self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size,
  13. stride=stride, padding=padding, groups=groups,
  14. bias=False)
  15. self.bn = nn.BatchNorm2d(out_channels)
  16. if act == 'relu':
  17. self.act = nn.ReLU(inplace=True)
  18. elif act == 'hard_swish':
  19. self.act = HSwish()
  20. elif act is None:
  21. self.act = None
  22. def forward(self, x):
  23. x = self.conv(x)
  24. x = self.bn(x)
  25. if self.act is not None:
  26. x = self.act(x)
  27. return x
  28. class ConvBNACTWithPool(nn.Module):
  29. def __init__(self, in_channels, out_channels, kernel_size, groups=1, act=None):
  30. super().__init__()
  31. # self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0, ceil_mode=True)
  32. self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0)
  33. self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=1,
  34. padding=(kernel_size - 1) // 2,
  35. groups=groups,
  36. bias=False)
  37. self.bn = nn.BatchNorm2d(out_channels)
  38. if act is None:
  39. self.act = None
  40. else:
  41. self.act = nn.ReLU(inplace=True)
  42. def forward(self, x):
  43. x = self.pool(x)
  44. x = self.conv(x)
  45. x = self.bn(x)
  46. if self.act is not None:
  47. x = self.act(x)
  48. return x
  49. class ShortCut(nn.Module):
  50. def __init__(self, in_channels, out_channels, stride, name, if_first=False):
  51. super().__init__()
  52. assert name is not None, 'shortcut must have name'
  53. self.name = name
  54. if in_channels != out_channels or stride != 1:
  55. if if_first:
  56. self.conv = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride,
  57. padding=0, groups=1, act=None)
  58. else:
  59. self.conv = ConvBNACTWithPool(in_channels=in_channels, out_channels=out_channels, kernel_size=1,
  60. groups=1, act=None)
  61. elif if_first:
  62. self.conv = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=stride,
  63. padding=0, groups=1, act=None)
  64. else:
  65. self.conv = None
  66. def forward(self, x):
  67. if self.conv is not None:
  68. x = self.conv(x)
  69. return x
  70. class BottleneckBlock(nn.Module):
  71. def __init__(self, in_channels, out_channels, stride, if_first, name):
  72. super().__init__()
  73. assert name is not None, 'bottleneck must have name'
  74. self.name = name
  75. self.conv0 = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=1, stride=1, padding=0,
  76. groups=1, act='relu')
  77. self.conv1 = ConvBNACT(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=stride,
  78. padding=1, groups=1, act='relu')
  79. self.conv2 = ConvBNACT(in_channels=out_channels, out_channels=out_channels * 4, kernel_size=1, stride=1,
  80. padding=0, groups=1, act=None)
  81. self.shortcut = ShortCut(in_channels=in_channels, out_channels=out_channels * 4, stride=stride,
  82. if_first=if_first, name=f'{name}_branch1')
  83. self.relu = nn.ReLU(inplace=True)
  84. self.output_channels = out_channels * 4
  85. def forward(self, x):
  86. y = self.conv0(x)
  87. y = self.conv1(y)
  88. y = self.conv2(y)
  89. y = y + self.shortcut(x)
  90. return self.relu(y)
  91. class BasicBlock(nn.Module):
  92. def __init__(self, in_channels, out_channels, stride, if_first, name):
  93. super().__init__()
  94. assert name is not None, 'block must have name'
  95. self.name = name
  96. self.conv0 = ConvBNACT(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride,
  97. padding=1, groups=1, act='relu')
  98. self.conv1 = ConvBNACT(in_channels=out_channels, out_channels=out_channels, kernel_size=3, stride=1, padding=1,
  99. groups=1, act=None)
  100. self.shortcut = ShortCut(in_channels=in_channels, out_channels=out_channels, stride=stride,
  101. name=f'{name}_branch1', if_first=if_first, )
  102. self.relu = nn.ReLU(inplace=True)
  103. self.output_channels = out_channels
  104. def forward(self, x):
  105. y = self.conv0(x)
  106. y = self.conv1(y)
  107. y = y + self.shortcut(x)
  108. return self.relu(y)
  109. class ResNet(nn.Module):
  110. def __init__(self, in_channels, layers, out_indices=[0, 1, 2, 3], pretrained=True, **kwargs):
  111. """
  112. the Resnet backbone network for detection module.
  113. Args:
  114. params(dict): the super parameters for network build
  115. """
  116. super().__init__()
  117. supported_layers = {
  118. 18: {'depth': [2, 2, 2, 2], 'block_class': BasicBlock},
  119. 34: {'depth': [3, 4, 6, 3], 'block_class': BasicBlock},
  120. 50: {'depth': [3, 4, 6, 3], 'block_class': BottleneckBlock},
  121. 101: {'depth': [3, 4, 23, 3], 'block_class': BottleneckBlock},
  122. 152: {'depth': [3, 8, 36, 3], 'block_class': BottleneckBlock},
  123. 200: {'depth': [3, 12, 48, 3], 'block_class': BottleneckBlock}
  124. }
  125. assert layers in supported_layers, \
  126. "supported layers are {} but input layer is {}".format(supported_layers, layers)
  127. depth = supported_layers[layers]['depth']
  128. block_class = supported_layers[layers]['block_class']
  129. self.use_supervised = kwargs.get('use_supervised', False)
  130. self.out_indices = out_indices
  131. num_filters = [64, 128, 256, 512]
  132. self.conv1 = nn.Sequential(
  133. ConvBNACT(in_channels=in_channels, out_channels=32, kernel_size=3, stride=2, padding=1, act='relu'),
  134. ConvBNACT(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1, act='relu'),
  135. ConvBNACT(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1, act='relu')
  136. )
  137. self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
  138. self.stages = nn.ModuleList()
  139. self.out_channels = []
  140. tmp_channels = []
  141. in_ch = 64
  142. for block_index in range(len(depth)):
  143. block_list = []
  144. for i in range(depth[block_index]):
  145. if layers >= 50:
  146. if layers in [101, 152, 200] and block_index == 2:
  147. if i == 0:
  148. conv_name = "res" + str(block_index + 2) + "a"
  149. else:
  150. conv_name = "res" + str(block_index + 2) + "b" + str(i)
  151. else:
  152. conv_name = "res" + str(block_index + 2) + chr(97 + i)
  153. else:
  154. conv_name = f'res{str(block_index + 2)}{chr(97 + i)}'
  155. block_list.append(block_class(in_channels=in_ch, out_channels=num_filters[block_index],
  156. stride=2 if i == 0 and block_index != 0 else 1,
  157. if_first=block_index == i == 0, name=conv_name))
  158. in_ch = block_list[-1].output_channels
  159. tmp_channels.append(in_ch)
  160. self.stages.append(nn.Sequential(*block_list))
  161. for idx, ch in enumerate(tmp_channels):
  162. if idx in self.out_indices:
  163. self.out_channels.append(ch)
  164. if pretrained:
  165. ckpt_path = f'./weights/resnet{layers}_vd.pth'
  166. logger = logging.getLogger('torchocr')
  167. if os.path.exists(ckpt_path):
  168. logger.info('load imagenet weights')
  169. self.load_state_dict(torch.load(ckpt_path))
  170. else:
  171. logger.info(f'{ckpt_path} not exists')
  172. if self.use_supervised:
  173. ckpt_path = f'./weights/res_supervised_140w_387e.pth'
  174. logger = logging.getLogger('torchocr')
  175. if os.path.exists(ckpt_path):
  176. logger.info('load supervised weights')
  177. self.load_state_dict(torch.load(ckpt_path))
  178. else:
  179. logger.info(f'{ckpt_path} not exists')
  180. def forward(self, x):
  181. x = self.conv1(x)
  182. x = self.pool1(x)
  183. out = []
  184. for idx, stage in enumerate(self.stages):
  185. x = stage(x)
  186. if idx in self.out_indices:
  187. out.append(x)
  188. return out