rec_vit_parseq.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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/PaddlePaddle/PaddleClas/blob/release%2F2.5/ppcls/arch/backbone/model_zoo/vision_transformer.py
  17. """
  18. from collections.abc import Callable
  19. import numpy as np
  20. import paddle
  21. import paddle.nn as nn
  22. from paddle.nn.initializer import TruncatedNormal, Constant, Normal
  23. trunc_normal_ = TruncatedNormal(std=0.02)
  24. normal_ = Normal
  25. zeros_ = Constant(value=0.0)
  26. ones_ = Constant(value=1.0)
  27. def to_2tuple(x):
  28. return tuple([x] * 2)
  29. def drop_path(x, drop_prob=0.0, training=False):
  30. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  31. the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  32. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ...
  33. """
  34. if drop_prob == 0.0 or not training:
  35. return x
  36. keep_prob = paddle.to_tensor(1 - drop_prob, dtype=x.dtype)
  37. shape = (x.shape[0],) + (1,) * (x.ndim - 1)
  38. random_tensor = keep_prob + paddle.rand(shape).astype(x.dtype)
  39. random_tensor = paddle.floor(random_tensor) # binarize
  40. output = x.divide(keep_prob) * random_tensor
  41. return output
  42. class DropPath(nn.Layer):
  43. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  44. def __init__(self, drop_prob=None):
  45. super(DropPath, self).__init__()
  46. self.drop_prob = drop_prob
  47. def forward(self, x):
  48. return drop_path(x, self.drop_prob, self.training)
  49. class Identity(nn.Layer):
  50. def __init__(self):
  51. super(Identity, self).__init__()
  52. def forward(self, input):
  53. return input
  54. class Mlp(nn.Layer):
  55. def __init__(
  56. self,
  57. in_features,
  58. hidden_features=None,
  59. out_features=None,
  60. act_layer=nn.GELU,
  61. drop=0.0,
  62. ):
  63. super().__init__()
  64. out_features = out_features or in_features
  65. hidden_features = hidden_features or in_features
  66. self.fc1 = nn.Linear(in_features, hidden_features)
  67. self.act = act_layer()
  68. self.fc2 = nn.Linear(hidden_features, out_features)
  69. self.drop = nn.Dropout(drop)
  70. def forward(self, x):
  71. x = self.fc1(x)
  72. x = self.act(x)
  73. x = self.drop(x)
  74. x = self.fc2(x)
  75. x = self.drop(x)
  76. return x
  77. class Attention(nn.Layer):
  78. def __init__(
  79. self,
  80. dim,
  81. num_heads=8,
  82. qkv_bias=False,
  83. qk_scale=None,
  84. attn_drop=0.0,
  85. proj_drop=0.0,
  86. ):
  87. super().__init__()
  88. self.num_heads = num_heads
  89. head_dim = dim // num_heads
  90. self.scale = qk_scale or head_dim**-0.5
  91. self.qkv = nn.Linear(dim, dim * 3, bias_attr=qkv_bias)
  92. self.attn_drop = nn.Dropout(attn_drop)
  93. self.proj = nn.Linear(dim, dim)
  94. self.proj_drop = nn.Dropout(proj_drop)
  95. def forward(self, x):
  96. # B= x.shape[0]
  97. N, C = x.shape[1:]
  98. qkv = (
  99. self.qkv(x)
  100. .reshape((-1, N, 3, self.num_heads, C // self.num_heads))
  101. .transpose((2, 0, 3, 1, 4))
  102. )
  103. q, k, v = qkv[0], qkv[1], qkv[2]
  104. attn = (q.matmul(k.transpose((0, 1, 3, 2)))) * self.scale
  105. attn = nn.functional.softmax(attn, axis=-1)
  106. attn = self.attn_drop(attn)
  107. x = (attn.matmul(v)).transpose((0, 2, 1, 3)).reshape((-1, N, C))
  108. x = self.proj(x)
  109. x = self.proj_drop(x)
  110. return x
  111. class Block(nn.Layer):
  112. def __init__(
  113. self,
  114. dim,
  115. num_heads,
  116. mlp_ratio=4.0,
  117. qkv_bias=False,
  118. qk_scale=None,
  119. drop=0.0,
  120. attn_drop=0.0,
  121. drop_path=0.0,
  122. act_layer=nn.GELU,
  123. norm_layer="nn.LayerNorm",
  124. epsilon=1e-5,
  125. ):
  126. super().__init__()
  127. if isinstance(norm_layer, str):
  128. self.norm1 = eval(norm_layer)(dim, epsilon=epsilon)
  129. elif isinstance(norm_layer, Callable):
  130. self.norm1 = norm_layer(dim)
  131. else:
  132. raise TypeError("The norm_layer must be str or paddle.nn.layer.Layer class")
  133. self.attn = Attention(
  134. dim,
  135. num_heads=num_heads,
  136. qkv_bias=qkv_bias,
  137. qk_scale=qk_scale,
  138. attn_drop=attn_drop,
  139. proj_drop=drop,
  140. )
  141. # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
  142. self.drop_path = DropPath(drop_path) if drop_path > 0.0 else Identity()
  143. if isinstance(norm_layer, str):
  144. self.norm2 = eval(norm_layer)(dim, epsilon=epsilon)
  145. elif isinstance(norm_layer, Callable):
  146. self.norm2 = norm_layer(dim)
  147. else:
  148. raise TypeError("The norm_layer must be str or paddle.nn.layer.Layer class")
  149. mlp_hidden_dim = int(dim * mlp_ratio)
  150. self.mlp = Mlp(
  151. in_features=dim,
  152. hidden_features=mlp_hidden_dim,
  153. act_layer=act_layer,
  154. drop=drop,
  155. )
  156. def forward(self, x):
  157. x = x + self.drop_path(self.attn(self.norm1(x)))
  158. x = x + self.drop_path(self.mlp(self.norm2(x)))
  159. return x
  160. class PatchEmbed(nn.Layer):
  161. """Image to Patch Embedding"""
  162. def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768):
  163. super().__init__()
  164. if isinstance(img_size, int):
  165. img_size = to_2tuple(img_size)
  166. if isinstance(patch_size, int):
  167. patch_size = to_2tuple(patch_size)
  168. num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0])
  169. self.img_size = img_size
  170. self.patch_size = patch_size
  171. self.num_patches = num_patches
  172. self.proj = nn.Conv2D(
  173. in_chans, embed_dim, kernel_size=patch_size, stride=patch_size
  174. )
  175. def forward(self, x):
  176. B, C, H, W = x.shape
  177. assert (
  178. H == self.img_size[0] and W == self.img_size[1]
  179. ), f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
  180. x = self.proj(x).flatten(2).transpose((0, 2, 1))
  181. return x
  182. class VisionTransformer(nn.Layer):
  183. """Vision Transformer with support for patch input"""
  184. def __init__(
  185. self,
  186. img_size=224,
  187. patch_size=16,
  188. in_channels=3,
  189. class_num=1000,
  190. embed_dim=768,
  191. depth=12,
  192. num_heads=12,
  193. mlp_ratio=4,
  194. qkv_bias=False,
  195. qk_scale=None,
  196. drop_rate=0.0,
  197. attn_drop_rate=0.0,
  198. drop_path_rate=0.0,
  199. norm_layer="nn.LayerNorm",
  200. epsilon=1e-5,
  201. **kwargs,
  202. ):
  203. super().__init__()
  204. self.class_num = class_num
  205. self.num_features = self.embed_dim = embed_dim
  206. self.patch_embed = PatchEmbed(
  207. img_size=img_size,
  208. patch_size=patch_size,
  209. in_chans=in_channels,
  210. embed_dim=embed_dim,
  211. )
  212. num_patches = self.patch_embed.num_patches
  213. self.pos_embed = self.create_parameter(
  214. shape=(1, num_patches, embed_dim), default_initializer=zeros_
  215. )
  216. self.add_parameter("pos_embed", self.pos_embed)
  217. self.cls_token = self.create_parameter(
  218. shape=(1, 1, embed_dim), default_initializer=zeros_
  219. )
  220. self.add_parameter("cls_token", self.cls_token)
  221. self.pos_drop = nn.Dropout(p=drop_rate)
  222. dpr = np.linspace(0, drop_path_rate, depth)
  223. self.blocks = nn.LayerList(
  224. [
  225. Block(
  226. dim=embed_dim,
  227. num_heads=num_heads,
  228. mlp_ratio=mlp_ratio,
  229. qkv_bias=qkv_bias,
  230. qk_scale=qk_scale,
  231. drop=drop_rate,
  232. attn_drop=attn_drop_rate,
  233. drop_path=dpr[i],
  234. norm_layer=norm_layer,
  235. epsilon=epsilon,
  236. )
  237. for i in range(depth)
  238. ]
  239. )
  240. self.norm = eval(norm_layer)(embed_dim, epsilon=epsilon)
  241. # Classifier head
  242. self.head = nn.Linear(embed_dim, class_num) if class_num > 0 else Identity()
  243. trunc_normal_(self.pos_embed)
  244. self.out_channels = embed_dim
  245. self.apply(self._init_weights)
  246. def _init_weights(self, m):
  247. if isinstance(m, nn.Linear):
  248. trunc_normal_(m.weight)
  249. if isinstance(m, nn.Linear) and m.bias is not None:
  250. zeros_(m.bias)
  251. elif isinstance(m, nn.LayerNorm):
  252. zeros_(m.bias)
  253. ones_(m.weight)
  254. def forward_features(self, x):
  255. B = x.shape[0]
  256. x = self.patch_embed(x)
  257. x = x + self.pos_embed
  258. x = self.pos_drop(x)
  259. for blk in self.blocks:
  260. x = blk(x)
  261. x = self.norm(x)
  262. return x
  263. def forward(self, x):
  264. x = self.forward_features(x)
  265. x = self.head(x)
  266. return x
  267. class ViTParseQ(VisionTransformer):
  268. def __init__(
  269. self,
  270. img_size=[224, 224],
  271. patch_size=[16, 16],
  272. in_channels=3,
  273. embed_dim=768,
  274. depth=12,
  275. num_heads=12,
  276. mlp_ratio=4.0,
  277. qkv_bias=True,
  278. drop_rate=0.0,
  279. attn_drop_rate=0.0,
  280. drop_path_rate=0.0,
  281. ):
  282. super().__init__(
  283. img_size,
  284. patch_size,
  285. in_channels,
  286. embed_dim=embed_dim,
  287. depth=depth,
  288. num_heads=num_heads,
  289. mlp_ratio=mlp_ratio,
  290. qkv_bias=qkv_bias,
  291. drop_rate=drop_rate,
  292. attn_drop_rate=attn_drop_rate,
  293. drop_path_rate=drop_path_rate,
  294. class_num=0,
  295. )
  296. def forward(self, x):
  297. return self.forward_features(x)