RNN.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import torch
  2. from torch import nn
  3. from .RecSVTR import Block
  4. class Swish(nn.Module):
  5. def __int__(self):
  6. super(Swish, self).__int__()
  7. def forward(self, x):
  8. return x * torch.sigmoid(x)
  9. class Im2Im(nn.Module):
  10. def __init__(self, in_channels, **kwargs):
  11. super().__init__()
  12. self.out_channels = in_channels
  13. def forward(self, x):
  14. return x
  15. class Im2Seq(nn.Module):
  16. def __init__(self, in_channels, **kwargs):
  17. super().__init__()
  18. self.out_channels = in_channels
  19. def forward(self, x):
  20. B, C, H, W = x.shape
  21. # assert H == 1
  22. x = x.reshape(B, C, H * W)
  23. x = x.permute((0, 2, 1))
  24. return x
  25. class EncoderWithRNN(nn.Module):
  26. def __init__(self, in_channels, **kwargs):
  27. super(EncoderWithRNN, self).__init__()
  28. hidden_size = kwargs.get("hidden_size", 256)
  29. self.out_channels = hidden_size * 2
  30. self.lstm = nn.LSTM(
  31. in_channels, hidden_size, bidirectional=True, num_layers=2, batch_first=True
  32. )
  33. def forward(self, x):
  34. self.lstm.flatten_parameters()
  35. x, _ = self.lstm(x)
  36. return x
  37. class SequenceEncoder(nn.Module):
  38. def __init__(self, in_channels, encoder_type="rnn", **kwargs):
  39. super(SequenceEncoder, self).__init__()
  40. self.encoder_reshape = Im2Seq(in_channels)
  41. self.out_channels = self.encoder_reshape.out_channels
  42. self.encoder_type = encoder_type
  43. if encoder_type == "reshape":
  44. self.only_reshape = True
  45. else:
  46. support_encoder_dict = {
  47. "reshape": Im2Seq,
  48. "rnn": EncoderWithRNN,
  49. "svtr": EncoderWithSVTR,
  50. }
  51. assert encoder_type in support_encoder_dict, "{} must in {}".format(
  52. encoder_type, support_encoder_dict.keys()
  53. )
  54. self.encoder = support_encoder_dict[encoder_type](
  55. self.encoder_reshape.out_channels, **kwargs
  56. )
  57. self.out_channels = self.encoder.out_channels
  58. self.only_reshape = False
  59. def forward(self, x):
  60. if self.encoder_type != "svtr":
  61. x = self.encoder_reshape(x)
  62. if not self.only_reshape:
  63. x = self.encoder(x)
  64. return x
  65. else:
  66. x = self.encoder(x)
  67. x = self.encoder_reshape(x)
  68. return x
  69. class ConvBNLayer(nn.Module):
  70. def __init__(
  71. self,
  72. in_channels,
  73. out_channels,
  74. kernel_size=3,
  75. stride=1,
  76. padding=0,
  77. bias_attr=False,
  78. groups=1,
  79. act=nn.GELU,
  80. ):
  81. super().__init__()
  82. self.conv = nn.Conv2d(
  83. in_channels=in_channels,
  84. out_channels=out_channels,
  85. kernel_size=kernel_size,
  86. stride=stride,
  87. padding=padding,
  88. groups=groups,
  89. # weight_attr=paddle.ParamAttr(initializer=nn.initializer.KaimingUniform()),
  90. bias=bias_attr,
  91. )
  92. self.norm = nn.BatchNorm2d(out_channels)
  93. self.act = Swish()
  94. def forward(self, inputs):
  95. out = self.conv(inputs)
  96. out = self.norm(out)
  97. out = self.act(out)
  98. return out
  99. class EncoderWithSVTR(nn.Module):
  100. def __init__(
  101. self,
  102. in_channels,
  103. dims=64, # XS
  104. depth=2,
  105. hidden_dims=120,
  106. use_guide=False,
  107. num_heads=8,
  108. qkv_bias=True,
  109. mlp_ratio=2.0,
  110. drop_rate=0.1,
  111. attn_drop_rate=0.1,
  112. drop_path=0.0,
  113. qk_scale=None,
  114. ):
  115. super(EncoderWithSVTR, self).__init__()
  116. self.depth = depth
  117. self.use_guide = use_guide
  118. self.conv1 = ConvBNLayer(in_channels, in_channels // 8, padding=1, act="swish")
  119. self.conv2 = ConvBNLayer(
  120. in_channels // 8, hidden_dims, kernel_size=1, act="swish"
  121. )
  122. self.svtr_block = nn.ModuleList(
  123. [
  124. Block(
  125. dim=hidden_dims,
  126. num_heads=num_heads,
  127. mixer="Global",
  128. HW=None,
  129. mlp_ratio=mlp_ratio,
  130. qkv_bias=qkv_bias,
  131. qk_scale=qk_scale,
  132. drop=drop_rate,
  133. act_layer="swish",
  134. attn_drop=attn_drop_rate,
  135. drop_path=drop_path,
  136. norm_layer="nn.LayerNorm",
  137. epsilon=1e-05,
  138. prenorm=False,
  139. )
  140. for i in range(depth)
  141. ]
  142. )
  143. self.norm = nn.LayerNorm(hidden_dims, eps=1e-6)
  144. self.conv3 = ConvBNLayer(hidden_dims, in_channels, kernel_size=1, act="swish")
  145. # last conv-nxn, the input is concat of input tensor and conv3 output tensor
  146. self.conv4 = ConvBNLayer(
  147. 2 * in_channels, in_channels // 8, padding=1, act="swish"
  148. )
  149. self.conv1x1 = ConvBNLayer(in_channels // 8, dims, kernel_size=1, act="swish")
  150. self.out_channels = dims
  151. self.apply(self._init_weights)
  152. def _init_weights(self, m):
  153. # weight initialization
  154. if isinstance(m, nn.Conv2d):
  155. nn.init.kaiming_normal_(m.weight, mode="fan_out")
  156. if m.bias is not None:
  157. nn.init.zeros_(m.bias)
  158. elif isinstance(m, nn.BatchNorm2d):
  159. nn.init.ones_(m.weight)
  160. nn.init.zeros_(m.bias)
  161. elif isinstance(m, nn.Linear):
  162. nn.init.normal_(m.weight, 0, 0.01)
  163. if m.bias is not None:
  164. nn.init.zeros_(m.bias)
  165. elif isinstance(m, nn.ConvTranspose2d):
  166. nn.init.kaiming_normal_(m.weight, mode="fan_out")
  167. if m.bias is not None:
  168. nn.init.zeros_(m.bias)
  169. elif isinstance(m, nn.LayerNorm):
  170. nn.init.ones_(m.weight)
  171. nn.init.zeros_(m.bias)
  172. def forward(self, x):
  173. # for use guide
  174. if self.use_guide:
  175. z = x.clone()
  176. z.stop_gradient = True
  177. else:
  178. z = x
  179. # for short cut
  180. h = z
  181. # reduce dim
  182. z = self.conv1(z)
  183. z = self.conv2(z)
  184. # SVTR global block
  185. B, C, H, W = z.shape
  186. z = z.flatten(2).permute(0, 2, 1)
  187. for blk in self.svtr_block:
  188. z = blk(z)
  189. z = self.norm(z)
  190. # last stage
  191. z = z.reshape([-1, H, W, C]).permute(0, 3, 1, 2)
  192. z = self.conv3(z)
  193. z = torch.cat((h, z), dim=1)
  194. z = self.conv1x1(self.conv4(z))
  195. return z
  196. if __name__ == "__main__":
  197. svtrRNN = EncoderWithSVTR(56)
  198. print(svtrRNN)