modeling_cvt.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. # coding=utf-8
  2. # Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch CvT model."""
  16. import collections.abc
  17. from dataclasses import dataclass
  18. from typing import Optional, Union
  19. import torch
  20. from torch import nn
  21. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  22. from ...modeling_outputs import ImageClassifierOutputWithNoAttention, ModelOutput
  23. from ...modeling_utils import PreTrainedModel
  24. from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
  25. from ...utils import auto_docstring, logging
  26. from .configuration_cvt import CvtConfig
  27. logger = logging.get_logger(__name__)
  28. @dataclass
  29. @auto_docstring(
  30. custom_intro="""
  31. Base class for model's outputs, with potential hidden states and attentions.
  32. """
  33. )
  34. class BaseModelOutputWithCLSToken(ModelOutput):
  35. r"""
  36. cls_token_value (`torch.FloatTensor` of shape `(batch_size, 1, hidden_size)`):
  37. Classification token at the output of the last layer of the model.
  38. """
  39. last_hidden_state: Optional[torch.FloatTensor] = None
  40. cls_token_value: Optional[torch.FloatTensor] = None
  41. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  42. # Copied from transformers.models.beit.modeling_beit.drop_path
  43. def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
  44. """
  45. Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  46. Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
  47. however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  48. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
  49. layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
  50. argument.
  51. """
  52. if drop_prob == 0.0 or not training:
  53. return input
  54. keep_prob = 1 - drop_prob
  55. shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  56. random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
  57. random_tensor.floor_() # binarize
  58. output = input.div(keep_prob) * random_tensor
  59. return output
  60. # Copied from transformers.models.beit.modeling_beit.BeitDropPath
  61. class CvtDropPath(nn.Module):
  62. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  63. def __init__(self, drop_prob: Optional[float] = None) -> None:
  64. super().__init__()
  65. self.drop_prob = drop_prob
  66. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  67. return drop_path(hidden_states, self.drop_prob, self.training)
  68. def extra_repr(self) -> str:
  69. return f"p={self.drop_prob}"
  70. class CvtEmbeddings(nn.Module):
  71. """
  72. Construct the CvT embeddings.
  73. """
  74. def __init__(self, patch_size, num_channels, embed_dim, stride, padding, dropout_rate):
  75. super().__init__()
  76. self.convolution_embeddings = CvtConvEmbeddings(
  77. patch_size=patch_size, num_channels=num_channels, embed_dim=embed_dim, stride=stride, padding=padding
  78. )
  79. self.dropout = nn.Dropout(dropout_rate)
  80. def forward(self, pixel_values):
  81. hidden_state = self.convolution_embeddings(pixel_values)
  82. hidden_state = self.dropout(hidden_state)
  83. return hidden_state
  84. class CvtConvEmbeddings(nn.Module):
  85. """
  86. Image to Conv Embedding.
  87. """
  88. def __init__(self, patch_size, num_channels, embed_dim, stride, padding):
  89. super().__init__()
  90. patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
  91. self.patch_size = patch_size
  92. self.projection = nn.Conv2d(num_channels, embed_dim, kernel_size=patch_size, stride=stride, padding=padding)
  93. self.normalization = nn.LayerNorm(embed_dim)
  94. def forward(self, pixel_values):
  95. pixel_values = self.projection(pixel_values)
  96. batch_size, num_channels, height, width = pixel_values.shape
  97. hidden_size = height * width
  98. # rearrange "b c h w -> b (h w) c"
  99. pixel_values = pixel_values.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
  100. if self.normalization:
  101. pixel_values = self.normalization(pixel_values)
  102. # rearrange "b (h w) c" -> b c h w"
  103. pixel_values = pixel_values.permute(0, 2, 1).view(batch_size, num_channels, height, width)
  104. return pixel_values
  105. class CvtSelfAttentionConvProjection(nn.Module):
  106. def __init__(self, embed_dim, kernel_size, padding, stride):
  107. super().__init__()
  108. self.convolution = nn.Conv2d(
  109. embed_dim,
  110. embed_dim,
  111. kernel_size=kernel_size,
  112. padding=padding,
  113. stride=stride,
  114. bias=False,
  115. groups=embed_dim,
  116. )
  117. self.normalization = nn.BatchNorm2d(embed_dim)
  118. def forward(self, hidden_state):
  119. hidden_state = self.convolution(hidden_state)
  120. hidden_state = self.normalization(hidden_state)
  121. return hidden_state
  122. class CvtSelfAttentionLinearProjection(nn.Module):
  123. def forward(self, hidden_state):
  124. batch_size, num_channels, height, width = hidden_state.shape
  125. hidden_size = height * width
  126. # rearrange " b c h w -> b (h w) c"
  127. hidden_state = hidden_state.view(batch_size, num_channels, hidden_size).permute(0, 2, 1)
  128. return hidden_state
  129. class CvtSelfAttentionProjection(nn.Module):
  130. def __init__(self, embed_dim, kernel_size, padding, stride, projection_method="dw_bn"):
  131. super().__init__()
  132. if projection_method == "dw_bn":
  133. self.convolution_projection = CvtSelfAttentionConvProjection(embed_dim, kernel_size, padding, stride)
  134. self.linear_projection = CvtSelfAttentionLinearProjection()
  135. def forward(self, hidden_state):
  136. hidden_state = self.convolution_projection(hidden_state)
  137. hidden_state = self.linear_projection(hidden_state)
  138. return hidden_state
  139. class CvtSelfAttention(nn.Module):
  140. def __init__(
  141. self,
  142. num_heads,
  143. embed_dim,
  144. kernel_size,
  145. padding_q,
  146. padding_kv,
  147. stride_q,
  148. stride_kv,
  149. qkv_projection_method,
  150. qkv_bias,
  151. attention_drop_rate,
  152. with_cls_token=True,
  153. **kwargs,
  154. ):
  155. super().__init__()
  156. self.scale = embed_dim**-0.5
  157. self.with_cls_token = with_cls_token
  158. self.embed_dim = embed_dim
  159. self.num_heads = num_heads
  160. self.convolution_projection_query = CvtSelfAttentionProjection(
  161. embed_dim,
  162. kernel_size,
  163. padding_q,
  164. stride_q,
  165. projection_method="linear" if qkv_projection_method == "avg" else qkv_projection_method,
  166. )
  167. self.convolution_projection_key = CvtSelfAttentionProjection(
  168. embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
  169. )
  170. self.convolution_projection_value = CvtSelfAttentionProjection(
  171. embed_dim, kernel_size, padding_kv, stride_kv, projection_method=qkv_projection_method
  172. )
  173. self.projection_query = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
  174. self.projection_key = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
  175. self.projection_value = nn.Linear(embed_dim, embed_dim, bias=qkv_bias)
  176. self.dropout = nn.Dropout(attention_drop_rate)
  177. def rearrange_for_multi_head_attention(self, hidden_state):
  178. batch_size, hidden_size, _ = hidden_state.shape
  179. head_dim = self.embed_dim // self.num_heads
  180. # rearrange 'b t (h d) -> b h t d'
  181. return hidden_state.view(batch_size, hidden_size, self.num_heads, head_dim).permute(0, 2, 1, 3)
  182. def forward(self, hidden_state, height, width):
  183. if self.with_cls_token:
  184. cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
  185. batch_size, hidden_size, num_channels = hidden_state.shape
  186. # rearrange "b (h w) c -> b c h w"
  187. hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
  188. key = self.convolution_projection_key(hidden_state)
  189. query = self.convolution_projection_query(hidden_state)
  190. value = self.convolution_projection_value(hidden_state)
  191. if self.with_cls_token:
  192. query = torch.cat((cls_token, query), dim=1)
  193. key = torch.cat((cls_token, key), dim=1)
  194. value = torch.cat((cls_token, value), dim=1)
  195. head_dim = self.embed_dim // self.num_heads
  196. query = self.rearrange_for_multi_head_attention(self.projection_query(query))
  197. key = self.rearrange_for_multi_head_attention(self.projection_key(key))
  198. value = self.rearrange_for_multi_head_attention(self.projection_value(value))
  199. attention_score = torch.einsum("bhlk,bhtk->bhlt", [query, key]) * self.scale
  200. attention_probs = torch.nn.functional.softmax(attention_score, dim=-1)
  201. attention_probs = self.dropout(attention_probs)
  202. context = torch.einsum("bhlt,bhtv->bhlv", [attention_probs, value])
  203. # rearrange"b h t d -> b t (h d)"
  204. _, _, hidden_size, _ = context.shape
  205. context = context.permute(0, 2, 1, 3).contiguous().view(batch_size, hidden_size, self.num_heads * head_dim)
  206. return context
  207. class CvtSelfOutput(nn.Module):
  208. """
  209. The residual connection is defined in CvtLayer instead of here (as is the case with other models), due to the
  210. layernorm applied before each block.
  211. """
  212. def __init__(self, embed_dim, drop_rate):
  213. super().__init__()
  214. self.dense = nn.Linear(embed_dim, embed_dim)
  215. self.dropout = nn.Dropout(drop_rate)
  216. def forward(self, hidden_state, input_tensor):
  217. hidden_state = self.dense(hidden_state)
  218. hidden_state = self.dropout(hidden_state)
  219. return hidden_state
  220. class CvtAttention(nn.Module):
  221. def __init__(
  222. self,
  223. num_heads,
  224. embed_dim,
  225. kernel_size,
  226. padding_q,
  227. padding_kv,
  228. stride_q,
  229. stride_kv,
  230. qkv_projection_method,
  231. qkv_bias,
  232. attention_drop_rate,
  233. drop_rate,
  234. with_cls_token=True,
  235. ):
  236. super().__init__()
  237. self.attention = CvtSelfAttention(
  238. num_heads,
  239. embed_dim,
  240. kernel_size,
  241. padding_q,
  242. padding_kv,
  243. stride_q,
  244. stride_kv,
  245. qkv_projection_method,
  246. qkv_bias,
  247. attention_drop_rate,
  248. with_cls_token,
  249. )
  250. self.output = CvtSelfOutput(embed_dim, drop_rate)
  251. self.pruned_heads = set()
  252. def prune_heads(self, heads):
  253. if len(heads) == 0:
  254. return
  255. heads, index = find_pruneable_heads_and_indices(
  256. heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
  257. )
  258. # Prune linear layers
  259. self.attention.query = prune_linear_layer(self.attention.query, index)
  260. self.attention.key = prune_linear_layer(self.attention.key, index)
  261. self.attention.value = prune_linear_layer(self.attention.value, index)
  262. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  263. # Update hyper params and store pruned heads
  264. self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
  265. self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
  266. self.pruned_heads = self.pruned_heads.union(heads)
  267. def forward(self, hidden_state, height, width):
  268. self_output = self.attention(hidden_state, height, width)
  269. attention_output = self.output(self_output, hidden_state)
  270. return attention_output
  271. class CvtIntermediate(nn.Module):
  272. def __init__(self, embed_dim, mlp_ratio):
  273. super().__init__()
  274. self.dense = nn.Linear(embed_dim, int(embed_dim * mlp_ratio))
  275. self.activation = nn.GELU()
  276. def forward(self, hidden_state):
  277. hidden_state = self.dense(hidden_state)
  278. hidden_state = self.activation(hidden_state)
  279. return hidden_state
  280. class CvtOutput(nn.Module):
  281. def __init__(self, embed_dim, mlp_ratio, drop_rate):
  282. super().__init__()
  283. self.dense = nn.Linear(int(embed_dim * mlp_ratio), embed_dim)
  284. self.dropout = nn.Dropout(drop_rate)
  285. def forward(self, hidden_state, input_tensor):
  286. hidden_state = self.dense(hidden_state)
  287. hidden_state = self.dropout(hidden_state)
  288. hidden_state = hidden_state + input_tensor
  289. return hidden_state
  290. class CvtLayer(nn.Module):
  291. """
  292. CvtLayer composed by attention layers, normalization and multi-layer perceptrons (mlps).
  293. """
  294. def __init__(
  295. self,
  296. num_heads,
  297. embed_dim,
  298. kernel_size,
  299. padding_q,
  300. padding_kv,
  301. stride_q,
  302. stride_kv,
  303. qkv_projection_method,
  304. qkv_bias,
  305. attention_drop_rate,
  306. drop_rate,
  307. mlp_ratio,
  308. drop_path_rate,
  309. with_cls_token=True,
  310. ):
  311. super().__init__()
  312. self.attention = CvtAttention(
  313. num_heads,
  314. embed_dim,
  315. kernel_size,
  316. padding_q,
  317. padding_kv,
  318. stride_q,
  319. stride_kv,
  320. qkv_projection_method,
  321. qkv_bias,
  322. attention_drop_rate,
  323. drop_rate,
  324. with_cls_token,
  325. )
  326. self.intermediate = CvtIntermediate(embed_dim, mlp_ratio)
  327. self.output = CvtOutput(embed_dim, mlp_ratio, drop_rate)
  328. self.drop_path = CvtDropPath(drop_prob=drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
  329. self.layernorm_before = nn.LayerNorm(embed_dim)
  330. self.layernorm_after = nn.LayerNorm(embed_dim)
  331. def forward(self, hidden_state, height, width):
  332. self_attention_output = self.attention(
  333. self.layernorm_before(hidden_state), # in Cvt, layernorm is applied before self-attention
  334. height,
  335. width,
  336. )
  337. attention_output = self_attention_output
  338. attention_output = self.drop_path(attention_output)
  339. # first residual connection
  340. hidden_state = attention_output + hidden_state
  341. # in Cvt, layernorm is also applied after self-attention
  342. layer_output = self.layernorm_after(hidden_state)
  343. layer_output = self.intermediate(layer_output)
  344. # second residual connection is done here
  345. layer_output = self.output(layer_output, hidden_state)
  346. layer_output = self.drop_path(layer_output)
  347. return layer_output
  348. class CvtStage(nn.Module):
  349. def __init__(self, config, stage):
  350. super().__init__()
  351. self.config = config
  352. self.stage = stage
  353. if self.config.cls_token[self.stage]:
  354. self.cls_token = nn.Parameter(torch.randn(1, 1, self.config.embed_dim[-1]))
  355. self.embedding = CvtEmbeddings(
  356. patch_size=config.patch_sizes[self.stage],
  357. stride=config.patch_stride[self.stage],
  358. num_channels=config.num_channels if self.stage == 0 else config.embed_dim[self.stage - 1],
  359. embed_dim=config.embed_dim[self.stage],
  360. padding=config.patch_padding[self.stage],
  361. dropout_rate=config.drop_rate[self.stage],
  362. )
  363. drop_path_rates = [
  364. x.item() for x in torch.linspace(0, config.drop_path_rate[self.stage], config.depth[stage], device="cpu")
  365. ]
  366. self.layers = nn.Sequential(
  367. *[
  368. CvtLayer(
  369. num_heads=config.num_heads[self.stage],
  370. embed_dim=config.embed_dim[self.stage],
  371. kernel_size=config.kernel_qkv[self.stage],
  372. padding_q=config.padding_q[self.stage],
  373. padding_kv=config.padding_kv[self.stage],
  374. stride_kv=config.stride_kv[self.stage],
  375. stride_q=config.stride_q[self.stage],
  376. qkv_projection_method=config.qkv_projection_method[self.stage],
  377. qkv_bias=config.qkv_bias[self.stage],
  378. attention_drop_rate=config.attention_drop_rate[self.stage],
  379. drop_rate=config.drop_rate[self.stage],
  380. drop_path_rate=drop_path_rates[self.stage],
  381. mlp_ratio=config.mlp_ratio[self.stage],
  382. with_cls_token=config.cls_token[self.stage],
  383. )
  384. for _ in range(config.depth[self.stage])
  385. ]
  386. )
  387. def forward(self, hidden_state):
  388. cls_token = None
  389. hidden_state = self.embedding(hidden_state)
  390. batch_size, num_channels, height, width = hidden_state.shape
  391. # rearrange b c h w -> b (h w) c"
  392. hidden_state = hidden_state.view(batch_size, num_channels, height * width).permute(0, 2, 1)
  393. if self.config.cls_token[self.stage]:
  394. cls_token = self.cls_token.expand(batch_size, -1, -1)
  395. hidden_state = torch.cat((cls_token, hidden_state), dim=1)
  396. for layer in self.layers:
  397. layer_outputs = layer(hidden_state, height, width)
  398. hidden_state = layer_outputs
  399. if self.config.cls_token[self.stage]:
  400. cls_token, hidden_state = torch.split(hidden_state, [1, height * width], 1)
  401. hidden_state = hidden_state.permute(0, 2, 1).view(batch_size, num_channels, height, width)
  402. return hidden_state, cls_token
  403. class CvtEncoder(nn.Module):
  404. def __init__(self, config):
  405. super().__init__()
  406. self.config = config
  407. self.stages = nn.ModuleList([])
  408. for stage_idx in range(len(config.depth)):
  409. self.stages.append(CvtStage(config, stage_idx))
  410. def forward(self, pixel_values, output_hidden_states=False, return_dict=True):
  411. all_hidden_states = () if output_hidden_states else None
  412. hidden_state = pixel_values
  413. cls_token = None
  414. for _, (stage_module) in enumerate(self.stages):
  415. hidden_state, cls_token = stage_module(hidden_state)
  416. if output_hidden_states:
  417. all_hidden_states = all_hidden_states + (hidden_state,)
  418. if not return_dict:
  419. return tuple(v for v in [hidden_state, cls_token, all_hidden_states] if v is not None)
  420. return BaseModelOutputWithCLSToken(
  421. last_hidden_state=hidden_state,
  422. cls_token_value=cls_token,
  423. hidden_states=all_hidden_states,
  424. )
  425. @auto_docstring
  426. class CvtPreTrainedModel(PreTrainedModel):
  427. config: CvtConfig
  428. base_model_prefix = "cvt"
  429. main_input_name = "pixel_values"
  430. _no_split_modules = ["CvtLayer"]
  431. def _init_weights(self, module):
  432. """Initialize the weights"""
  433. if isinstance(module, (nn.Linear, nn.Conv2d)):
  434. module.weight.data = nn.init.trunc_normal_(module.weight.data, mean=0.0, std=self.config.initializer_range)
  435. if module.bias is not None:
  436. module.bias.data.zero_()
  437. elif isinstance(module, nn.LayerNorm):
  438. module.bias.data.zero_()
  439. module.weight.data.fill_(1.0)
  440. elif isinstance(module, CvtStage):
  441. if self.config.cls_token[module.stage]:
  442. module.cls_token.data = nn.init.trunc_normal_(
  443. module.cls_token.data, mean=0.0, std=self.config.initializer_range
  444. )
  445. @auto_docstring
  446. class CvtModel(CvtPreTrainedModel):
  447. def __init__(self, config, add_pooling_layer=True):
  448. r"""
  449. add_pooling_layer (bool, *optional*, defaults to `True`):
  450. Whether to add a pooling layer
  451. """
  452. super().__init__(config)
  453. self.config = config
  454. self.encoder = CvtEncoder(config)
  455. self.post_init()
  456. def _prune_heads(self, heads_to_prune):
  457. """
  458. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  459. class PreTrainedModel
  460. """
  461. for layer, heads in heads_to_prune.items():
  462. self.encoder.layer[layer].attention.prune_heads(heads)
  463. @auto_docstring
  464. def forward(
  465. self,
  466. pixel_values: Optional[torch.Tensor] = None,
  467. output_hidden_states: Optional[bool] = None,
  468. return_dict: Optional[bool] = None,
  469. ) -> Union[tuple, BaseModelOutputWithCLSToken]:
  470. output_hidden_states = (
  471. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  472. )
  473. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  474. if pixel_values is None:
  475. raise ValueError("You have to specify pixel_values")
  476. encoder_outputs = self.encoder(
  477. pixel_values,
  478. output_hidden_states=output_hidden_states,
  479. return_dict=return_dict,
  480. )
  481. sequence_output = encoder_outputs[0]
  482. if not return_dict:
  483. return (sequence_output,) + encoder_outputs[1:]
  484. return BaseModelOutputWithCLSToken(
  485. last_hidden_state=sequence_output,
  486. cls_token_value=encoder_outputs.cls_token_value,
  487. hidden_states=encoder_outputs.hidden_states,
  488. )
  489. @auto_docstring(
  490. custom_intro="""
  491. Cvt Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
  492. the [CLS] token) e.g. for ImageNet.
  493. """
  494. )
  495. class CvtForImageClassification(CvtPreTrainedModel):
  496. def __init__(self, config):
  497. super().__init__(config)
  498. self.num_labels = config.num_labels
  499. self.cvt = CvtModel(config, add_pooling_layer=False)
  500. self.layernorm = nn.LayerNorm(config.embed_dim[-1])
  501. # Classifier head
  502. self.classifier = (
  503. nn.Linear(config.embed_dim[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
  504. )
  505. # Initialize weights and apply final processing
  506. self.post_init()
  507. @auto_docstring
  508. def forward(
  509. self,
  510. pixel_values: Optional[torch.Tensor] = None,
  511. labels: Optional[torch.Tensor] = None,
  512. output_hidden_states: Optional[bool] = None,
  513. return_dict: Optional[bool] = None,
  514. ) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
  515. r"""
  516. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  517. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  518. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  519. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  520. """
  521. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  522. outputs = self.cvt(
  523. pixel_values,
  524. output_hidden_states=output_hidden_states,
  525. return_dict=return_dict,
  526. )
  527. sequence_output = outputs[0]
  528. cls_token = outputs[1]
  529. if self.config.cls_token[-1]:
  530. sequence_output = self.layernorm(cls_token)
  531. else:
  532. batch_size, num_channels, height, width = sequence_output.shape
  533. # rearrange "b c h w -> b (h w) c"
  534. sequence_output = sequence_output.view(batch_size, num_channels, height * width).permute(0, 2, 1)
  535. sequence_output = self.layernorm(sequence_output)
  536. sequence_output_mean = sequence_output.mean(dim=1)
  537. logits = self.classifier(sequence_output_mean)
  538. loss = None
  539. if labels is not None:
  540. if self.config.problem_type is None:
  541. if self.config.num_labels == 1:
  542. self.config.problem_type = "regression"
  543. elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  544. self.config.problem_type = "single_label_classification"
  545. else:
  546. self.config.problem_type = "multi_label_classification"
  547. if self.config.problem_type == "regression":
  548. loss_fct = MSELoss()
  549. if self.config.num_labels == 1:
  550. loss = loss_fct(logits.squeeze(), labels.squeeze())
  551. else:
  552. loss = loss_fct(logits, labels)
  553. elif self.config.problem_type == "single_label_classification":
  554. loss_fct = CrossEntropyLoss()
  555. loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
  556. elif self.config.problem_type == "multi_label_classification":
  557. loss_fct = BCEWithLogitsLoss()
  558. loss = loss_fct(logits, labels)
  559. if not return_dict:
  560. output = (logits,) + outputs[2:]
  561. return ((loss,) + output) if loss is not None else output
  562. return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
  563. __all__ = ["CvtForImageClassification", "CvtModel", "CvtPreTrainedModel"]