rec_vitstr.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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/roatienza/deep-text-recognition-benchmark/blob/master/modules/vitstr.py
  17. """
  18. import numpy as np
  19. import paddle
  20. import paddle.nn as nn
  21. from ppocr.modeling.backbones.rec_svtrnet import Block, PatchEmbed, zeros_, trunc_normal_, ones_
  22. scale_dim_heads = {'tiny': [192, 3], 'small': [384, 6], 'base': [768, 12]}
  23. class ViTSTR(nn.Layer):
  24. def __init__(self,
  25. img_size=[224, 224],
  26. in_channels=1,
  27. scale='tiny',
  28. seqlen=27,
  29. patch_size=[16, 16],
  30. embed_dim=None,
  31. depth=12,
  32. num_heads=None,
  33. mlp_ratio=4,
  34. qkv_bias=True,
  35. qk_scale=None,
  36. drop_path_rate=0.,
  37. drop_rate=0.,
  38. attn_drop_rate=0.,
  39. norm_layer='nn.LayerNorm',
  40. act_layer='nn.GELU',
  41. epsilon=1e-6,
  42. out_channels=None,
  43. **kwargs):
  44. super().__init__()
  45. self.seqlen = seqlen
  46. embed_dim = embed_dim if embed_dim is not None else scale_dim_heads[
  47. scale][0]
  48. num_heads = num_heads if num_heads is not None else scale_dim_heads[
  49. scale][1]
  50. out_channels = out_channels if out_channels is not None else embed_dim
  51. self.patch_embed = PatchEmbed(
  52. img_size=img_size,
  53. in_channels=in_channels,
  54. embed_dim=embed_dim,
  55. patch_size=patch_size,
  56. mode='linear')
  57. num_patches = self.patch_embed.num_patches
  58. self.pos_embed = self.create_parameter(
  59. shape=[1, num_patches + 1, embed_dim], default_initializer=zeros_)
  60. self.add_parameter("pos_embed", self.pos_embed)
  61. self.cls_token = self.create_parameter(
  62. shape=[1, 1, embed_dim], default_initializer=zeros_)
  63. self.add_parameter("cls_token", self.cls_token)
  64. self.pos_drop = nn.Dropout(p=drop_rate)
  65. dpr = np.linspace(0, drop_path_rate, depth)
  66. self.blocks = nn.LayerList([
  67. Block(
  68. dim=embed_dim,
  69. num_heads=num_heads,
  70. mlp_ratio=mlp_ratio,
  71. qkv_bias=qkv_bias,
  72. qk_scale=qk_scale,
  73. drop=drop_rate,
  74. attn_drop=attn_drop_rate,
  75. drop_path=dpr[i],
  76. norm_layer=norm_layer,
  77. act_layer=eval(act_layer),
  78. epsilon=epsilon,
  79. prenorm=False) for i in range(depth)
  80. ])
  81. self.norm = eval(norm_layer)(embed_dim, epsilon=epsilon)
  82. self.out_channels = out_channels
  83. trunc_normal_(self.pos_embed)
  84. trunc_normal_(self.cls_token)
  85. self.apply(self._init_weights)
  86. def _init_weights(self, m):
  87. if isinstance(m, nn.Linear):
  88. trunc_normal_(m.weight)
  89. if isinstance(m, nn.Linear) and m.bias is not None:
  90. zeros_(m.bias)
  91. elif isinstance(m, nn.LayerNorm):
  92. zeros_(m.bias)
  93. ones_(m.weight)
  94. def forward_features(self, x):
  95. B = x.shape[0]
  96. x = self.patch_embed(x)
  97. cls_tokens = paddle.tile(self.cls_token, repeat_times=[B, 1, 1])
  98. x = paddle.concat((cls_tokens, x), axis=1)
  99. x = x + self.pos_embed
  100. x = self.pos_drop(x)
  101. for blk in self.blocks:
  102. x = blk(x)
  103. x = self.norm(x)
  104. return x
  105. def forward(self, x):
  106. x = self.forward_features(x)
  107. x = x[:, :self.seqlen]
  108. return x.transpose([0, 2, 1]).unsqueeze(2)