modeling_pvt.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. # Copyright 2023 Authors: Wenhai Wang, Enze Xie, Xiang Li, Deng-Ping Fan,
  2. # Kaitao Song, Ding Liang, Tong Lu, Ping Luo, Ling Shao and The HuggingFace Inc. team.
  3. # All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """PyTorch PVT model."""
  17. import collections
  18. import math
  19. from collections.abc import Iterable
  20. import torch
  21. import torch.nn.functional as F
  22. from torch import nn
  23. from ... import initialization as init
  24. from ...activations import ACT2FN
  25. from ...modeling_outputs import BaseModelOutput, ImageClassifierOutput
  26. from ...modeling_utils import PreTrainedModel
  27. from ...utils import auto_docstring, logging
  28. from .configuration_pvt import PvtConfig
  29. logger = logging.get_logger(__name__)
  30. # Copied from transformers.models.beit.modeling_beit.drop_path
  31. def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
  32. """
  33. Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  34. """
  35. if drop_prob == 0.0 or not training:
  36. return input
  37. keep_prob = 1 - drop_prob
  38. shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  39. random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
  40. random_tensor.floor_() # binarize
  41. output = input.div(keep_prob) * random_tensor
  42. return output
  43. # Copied from transformers.models.convnext.modeling_convnext.ConvNextDropPath with ConvNext->Pvt
  44. class PvtDropPath(nn.Module):
  45. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  46. def __init__(self, drop_prob: float | None = None) -> None:
  47. super().__init__()
  48. self.drop_prob = drop_prob
  49. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  50. return drop_path(hidden_states, self.drop_prob, self.training)
  51. def extra_repr(self) -> str:
  52. return f"p={self.drop_prob}"
  53. class PvtPatchEmbeddings(nn.Module):
  54. """
  55. This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
  56. `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
  57. Transformer.
  58. """
  59. def __init__(
  60. self,
  61. config: PvtConfig,
  62. image_size: int | Iterable[int],
  63. patch_size: int | Iterable[int],
  64. stride: int,
  65. num_channels: int,
  66. hidden_size: int,
  67. cls_token: bool = False,
  68. ):
  69. super().__init__()
  70. self.config = config
  71. image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
  72. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  73. num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
  74. self.image_size = image_size
  75. self.patch_size = patch_size
  76. self.num_channels = num_channels
  77. self.num_patches = num_patches
  78. self.position_embeddings = nn.Parameter(
  79. torch.randn(1, num_patches + 1 if cls_token else num_patches, hidden_size)
  80. )
  81. self.cls_token = nn.Parameter(torch.zeros(1, 1, hidden_size)) if cls_token else None
  82. self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=stride, stride=patch_size)
  83. self.layer_norm = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
  84. self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
  85. def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
  86. num_patches = height * width
  87. # always interpolate when tracing to ensure the exported model works for dynamic input shapes
  88. if not torch.jit.is_tracing() and num_patches == self.config.image_size * self.config.image_size:
  89. return self.position_embeddings
  90. embeddings = embeddings.reshape(1, height, width, -1).permute(0, 3, 1, 2)
  91. interpolated_embeddings = F.interpolate(embeddings, size=(height, width), mode="bilinear")
  92. interpolated_embeddings = interpolated_embeddings.reshape(1, -1, height * width).permute(0, 2, 1)
  93. return interpolated_embeddings
  94. def forward(self, pixel_values: torch.Tensor) -> tuple[torch.Tensor, int, int]:
  95. batch_size, num_channels, height, width = pixel_values.shape
  96. if num_channels != self.num_channels:
  97. raise ValueError(
  98. "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
  99. )
  100. patch_embed = self.projection(pixel_values)
  101. *_, height, width = patch_embed.shape
  102. patch_embed = patch_embed.flatten(2).transpose(1, 2)
  103. embeddings = self.layer_norm(patch_embed)
  104. if self.cls_token is not None:
  105. cls_token = self.cls_token.expand(batch_size, -1, -1)
  106. embeddings = torch.cat((cls_token, embeddings), dim=1)
  107. position_embeddings = self.interpolate_pos_encoding(self.position_embeddings[:, 1:], height, width)
  108. position_embeddings = torch.cat((self.position_embeddings[:, :1], position_embeddings), dim=1)
  109. else:
  110. position_embeddings = self.interpolate_pos_encoding(self.position_embeddings, height, width)
  111. embeddings = self.dropout(embeddings + position_embeddings)
  112. return embeddings, height, width
  113. class PvtSelfOutput(nn.Module):
  114. def __init__(self, config: PvtConfig, hidden_size: int):
  115. super().__init__()
  116. self.dense = nn.Linear(hidden_size, hidden_size)
  117. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  118. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  119. hidden_states = self.dense(hidden_states)
  120. hidden_states = self.dropout(hidden_states)
  121. return hidden_states
  122. class PvtEfficientSelfAttention(nn.Module):
  123. """Efficient self-attention mechanism with reduction of the sequence [PvT paper](https://huggingface.co/papers/2102.12122)."""
  124. def __init__(
  125. self, config: PvtConfig, hidden_size: int, num_attention_heads: int, sequences_reduction_ratio: float
  126. ):
  127. super().__init__()
  128. self.hidden_size = hidden_size
  129. self.num_attention_heads = num_attention_heads
  130. if self.hidden_size % self.num_attention_heads != 0:
  131. raise ValueError(
  132. f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
  133. f"heads ({self.num_attention_heads})"
  134. )
  135. self.attention_head_size = int(self.hidden_size / self.num_attention_heads)
  136. self.all_head_size = self.num_attention_heads * self.attention_head_size
  137. self.query = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias)
  138. self.key = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias)
  139. self.value = nn.Linear(self.hidden_size, self.all_head_size, bias=config.qkv_bias)
  140. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  141. self.sequences_reduction_ratio = sequences_reduction_ratio
  142. if sequences_reduction_ratio > 1:
  143. self.sequence_reduction = nn.Conv2d(
  144. hidden_size, hidden_size, kernel_size=sequences_reduction_ratio, stride=sequences_reduction_ratio
  145. )
  146. self.layer_norm = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
  147. def transpose_for_scores(self, hidden_states: int) -> torch.Tensor:
  148. new_shape = hidden_states.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  149. hidden_states = hidden_states.view(new_shape)
  150. return hidden_states.permute(0, 2, 1, 3)
  151. def forward(
  152. self,
  153. hidden_states: torch.Tensor,
  154. height: int,
  155. width: int,
  156. output_attentions: bool = False,
  157. ) -> tuple[torch.Tensor]:
  158. query_layer = self.transpose_for_scores(self.query(hidden_states))
  159. if self.sequences_reduction_ratio > 1:
  160. batch_size, seq_len, num_channels = hidden_states.shape
  161. # Reshape to (batch_size, num_channels, height, width)
  162. hidden_states = hidden_states.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
  163. # Apply sequence reduction
  164. hidden_states = self.sequence_reduction(hidden_states)
  165. # Reshape back to (batch_size, seq_len, num_channels)
  166. hidden_states = hidden_states.reshape(batch_size, num_channels, -1).permute(0, 2, 1)
  167. hidden_states = self.layer_norm(hidden_states)
  168. key_layer = self.transpose_for_scores(self.key(hidden_states))
  169. value_layer = self.transpose_for_scores(self.value(hidden_states))
  170. # Take the dot product between "query" and "key" to get the raw attention scores.
  171. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  172. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  173. # Normalize the attention scores to probabilities.
  174. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  175. # This is actually dropping out entire tokens to attend to, which might
  176. # seem a bit unusual, but is taken from the original Transformer paper.
  177. attention_probs = self.dropout(attention_probs)
  178. context_layer = torch.matmul(attention_probs, value_layer)
  179. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  180. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  181. context_layer = context_layer.view(new_context_layer_shape)
  182. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  183. return outputs
  184. class PvtAttention(nn.Module):
  185. def __init__(
  186. self, config: PvtConfig, hidden_size: int, num_attention_heads: int, sequences_reduction_ratio: float
  187. ):
  188. super().__init__()
  189. self.self = PvtEfficientSelfAttention(
  190. config,
  191. hidden_size=hidden_size,
  192. num_attention_heads=num_attention_heads,
  193. sequences_reduction_ratio=sequences_reduction_ratio,
  194. )
  195. self.output = PvtSelfOutput(config, hidden_size=hidden_size)
  196. def forward(
  197. self, hidden_states: torch.Tensor, height: int, width: int, output_attentions: bool = False
  198. ) -> tuple[torch.Tensor]:
  199. self_outputs = self.self(hidden_states, height, width, output_attentions)
  200. attention_output = self.output(self_outputs[0])
  201. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  202. return outputs
  203. class PvtFFN(nn.Module):
  204. def __init__(
  205. self,
  206. config: PvtConfig,
  207. in_features: int,
  208. hidden_features: int | None = None,
  209. out_features: int | None = None,
  210. ):
  211. super().__init__()
  212. out_features = out_features if out_features is not None else in_features
  213. self.dense1 = nn.Linear(in_features, hidden_features)
  214. if isinstance(config.hidden_act, str):
  215. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  216. else:
  217. self.intermediate_act_fn = config.hidden_act
  218. self.dense2 = nn.Linear(hidden_features, out_features)
  219. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  220. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  221. hidden_states = self.dense1(hidden_states)
  222. hidden_states = self.intermediate_act_fn(hidden_states)
  223. hidden_states = self.dropout(hidden_states)
  224. hidden_states = self.dense2(hidden_states)
  225. hidden_states = self.dropout(hidden_states)
  226. return hidden_states
  227. class PvtLayer(nn.Module):
  228. def __init__(
  229. self,
  230. config: PvtConfig,
  231. hidden_size: int,
  232. num_attention_heads: int,
  233. drop_path: float,
  234. sequences_reduction_ratio: float,
  235. mlp_ratio: float,
  236. ):
  237. super().__init__()
  238. self.layer_norm_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
  239. self.attention = PvtAttention(
  240. config=config,
  241. hidden_size=hidden_size,
  242. num_attention_heads=num_attention_heads,
  243. sequences_reduction_ratio=sequences_reduction_ratio,
  244. )
  245. self.drop_path = PvtDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
  246. self.layer_norm_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
  247. mlp_hidden_size = int(hidden_size * mlp_ratio)
  248. self.mlp = PvtFFN(config=config, in_features=hidden_size, hidden_features=mlp_hidden_size)
  249. def forward(self, hidden_states: torch.Tensor, height: int, width: int, output_attentions: bool = False):
  250. self_attention_outputs = self.attention(
  251. hidden_states=self.layer_norm_1(hidden_states),
  252. height=height,
  253. width=width,
  254. output_attentions=output_attentions,
  255. )
  256. attention_output = self_attention_outputs[0]
  257. outputs = self_attention_outputs[1:]
  258. attention_output = self.drop_path(attention_output)
  259. hidden_states = attention_output + hidden_states
  260. mlp_output = self.mlp(self.layer_norm_2(hidden_states))
  261. mlp_output = self.drop_path(mlp_output)
  262. layer_output = hidden_states + mlp_output
  263. outputs = (layer_output,) + outputs
  264. return outputs
  265. class PvtEncoder(nn.Module):
  266. def __init__(self, config: PvtConfig):
  267. super().__init__()
  268. self.config = config
  269. # stochastic depth decay rule
  270. drop_path_decays = torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu").tolist()
  271. # patch embeddings
  272. embeddings = []
  273. for i in range(config.num_encoder_blocks):
  274. embeddings.append(
  275. PvtPatchEmbeddings(
  276. config=config,
  277. image_size=config.image_size if i == 0 else self.config.image_size // (2 ** (i + 1)),
  278. patch_size=config.patch_sizes[i],
  279. stride=config.strides[i],
  280. num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1],
  281. hidden_size=config.hidden_sizes[i],
  282. cls_token=i == config.num_encoder_blocks - 1,
  283. )
  284. )
  285. self.patch_embeddings = nn.ModuleList(embeddings)
  286. # Transformer blocks
  287. blocks = []
  288. cur = 0
  289. for i in range(config.num_encoder_blocks):
  290. # each block consists of layers
  291. layers = []
  292. if i != 0:
  293. cur += config.depths[i - 1]
  294. for j in range(config.depths[i]):
  295. layers.append(
  296. PvtLayer(
  297. config=config,
  298. hidden_size=config.hidden_sizes[i],
  299. num_attention_heads=config.num_attention_heads[i],
  300. drop_path=drop_path_decays[cur + j],
  301. sequences_reduction_ratio=config.sequence_reduction_ratios[i],
  302. mlp_ratio=config.mlp_ratios[i],
  303. )
  304. )
  305. blocks.append(nn.ModuleList(layers))
  306. self.block = nn.ModuleList(blocks)
  307. # Layer norms
  308. self.layer_norm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
  309. def forward(
  310. self,
  311. pixel_values: torch.FloatTensor,
  312. output_attentions: bool | None = False,
  313. output_hidden_states: bool | None = False,
  314. return_dict: bool | None = True,
  315. ) -> tuple | BaseModelOutput:
  316. all_hidden_states = () if output_hidden_states else None
  317. all_self_attentions = () if output_attentions else None
  318. batch_size = pixel_values.shape[0]
  319. num_blocks = len(self.block)
  320. hidden_states = pixel_values
  321. for idx, (embedding_layer, block_layer) in enumerate(zip(self.patch_embeddings, self.block)):
  322. # first, obtain patch embeddings
  323. hidden_states, height, width = embedding_layer(hidden_states)
  324. # second, send embeddings through blocks
  325. for block in block_layer:
  326. layer_outputs = block(hidden_states, height, width, output_attentions)
  327. hidden_states = layer_outputs[0]
  328. if output_attentions:
  329. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  330. if output_hidden_states:
  331. all_hidden_states = all_hidden_states + (hidden_states,)
  332. if idx != num_blocks - 1:
  333. hidden_states = hidden_states.reshape(batch_size, height, width, -1).permute(0, 3, 1, 2).contiguous()
  334. hidden_states = self.layer_norm(hidden_states)
  335. if output_hidden_states:
  336. all_hidden_states = all_hidden_states + (hidden_states,)
  337. if not return_dict:
  338. return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
  339. return BaseModelOutput(
  340. last_hidden_state=hidden_states,
  341. hidden_states=all_hidden_states,
  342. attentions=all_self_attentions,
  343. )
  344. @auto_docstring
  345. class PvtPreTrainedModel(PreTrainedModel):
  346. config: PvtConfig
  347. base_model_prefix = "pvt"
  348. main_input_name = "pixel_values"
  349. input_modalities = ("image",)
  350. _no_split_modules = []
  351. @torch.no_grad()
  352. def _init_weights(self, module: nn.Module) -> None:
  353. """Initialize the weights"""
  354. std = self.config.initializer_range
  355. if isinstance(module, (nn.Linear, nn.Conv2d)):
  356. init.trunc_normal_(module.weight, mean=0.0, std=std)
  357. if module.bias is not None:
  358. init.zeros_(module.bias)
  359. elif isinstance(module, nn.LayerNorm):
  360. init.zeros_(module.bias)
  361. init.ones_(module.weight)
  362. elif isinstance(module, PvtPatchEmbeddings):
  363. init.trunc_normal_(module.position_embeddings, mean=0.0, std=std)
  364. if module.cls_token is not None:
  365. init.trunc_normal_(module.cls_token, mean=0.0, std=std)
  366. @auto_docstring
  367. class PvtModel(PvtPreTrainedModel):
  368. def __init__(self, config: PvtConfig):
  369. super().__init__(config)
  370. self.config = config
  371. # hierarchical Transformer encoder
  372. self.encoder = PvtEncoder(config)
  373. # Initialize weights and apply final processing
  374. self.post_init()
  375. @auto_docstring
  376. def forward(
  377. self,
  378. pixel_values: torch.FloatTensor,
  379. output_attentions: bool | None = None,
  380. output_hidden_states: bool | None = None,
  381. return_dict: bool | None = None,
  382. **kwargs,
  383. ) -> tuple | BaseModelOutput:
  384. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  385. output_hidden_states = (
  386. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  387. )
  388. return_dict = return_dict if return_dict is not None else self.config.return_dict
  389. encoder_outputs = self.encoder(
  390. pixel_values=pixel_values,
  391. output_attentions=output_attentions,
  392. output_hidden_states=output_hidden_states,
  393. return_dict=return_dict,
  394. )
  395. sequence_output = encoder_outputs[0]
  396. if not return_dict:
  397. return (sequence_output,) + encoder_outputs[1:]
  398. return BaseModelOutput(
  399. last_hidden_state=sequence_output,
  400. hidden_states=encoder_outputs.hidden_states,
  401. attentions=encoder_outputs.attentions,
  402. )
  403. @auto_docstring(
  404. custom_intro="""
  405. Pvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
  406. the [CLS] token) e.g. for ImageNet.
  407. """
  408. )
  409. class PvtForImageClassification(PvtPreTrainedModel):
  410. def __init__(self, config: PvtConfig) -> None:
  411. super().__init__(config)
  412. self.num_labels = config.num_labels
  413. self.pvt = PvtModel(config)
  414. # Classifier head
  415. self.classifier = (
  416. nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
  417. )
  418. # Initialize weights and apply final processing
  419. self.post_init()
  420. @auto_docstring
  421. def forward(
  422. self,
  423. pixel_values: torch.Tensor | None,
  424. labels: torch.Tensor | None = None,
  425. output_attentions: bool | None = None,
  426. output_hidden_states: bool | None = None,
  427. return_dict: bool | None = None,
  428. **kwargs,
  429. ) -> tuple | ImageClassifierOutput:
  430. r"""
  431. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  432. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  433. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  434. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  435. """
  436. return_dict = return_dict if return_dict is not None else self.config.return_dict
  437. outputs = self.pvt(
  438. pixel_values=pixel_values,
  439. output_attentions=output_attentions,
  440. output_hidden_states=output_hidden_states,
  441. return_dict=return_dict,
  442. )
  443. sequence_output = outputs[0]
  444. logits = self.classifier(sequence_output[:, 0, :])
  445. loss = None
  446. if labels is not None:
  447. loss = self.loss_function(labels, logits, self.config)
  448. if not return_dict:
  449. output = (logits,) + outputs[1:]
  450. return ((loss,) + output) if loss is not None else output
  451. return ImageClassifierOutput(
  452. loss=loss,
  453. logits=logits,
  454. hidden_states=outputs.hidden_states,
  455. attentions=outputs.attentions,
  456. )
  457. __all__ = ["PvtForImageClassification", "PvtModel", "PvtPreTrainedModel"]