rec_abinet_head.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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/FangShancheng/ABINet/tree/main/modules
  17. """
  18. import math
  19. import paddle
  20. from paddle import nn
  21. import paddle.nn.functional as F
  22. from paddle.nn import LayerList
  23. from ppocr.modeling.heads.rec_nrtr_head import TransformerBlock, PositionalEncoding
  24. class BCNLanguage(nn.Layer):
  25. def __init__(
  26. self,
  27. d_model=512,
  28. nhead=8,
  29. num_layers=4,
  30. dim_feedforward=2048,
  31. dropout=0.0,
  32. max_length=25,
  33. detach=True,
  34. num_classes=37,
  35. ):
  36. super().__init__()
  37. self.d_model = d_model
  38. self.detach = detach
  39. self.max_length = max_length + 1 # additional stop token
  40. self.proj = nn.Linear(num_classes, d_model, bias_attr=False)
  41. self.token_encoder = PositionalEncoding(
  42. dropout=0.1, dim=d_model, max_len=self.max_length
  43. )
  44. self.pos_encoder = PositionalEncoding(
  45. dropout=0, dim=d_model, max_len=self.max_length
  46. )
  47. self.decoder = nn.LayerList(
  48. [
  49. TransformerBlock(
  50. d_model=d_model,
  51. nhead=nhead,
  52. dim_feedforward=dim_feedforward,
  53. attention_dropout_rate=dropout,
  54. residual_dropout_rate=dropout,
  55. with_self_attn=False,
  56. with_cross_attn=True,
  57. )
  58. for i in range(num_layers)
  59. ]
  60. )
  61. self.cls = nn.Linear(d_model, num_classes)
  62. def forward(self, tokens, lengths):
  63. """
  64. Args:
  65. tokens: (B, N, C) where N is length, B is batch size and C is classes number
  66. lengths: (B,)
  67. """
  68. if self.detach:
  69. tokens = tokens.detach()
  70. embed = self.proj(tokens) # (B, N, C)
  71. embed = self.token_encoder(embed) # (B, N, C)
  72. padding_mask = _get_mask(lengths, self.max_length)
  73. zeros = paddle.zeros_like(embed) # (B, N, C)
  74. query = self.pos_encoder(zeros)
  75. for decoder_layer in self.decoder:
  76. query = decoder_layer(query, embed, cross_mask=padding_mask)
  77. output = query # (B, N, C)
  78. logits = self.cls(output) # (B, N, C)
  79. return output, logits
  80. def encoder_layer(in_c, out_c, k=3, s=2, p=1):
  81. return nn.Sequential(
  82. nn.Conv2D(in_c, out_c, k, s, p), nn.BatchNorm2D(out_c), nn.ReLU()
  83. )
  84. def decoder_layer(
  85. in_c, out_c, k=3, s=1, p=1, mode="nearest", scale_factor=None, size=None
  86. ):
  87. align_corners = False if mode == "nearest" else True
  88. return nn.Sequential(
  89. nn.Upsample(
  90. size=size, scale_factor=scale_factor, mode=mode, align_corners=align_corners
  91. ),
  92. nn.Conv2D(in_c, out_c, k, s, p),
  93. nn.BatchNorm2D(out_c),
  94. nn.ReLU(),
  95. )
  96. class PositionAttention(nn.Layer):
  97. def __init__(
  98. self,
  99. max_length,
  100. in_channels=512,
  101. num_channels=64,
  102. h=8,
  103. w=32,
  104. mode="nearest",
  105. **kwargs,
  106. ):
  107. super().__init__()
  108. self.max_length = max_length
  109. self.k_encoder = nn.Sequential(
  110. encoder_layer(in_channels, num_channels, s=(1, 2)),
  111. encoder_layer(num_channels, num_channels, s=(2, 2)),
  112. encoder_layer(num_channels, num_channels, s=(2, 2)),
  113. encoder_layer(num_channels, num_channels, s=(2, 2)),
  114. )
  115. self.k_decoder = nn.Sequential(
  116. decoder_layer(num_channels, num_channels, scale_factor=2, mode=mode),
  117. decoder_layer(num_channels, num_channels, scale_factor=2, mode=mode),
  118. decoder_layer(num_channels, num_channels, scale_factor=2, mode=mode),
  119. decoder_layer(num_channels, in_channels, size=(h, w), mode=mode),
  120. )
  121. self.pos_encoder = PositionalEncoding(
  122. dropout=0, dim=in_channels, max_len=max_length
  123. )
  124. self.project = nn.Linear(in_channels, in_channels)
  125. def forward(self, x):
  126. B, C, H, W = x.shape
  127. k, v = x, x
  128. # calculate key vector
  129. features = []
  130. for i in range(0, len(self.k_encoder)):
  131. k = self.k_encoder[i](k)
  132. features.append(k)
  133. for i in range(0, len(self.k_decoder) - 1):
  134. k = self.k_decoder[i](k)
  135. # print(k.shape, features[len(self.k_decoder) - 2 - i].shape)
  136. k = k + features[len(self.k_decoder) - 2 - i]
  137. k = self.k_decoder[-1](k)
  138. # calculate query vector
  139. # TODO q=f(q,k)
  140. zeros = paddle.zeros((B, self.max_length, C), dtype=x.dtype) # (B, N, C)
  141. q = self.pos_encoder(zeros) # (B, N, C)
  142. q = self.project(q) # (B, N, C)
  143. # calculate attention
  144. attn_scores = q @ k.flatten(2) # (B, N, (H*W))
  145. attn_scores = attn_scores / (C**0.5)
  146. attn_scores = F.softmax(attn_scores, axis=-1)
  147. v = v.flatten(2).transpose([0, 2, 1]) # (B, (H*W), C)
  148. attn_vecs = attn_scores @ v # (B, N, C)
  149. return attn_vecs, attn_scores.reshape([0, self.max_length, H, W])
  150. class ABINetHead(nn.Layer):
  151. def __init__(
  152. self,
  153. in_channels,
  154. out_channels,
  155. d_model=512,
  156. nhead=8,
  157. num_layers=3,
  158. dim_feedforward=2048,
  159. dropout=0.1,
  160. max_length=25,
  161. use_lang=False,
  162. iter_size=1,
  163. image_size=(32, 128),
  164. ):
  165. super().__init__()
  166. self.max_length = max_length + 1
  167. h, w = image_size[0] // 4, image_size[1] // 4
  168. self.pos_encoder = PositionalEncoding(dropout=0.1, dim=d_model, max_len=h * w)
  169. self.encoder = nn.LayerList(
  170. [
  171. TransformerBlock(
  172. d_model=d_model,
  173. nhead=nhead,
  174. dim_feedforward=dim_feedforward,
  175. attention_dropout_rate=dropout,
  176. residual_dropout_rate=dropout,
  177. with_self_attn=True,
  178. with_cross_attn=False,
  179. )
  180. for i in range(num_layers)
  181. ]
  182. )
  183. self.decoder = PositionAttention(
  184. max_length=max_length + 1, mode="nearest", h=h, w=w # additional stop token
  185. )
  186. self.out_channels = out_channels
  187. self.cls = nn.Linear(d_model, self.out_channels)
  188. self.use_lang = use_lang
  189. if use_lang:
  190. self.iter_size = iter_size
  191. self.language = BCNLanguage(
  192. d_model=d_model,
  193. nhead=nhead,
  194. num_layers=4,
  195. dim_feedforward=dim_feedforward,
  196. dropout=dropout,
  197. max_length=max_length,
  198. num_classes=self.out_channels,
  199. )
  200. # alignment
  201. self.w_att_align = nn.Linear(2 * d_model, d_model)
  202. self.cls_align = nn.Linear(d_model, self.out_channels)
  203. def forward(self, x, targets=None):
  204. x = x.transpose([0, 2, 3, 1])
  205. _, H, W, C = x.shape
  206. feature = x.flatten(1, 2)
  207. feature = self.pos_encoder(feature)
  208. for encoder_layer in self.encoder:
  209. feature = encoder_layer(feature)
  210. feature = feature.reshape([0, H, W, C]).transpose([0, 3, 1, 2])
  211. v_feature, attn_scores = self.decoder(feature) # (B, N, C), (B, C, H, W)
  212. vis_logits = self.cls(v_feature) # (B, N, C)
  213. logits = vis_logits
  214. vis_lengths = _get_length(vis_logits)
  215. if self.use_lang:
  216. align_logits = vis_logits
  217. align_lengths = vis_lengths
  218. all_l_res, all_a_res = [], []
  219. for i in range(self.iter_size):
  220. tokens = F.softmax(align_logits, axis=-1)
  221. lengths = align_lengths
  222. lengths = paddle.clip(
  223. lengths, 2, self.max_length
  224. ) # TODO:move to language model
  225. l_feature, l_logits = self.language(tokens, lengths)
  226. # alignment
  227. all_l_res.append(l_logits)
  228. fuse = paddle.concat((l_feature, v_feature), -1)
  229. f_att = F.sigmoid(self.w_att_align(fuse))
  230. output = f_att * v_feature + (1 - f_att) * l_feature
  231. align_logits = self.cls_align(output) # (B, N, C)
  232. align_lengths = _get_length(align_logits)
  233. all_a_res.append(align_logits)
  234. if self.training:
  235. return {"align": all_a_res, "lang": all_l_res, "vision": vis_logits}
  236. else:
  237. logits = align_logits
  238. if self.training:
  239. return logits
  240. else:
  241. return F.softmax(logits, -1)
  242. def _get_length(logit):
  243. """Greed decoder to obtain length from logit"""
  244. out = logit.argmax(-1) == 0
  245. abn = out.any(-1)
  246. out_int = out.cast("int32")
  247. out = (out_int.cumsum(-1) == 1) & out
  248. out = out.cast("int32")
  249. out = out.argmax(-1)
  250. out = out + 1
  251. len_seq = paddle.zeros_like(out) + logit.shape[1]
  252. out = paddle.where(abn, out, len_seq)
  253. return out
  254. def _get_mask(length, max_length):
  255. """Generate a square mask for the sequence. The masked positions are filled with float('-inf').
  256. Unmasked positions are filled with float(0.0).
  257. """
  258. length = length.unsqueeze(-1)
  259. B = length.shape[0]
  260. grid = paddle.arange(0, max_length).unsqueeze(0).tile([B, 1])
  261. zero_mask = paddle.zeros([B, max_length], dtype="float32")
  262. inf_mask = paddle.full([B, max_length], "-inf", dtype="float32")
  263. diag_mask = paddle.diag(
  264. paddle.full([max_length], "-inf", dtype=paddle.float32), offset=0, name=None
  265. )
  266. mask = paddle.where(grid >= length, inf_mask, zero_mask)
  267. mask = mask.unsqueeze(1) + diag_mask
  268. return mask.unsqueeze(1)