table_master_resnet.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. # Copyright (c) 2022 PaddlePaddle Authors. 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. """
  15. This code is refer from:
  16. https://github.com/JiaquanYe/TableMASTER-mmocr/blob/master/mmocr/models/textrecog/backbones/table_resnet_extra.py
  17. """
  18. import paddle
  19. import paddle.nn as nn
  20. import paddle.nn.functional as F
  21. class BasicBlock(nn.Layer):
  22. expansion = 1
  23. def __init__(self, inplanes, planes, stride=1, downsample=None, gcb_config=None):
  24. super(BasicBlock, self).__init__()
  25. self.conv1 = nn.Conv2D(
  26. inplanes, planes, kernel_size=3, stride=stride, padding=1, bias_attr=False
  27. )
  28. self.bn1 = nn.BatchNorm2D(planes, momentum=0.9)
  29. self.relu = nn.ReLU()
  30. self.conv2 = nn.Conv2D(
  31. planes, planes, kernel_size=3, stride=1, padding=1, bias_attr=False
  32. )
  33. self.bn2 = nn.BatchNorm2D(planes, momentum=0.9)
  34. self.downsample = downsample
  35. self.stride = stride
  36. self.gcb_config = gcb_config
  37. if self.gcb_config is not None:
  38. gcb_ratio = gcb_config["ratio"]
  39. gcb_headers = gcb_config["headers"]
  40. att_scale = gcb_config["att_scale"]
  41. fusion_type = gcb_config["fusion_type"]
  42. self.context_block = MultiAspectGCAttention(
  43. inplanes=planes,
  44. ratio=gcb_ratio,
  45. headers=gcb_headers,
  46. att_scale=att_scale,
  47. fusion_type=fusion_type,
  48. )
  49. def forward(self, x):
  50. residual = x
  51. out = self.conv1(x)
  52. out = self.bn1(out)
  53. out = self.relu(out)
  54. out = self.conv2(out)
  55. out = self.bn2(out)
  56. if self.gcb_config is not None:
  57. out = self.context_block(out)
  58. if self.downsample is not None:
  59. residual = self.downsample(x)
  60. out += residual
  61. out = self.relu(out)
  62. return out
  63. def get_gcb_config(gcb_config, layer):
  64. if gcb_config is None or not gcb_config["layers"][layer]:
  65. return None
  66. else:
  67. return gcb_config
  68. class TableResNetExtra(nn.Layer):
  69. def __init__(self, layers, in_channels=3, gcb_config=None):
  70. assert len(layers) >= 4
  71. super(TableResNetExtra, self).__init__()
  72. self.inplanes = 128
  73. self.conv1 = nn.Conv2D(
  74. in_channels, 64, kernel_size=3, stride=1, padding=1, bias_attr=False
  75. )
  76. self.bn1 = nn.BatchNorm2D(64)
  77. self.relu1 = nn.ReLU()
  78. self.conv2 = nn.Conv2D(
  79. 64, 128, kernel_size=3, stride=1, padding=1, bias_attr=False
  80. )
  81. self.bn2 = nn.BatchNorm2D(128)
  82. self.relu2 = nn.ReLU()
  83. self.maxpool1 = nn.MaxPool2D(kernel_size=2, stride=2)
  84. self.layer1 = self._make_layer(
  85. BasicBlock,
  86. 256,
  87. layers[0],
  88. stride=1,
  89. gcb_config=get_gcb_config(gcb_config, 0),
  90. )
  91. self.conv3 = nn.Conv2D(
  92. 256, 256, kernel_size=3, stride=1, padding=1, bias_attr=False
  93. )
  94. self.bn3 = nn.BatchNorm2D(256)
  95. self.relu3 = nn.ReLU()
  96. self.maxpool2 = nn.MaxPool2D(kernel_size=2, stride=2)
  97. self.layer2 = self._make_layer(
  98. BasicBlock,
  99. 256,
  100. layers[1],
  101. stride=1,
  102. gcb_config=get_gcb_config(gcb_config, 1),
  103. )
  104. self.conv4 = nn.Conv2D(
  105. 256, 256, kernel_size=3, stride=1, padding=1, bias_attr=False
  106. )
  107. self.bn4 = nn.BatchNorm2D(256)
  108. self.relu4 = nn.ReLU()
  109. self.maxpool3 = nn.MaxPool2D(kernel_size=2, stride=2)
  110. self.layer3 = self._make_layer(
  111. BasicBlock,
  112. 512,
  113. layers[2],
  114. stride=1,
  115. gcb_config=get_gcb_config(gcb_config, 2),
  116. )
  117. self.conv5 = nn.Conv2D(
  118. 512, 512, kernel_size=3, stride=1, padding=1, bias_attr=False
  119. )
  120. self.bn5 = nn.BatchNorm2D(512)
  121. self.relu5 = nn.ReLU()
  122. self.layer4 = self._make_layer(
  123. BasicBlock,
  124. 512,
  125. layers[3],
  126. stride=1,
  127. gcb_config=get_gcb_config(gcb_config, 3),
  128. )
  129. self.conv6 = nn.Conv2D(
  130. 512, 512, kernel_size=3, stride=1, padding=1, bias_attr=False
  131. )
  132. self.bn6 = nn.BatchNorm2D(512)
  133. self.relu6 = nn.ReLU()
  134. self.out_channels = [256, 256, 512]
  135. def _make_layer(self, block, planes, blocks, stride=1, gcb_config=None):
  136. downsample = None
  137. if stride != 1 or self.inplanes != planes * block.expansion:
  138. downsample = nn.Sequential(
  139. nn.Conv2D(
  140. self.inplanes,
  141. planes * block.expansion,
  142. kernel_size=1,
  143. stride=stride,
  144. bias_attr=False,
  145. ),
  146. nn.BatchNorm2D(planes * block.expansion),
  147. )
  148. layers = []
  149. layers.append(
  150. block(self.inplanes, planes, stride, downsample, gcb_config=gcb_config)
  151. )
  152. self.inplanes = planes * block.expansion
  153. for _ in range(1, blocks):
  154. layers.append(block(self.inplanes, planes))
  155. return nn.Sequential(*layers)
  156. def forward(self, x):
  157. f = []
  158. x = self.conv1(x)
  159. x = self.bn1(x)
  160. x = self.relu1(x)
  161. x = self.conv2(x)
  162. x = self.bn2(x)
  163. x = self.relu2(x)
  164. x = self.maxpool1(x)
  165. x = self.layer1(x)
  166. x = self.conv3(x)
  167. x = self.bn3(x)
  168. x = self.relu3(x)
  169. f.append(x)
  170. x = self.maxpool2(x)
  171. x = self.layer2(x)
  172. x = self.conv4(x)
  173. x = self.bn4(x)
  174. x = self.relu4(x)
  175. f.append(x)
  176. x = self.maxpool3(x)
  177. x = self.layer3(x)
  178. x = self.conv5(x)
  179. x = self.bn5(x)
  180. x = self.relu5(x)
  181. x = self.layer4(x)
  182. x = self.conv6(x)
  183. x = self.bn6(x)
  184. x = self.relu6(x)
  185. f.append(x)
  186. return f
  187. class MultiAspectGCAttention(nn.Layer):
  188. def __init__(
  189. self,
  190. inplanes,
  191. ratio,
  192. headers,
  193. pooling_type="att",
  194. att_scale=False,
  195. fusion_type="channel_add",
  196. ):
  197. super(MultiAspectGCAttention, self).__init__()
  198. assert pooling_type in ["avg", "att"]
  199. assert fusion_type in ["channel_add", "channel_mul", "channel_concat"]
  200. assert (
  201. inplanes % headers == 0 and inplanes >= 8
  202. ) # inplanes must be divided by headers evenly
  203. self.headers = headers
  204. self.inplanes = inplanes
  205. self.ratio = ratio
  206. self.planes = int(inplanes * ratio)
  207. self.pooling_type = pooling_type
  208. self.fusion_type = fusion_type
  209. self.att_scale = False
  210. self.single_header_inplanes = int(inplanes / headers)
  211. if pooling_type == "att":
  212. self.conv_mask = nn.Conv2D(self.single_header_inplanes, 1, kernel_size=1)
  213. self.softmax = nn.Softmax(axis=2)
  214. else:
  215. self.avg_pool = nn.AdaptiveAvgPool2D(1)
  216. if fusion_type == "channel_add":
  217. self.channel_add_conv = nn.Sequential(
  218. nn.Conv2D(self.inplanes, self.planes, kernel_size=1),
  219. nn.LayerNorm([self.planes, 1, 1]),
  220. nn.ReLU(),
  221. nn.Conv2D(self.planes, self.inplanes, kernel_size=1),
  222. )
  223. elif fusion_type == "channel_concat":
  224. self.channel_concat_conv = nn.Sequential(
  225. nn.Conv2D(self.inplanes, self.planes, kernel_size=1),
  226. nn.LayerNorm([self.planes, 1, 1]),
  227. nn.ReLU(),
  228. nn.Conv2D(self.planes, self.inplanes, kernel_size=1),
  229. )
  230. # for concat
  231. self.cat_conv = nn.Conv2D(2 * self.inplanes, self.inplanes, kernel_size=1)
  232. elif fusion_type == "channel_mul":
  233. self.channel_mul_conv = nn.Sequential(
  234. nn.Conv2D(self.inplanes, self.planes, kernel_size=1),
  235. nn.LayerNorm([self.planes, 1, 1]),
  236. nn.ReLU(),
  237. nn.Conv2D(self.planes, self.inplanes, kernel_size=1),
  238. )
  239. def spatial_pool(self, x):
  240. batch, channel, height, width = x.shape
  241. if self.pooling_type == "att":
  242. # [N*headers, C', H , W] C = headers * C'
  243. x = x.reshape(
  244. [batch * self.headers, self.single_header_inplanes, height, width]
  245. )
  246. input_x = x
  247. # [N*headers, C', H * W] C = headers * C'
  248. # input_x = input_x.view(batch, channel, height * width)
  249. input_x = input_x.reshape(
  250. [batch * self.headers, self.single_header_inplanes, height * width]
  251. )
  252. # [N*headers, 1, C', H * W]
  253. input_x = input_x.unsqueeze(1)
  254. # [N*headers, 1, H, W]
  255. context_mask = self.conv_mask(x)
  256. # [N*headers, 1, H * W]
  257. context_mask = context_mask.reshape(
  258. [batch * self.headers, 1, height * width]
  259. )
  260. # scale variance
  261. if self.att_scale and self.headers > 1:
  262. context_mask = context_mask / paddle.sqrt(self.single_header_inplanes)
  263. # [N*headers, 1, H * W]
  264. context_mask = self.softmax(context_mask)
  265. # [N*headers, 1, H * W, 1]
  266. context_mask = context_mask.unsqueeze(-1)
  267. # [N*headers, 1, C', 1] = [N*headers, 1, C', H * W] * [N*headers, 1, H * W, 1]
  268. context = paddle.matmul(input_x, context_mask)
  269. # [N, headers * C', 1, 1]
  270. context = context.reshape(
  271. [batch, self.headers * self.single_header_inplanes, 1, 1]
  272. )
  273. else:
  274. # [N, C, 1, 1]
  275. context = self.avg_pool(x)
  276. return context
  277. def forward(self, x):
  278. # [N, C, 1, 1]
  279. context = self.spatial_pool(x)
  280. out = x
  281. if self.fusion_type == "channel_mul":
  282. # [N, C, 1, 1]
  283. channel_mul_term = F.sigmoid(self.channel_mul_conv(context))
  284. out = out * channel_mul_term
  285. elif self.fusion_type == "channel_add":
  286. # [N, C, 1, 1]
  287. channel_add_term = self.channel_add_conv(context)
  288. out = out + channel_add_term
  289. else:
  290. # [N, C, 1, 1]
  291. channel_concat_term = self.channel_concat_conv(context)
  292. # use concat
  293. _, C1, _, _ = channel_concat_term.shape
  294. N, C2, H, W = out.shape
  295. out = paddle.concat(
  296. [out, channel_concat_term.expand([-1, -1, H, W])], axis=1
  297. )
  298. out = self.cat_conv(out)
  299. out = F.layer_norm(out, [self.inplanes, H, W])
  300. out = F.relu(out)
  301. return out