modeling_convnextv2.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. # coding=utf-8
  2. # Copyright 2023 Meta Platforms, Inc. 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 ConvNextV2 model."""
  16. from typing import Optional, Tuple, Union
  17. import torch
  18. import torch.utils.checkpoint
  19. from torch import nn
  20. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  21. from ...activations import ACT2FN
  22. from ...modeling_outputs import (
  23. BackboneOutput,
  24. BaseModelOutputWithNoAttention,
  25. BaseModelOutputWithPoolingAndNoAttention,
  26. ImageClassifierOutputWithNoAttention,
  27. )
  28. from ...modeling_utils import PreTrainedModel
  29. from ...utils import (
  30. add_code_sample_docstrings,
  31. add_start_docstrings,
  32. add_start_docstrings_to_model_forward,
  33. logging,
  34. replace_return_docstrings,
  35. )
  36. from ...utils.backbone_utils import BackboneMixin
  37. from .configuration_convnextv2 import ConvNextV2Config
  38. logger = logging.get_logger(__name__)
  39. # General docstring
  40. _CONFIG_FOR_DOC = "ConvNextV2Config"
  41. # Base docstring
  42. _CHECKPOINT_FOR_DOC = "facebook/convnextv2-tiny-1k-224"
  43. _EXPECTED_OUTPUT_SHAPE = [1, 768, 7, 7]
  44. # Image classification docstring
  45. _IMAGE_CLASS_CHECKPOINT = "facebook/convnextv2-tiny-1k-224"
  46. _IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
  47. # Copied from transformers.models.beit.modeling_beit.drop_path
  48. def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
  49. """
  50. Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
  51. Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
  52. however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
  53. See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
  54. layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
  55. argument.
  56. """
  57. if drop_prob == 0.0 or not training:
  58. return input
  59. keep_prob = 1 - drop_prob
  60. shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
  61. random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
  62. random_tensor.floor_() # binarize
  63. output = input.div(keep_prob) * random_tensor
  64. return output
  65. # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->ConvNextV2
  66. class ConvNextV2DropPath(nn.Module):
  67. """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
  68. def __init__(self, drop_prob: Optional[float] = None) -> None:
  69. super().__init__()
  70. self.drop_prob = drop_prob
  71. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  72. return drop_path(hidden_states, self.drop_prob, self.training)
  73. def extra_repr(self) -> str:
  74. return "p={}".format(self.drop_prob)
  75. class ConvNextV2GRN(nn.Module):
  76. """GRN (Global Response Normalization) layer"""
  77. def __init__(self, dim: int):
  78. super().__init__()
  79. self.weight = nn.Parameter(torch.zeros(1, 1, 1, dim))
  80. self.bias = nn.Parameter(torch.zeros(1, 1, 1, dim))
  81. def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
  82. # Compute and normalize global spatial feature maps
  83. global_features = torch.norm(hidden_states, p=2, dim=(1, 2), keepdim=True)
  84. norm_features = global_features / (global_features.mean(dim=-1, keepdim=True) + 1e-6)
  85. hidden_states = self.weight * (hidden_states * norm_features) + self.bias + hidden_states
  86. return hidden_states
  87. # Copied from transformers.models.convnext.modeling_convnext.ConvNextLayerNorm with ConvNext->ConvNextV2
  88. class ConvNextV2LayerNorm(nn.Module):
  89. r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
  90. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
  91. width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
  92. """
  93. def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
  94. super().__init__()
  95. self.weight = nn.Parameter(torch.ones(normalized_shape))
  96. self.bias = nn.Parameter(torch.zeros(normalized_shape))
  97. self.eps = eps
  98. self.data_format = data_format
  99. if self.data_format not in ["channels_last", "channels_first"]:
  100. raise NotImplementedError(f"Unsupported data format: {self.data_format}")
  101. self.normalized_shape = (normalized_shape,)
  102. def forward(self, x: torch.Tensor) -> torch.Tensor:
  103. if self.data_format == "channels_last":
  104. x = torch.nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
  105. elif self.data_format == "channels_first":
  106. input_dtype = x.dtype
  107. x = x.float()
  108. u = x.mean(1, keepdim=True)
  109. s = (x - u).pow(2).mean(1, keepdim=True)
  110. x = (x - u) / torch.sqrt(s + self.eps)
  111. x = x.to(dtype=input_dtype)
  112. x = self.weight[:, None, None] * x + self.bias[:, None, None]
  113. return x
  114. # Copied from transformers.models.convnext.modeling_convnext.ConvNextEmbeddings with ConvNext->ConvNextV2
  115. class ConvNextV2Embeddings(nn.Module):
  116. """This class is comparable to (and inspired by) the SwinEmbeddings class
  117. found in src/transformers/models/swin/modeling_swin.py.
  118. """
  119. def __init__(self, config):
  120. super().__init__()
  121. self.patch_embeddings = nn.Conv2d(
  122. config.num_channels, config.hidden_sizes[0], kernel_size=config.patch_size, stride=config.patch_size
  123. )
  124. self.layernorm = ConvNextV2LayerNorm(config.hidden_sizes[0], eps=1e-6, data_format="channels_first")
  125. self.num_channels = config.num_channels
  126. def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
  127. num_channels = pixel_values.shape[1]
  128. if num_channels != self.num_channels:
  129. raise ValueError(
  130. "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
  131. )
  132. embeddings = self.patch_embeddings(pixel_values)
  133. embeddings = self.layernorm(embeddings)
  134. return embeddings
  135. class ConvNextV2Layer(nn.Module):
  136. """This corresponds to the `Block` class in the original implementation.
  137. There are two equivalent implementations: [DwConv, LayerNorm (channels_first), Conv, GELU,1x1 Conv]; all in (N, C,
  138. H, W) (2) [DwConv, Permute to (N, H, W, C), LayerNorm (channels_last), Linear, GELU, Linear]; Permute back
  139. The authors used (2) as they find it slightly faster in PyTorch.
  140. Args:
  141. config ([`ConvNextV2Config`]): Model configuration class.
  142. dim (`int`): Number of input channels.
  143. drop_path (`float`): Stochastic depth rate. Default: 0.0.
  144. """
  145. def __init__(self, config, dim, drop_path=0):
  146. super().__init__()
  147. # depthwise conv
  148. self.dwconv = nn.Conv2d(dim, dim, kernel_size=7, padding=3, groups=dim)
  149. self.layernorm = ConvNextV2LayerNorm(dim, eps=1e-6)
  150. # pointwise/1x1 convs, implemented with linear layers
  151. self.pwconv1 = nn.Linear(dim, 4 * dim)
  152. self.act = ACT2FN[config.hidden_act]
  153. self.grn = ConvNextV2GRN(4 * dim)
  154. self.pwconv2 = nn.Linear(4 * dim, dim)
  155. self.drop_path = ConvNextV2DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
  156. def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
  157. input = hidden_states
  158. x = self.dwconv(hidden_states)
  159. # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
  160. x = x.permute(0, 2, 3, 1)
  161. x = self.layernorm(x)
  162. x = self.pwconv1(x)
  163. x = self.act(x)
  164. x = self.grn(x)
  165. x = self.pwconv2(x)
  166. # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
  167. x = x.permute(0, 3, 1, 2)
  168. x = input + self.drop_path(x)
  169. return x
  170. # Copied from transformers.models.convnext.modeling_convnext.ConvNextStage with ConvNeXT->ConvNeXTV2, ConvNext->ConvNextV2
  171. class ConvNextV2Stage(nn.Module):
  172. """ConvNeXTV2 stage, consisting of an optional downsampling layer + multiple residual blocks.
  173. Args:
  174. config ([`ConvNextV2Config`]): Model configuration class.
  175. in_channels (`int`): Number of input channels.
  176. out_channels (`int`): Number of output channels.
  177. depth (`int`): Number of residual blocks.
  178. drop_path_rates(`List[float]`): Stochastic depth rates for each layer.
  179. """
  180. def __init__(self, config, in_channels, out_channels, kernel_size=2, stride=2, depth=2, drop_path_rates=None):
  181. super().__init__()
  182. if in_channels != out_channels or stride > 1:
  183. self.downsampling_layer = nn.Sequential(
  184. ConvNextV2LayerNorm(in_channels, eps=1e-6, data_format="channels_first"),
  185. nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride),
  186. )
  187. else:
  188. self.downsampling_layer = nn.Identity()
  189. drop_path_rates = drop_path_rates or [0.0] * depth
  190. self.layers = nn.Sequential(
  191. *[ConvNextV2Layer(config, dim=out_channels, drop_path=drop_path_rates[j]) for j in range(depth)]
  192. )
  193. def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
  194. hidden_states = self.downsampling_layer(hidden_states)
  195. hidden_states = self.layers(hidden_states)
  196. return hidden_states
  197. # Copied from transformers.models.convnext.modeling_convnext.ConvNextEncoder with ConvNext->ConvNextV2
  198. class ConvNextV2Encoder(nn.Module):
  199. def __init__(self, config):
  200. super().__init__()
  201. self.stages = nn.ModuleList()
  202. drop_path_rates = [
  203. x.tolist() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths)).split(config.depths)
  204. ]
  205. prev_chs = config.hidden_sizes[0]
  206. for i in range(config.num_stages):
  207. out_chs = config.hidden_sizes[i]
  208. stage = ConvNextV2Stage(
  209. config,
  210. in_channels=prev_chs,
  211. out_channels=out_chs,
  212. stride=2 if i > 0 else 1,
  213. depth=config.depths[i],
  214. drop_path_rates=drop_path_rates[i],
  215. )
  216. self.stages.append(stage)
  217. prev_chs = out_chs
  218. def forward(
  219. self,
  220. hidden_states: torch.FloatTensor,
  221. output_hidden_states: Optional[bool] = False,
  222. return_dict: Optional[bool] = True,
  223. ) -> Union[Tuple, BaseModelOutputWithNoAttention]:
  224. all_hidden_states = () if output_hidden_states else None
  225. for i, layer_module in enumerate(self.stages):
  226. if output_hidden_states:
  227. all_hidden_states = all_hidden_states + (hidden_states,)
  228. hidden_states = layer_module(hidden_states)
  229. if output_hidden_states:
  230. all_hidden_states = all_hidden_states + (hidden_states,)
  231. if not return_dict:
  232. return tuple(v for v in [hidden_states, all_hidden_states] if v is not None)
  233. return BaseModelOutputWithNoAttention(
  234. last_hidden_state=hidden_states,
  235. hidden_states=all_hidden_states,
  236. )
  237. # Copied from transformers.models.convnext.modeling_convnext.ConvNextPreTrainedModel with ConvNext->ConvNextV2, convnext->convnextv2
  238. class ConvNextV2PreTrainedModel(PreTrainedModel):
  239. """
  240. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  241. models.
  242. """
  243. config_class = ConvNextV2Config
  244. base_model_prefix = "convnextv2"
  245. main_input_name = "pixel_values"
  246. _no_split_modules = ["ConvNextV2Layer"]
  247. def _init_weights(self, module):
  248. """Initialize the weights"""
  249. if isinstance(module, (nn.Linear, nn.Conv2d)):
  250. # Slightly different from the TF version which uses truncated_normal for initialization
  251. # cf https://github.com/pytorch/pytorch/pull/5617
  252. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  253. if module.bias is not None:
  254. module.bias.data.zero_()
  255. elif isinstance(module, nn.LayerNorm):
  256. module.bias.data.zero_()
  257. module.weight.data.fill_(1.0)
  258. CONVNEXTV2_START_DOCSTRING = r"""
  259. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
  260. as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
  261. behavior.
  262. Parameters:
  263. config ([`ConvNextV2Config`]): Model configuration class with all the parameters of the model.
  264. Initializing with a config file does not load the weights associated with the model, only the
  265. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  266. """
  267. CONVNEXTV2_INPUTS_DOCSTRING = r"""
  268. Args:
  269. pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
  270. Pixel values. Pixel values can be obtained using [`ConvNextImageProcessor`]. See
  271. [`ConvNextImageProcessor.__call__`] for details.
  272. output_hidden_states (`bool`, *optional*):
  273. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  274. more detail.
  275. return_dict (`bool`, *optional*):
  276. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  277. """
  278. @add_start_docstrings(
  279. "The bare ConvNextV2 model outputting raw features without any specific head on top.",
  280. CONVNEXTV2_START_DOCSTRING,
  281. )
  282. # Copied from transformers.models.convnext.modeling_convnext.ConvNextModel with CONVNEXT->CONVNEXTV2, ConvNext->ConvNextV2
  283. class ConvNextV2Model(ConvNextV2PreTrainedModel):
  284. def __init__(self, config):
  285. super().__init__(config)
  286. self.config = config
  287. self.embeddings = ConvNextV2Embeddings(config)
  288. self.encoder = ConvNextV2Encoder(config)
  289. # final layernorm layer
  290. self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
  291. # Initialize weights and apply final processing
  292. self.post_init()
  293. @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
  294. @add_code_sample_docstrings(
  295. checkpoint=_CHECKPOINT_FOR_DOC,
  296. output_type=BaseModelOutputWithPoolingAndNoAttention,
  297. config_class=_CONFIG_FOR_DOC,
  298. modality="vision",
  299. expected_output=_EXPECTED_OUTPUT_SHAPE,
  300. )
  301. def forward(
  302. self,
  303. pixel_values: torch.FloatTensor = None,
  304. output_hidden_states: Optional[bool] = None,
  305. return_dict: Optional[bool] = None,
  306. ) -> Union[Tuple, BaseModelOutputWithPoolingAndNoAttention]:
  307. output_hidden_states = (
  308. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  309. )
  310. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  311. if pixel_values is None:
  312. raise ValueError("You have to specify pixel_values")
  313. embedding_output = self.embeddings(pixel_values)
  314. encoder_outputs = self.encoder(
  315. embedding_output,
  316. output_hidden_states=output_hidden_states,
  317. return_dict=return_dict,
  318. )
  319. last_hidden_state = encoder_outputs[0]
  320. # global average pooling, (N, C, H, W) -> (N, C)
  321. pooled_output = self.layernorm(last_hidden_state.mean([-2, -1]))
  322. if not return_dict:
  323. return (last_hidden_state, pooled_output) + encoder_outputs[1:]
  324. return BaseModelOutputWithPoolingAndNoAttention(
  325. last_hidden_state=last_hidden_state,
  326. pooler_output=pooled_output,
  327. hidden_states=encoder_outputs.hidden_states,
  328. )
  329. @add_start_docstrings(
  330. """
  331. ConvNextV2 Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
  332. ImageNet.
  333. """,
  334. CONVNEXTV2_START_DOCSTRING,
  335. )
  336. # Copied from transformers.models.convnext.modeling_convnext.ConvNextForImageClassification with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,convnext->convnextv2
  337. class ConvNextV2ForImageClassification(ConvNextV2PreTrainedModel):
  338. def __init__(self, config):
  339. super().__init__(config)
  340. self.num_labels = config.num_labels
  341. self.convnextv2 = ConvNextV2Model(config)
  342. # Classifier head
  343. self.classifier = (
  344. nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
  345. )
  346. # Initialize weights and apply final processing
  347. self.post_init()
  348. @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
  349. @add_code_sample_docstrings(
  350. checkpoint=_IMAGE_CLASS_CHECKPOINT,
  351. output_type=ImageClassifierOutputWithNoAttention,
  352. config_class=_CONFIG_FOR_DOC,
  353. expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
  354. )
  355. def forward(
  356. self,
  357. pixel_values: torch.FloatTensor = None,
  358. labels: Optional[torch.LongTensor] = None,
  359. output_hidden_states: Optional[bool] = None,
  360. return_dict: Optional[bool] = None,
  361. ) -> Union[Tuple, ImageClassifierOutputWithNoAttention]:
  362. r"""
  363. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  364. Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
  365. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  366. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  367. """
  368. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  369. outputs = self.convnextv2(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
  370. pooled_output = outputs.pooler_output if return_dict else outputs[1]
  371. logits = self.classifier(pooled_output)
  372. loss = None
  373. if labels is not None:
  374. if self.config.problem_type is None:
  375. if self.num_labels == 1:
  376. self.config.problem_type = "regression"
  377. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  378. self.config.problem_type = "single_label_classification"
  379. else:
  380. self.config.problem_type = "multi_label_classification"
  381. if self.config.problem_type == "regression":
  382. loss_fct = MSELoss()
  383. if self.num_labels == 1:
  384. loss = loss_fct(logits.squeeze(), labels.squeeze())
  385. else:
  386. loss = loss_fct(logits, labels)
  387. elif self.config.problem_type == "single_label_classification":
  388. loss_fct = CrossEntropyLoss()
  389. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  390. elif self.config.problem_type == "multi_label_classification":
  391. loss_fct = BCEWithLogitsLoss()
  392. loss = loss_fct(logits, labels)
  393. if not return_dict:
  394. output = (logits,) + outputs[2:]
  395. return ((loss,) + output) if loss is not None else output
  396. return ImageClassifierOutputWithNoAttention(
  397. loss=loss,
  398. logits=logits,
  399. hidden_states=outputs.hidden_states,
  400. )
  401. @add_start_docstrings(
  402. """
  403. ConvNeXT V2 backbone, to be used with frameworks like DETR and MaskFormer.
  404. """,
  405. CONVNEXTV2_START_DOCSTRING,
  406. )
  407. # Copied from transformers.models.convnext.modeling_convnext.ConvNextBackbone with CONVNEXT->CONVNEXTV2,ConvNext->ConvNextV2,facebook/convnext-tiny-224->facebook/convnextv2-tiny-1k-224
  408. class ConvNextV2Backbone(ConvNextV2PreTrainedModel, BackboneMixin):
  409. def __init__(self, config):
  410. super().__init__(config)
  411. super()._init_backbone(config)
  412. self.embeddings = ConvNextV2Embeddings(config)
  413. self.encoder = ConvNextV2Encoder(config)
  414. self.num_features = [config.hidden_sizes[0]] + config.hidden_sizes
  415. # Add layer norms to hidden states of out_features
  416. hidden_states_norms = {}
  417. for stage, num_channels in zip(self._out_features, self.channels):
  418. hidden_states_norms[stage] = ConvNextV2LayerNorm(num_channels, data_format="channels_first")
  419. self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
  420. # initialize weights and apply final processing
  421. self.post_init()
  422. @add_start_docstrings_to_model_forward(CONVNEXTV2_INPUTS_DOCSTRING)
  423. @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
  424. def forward(
  425. self,
  426. pixel_values: torch.Tensor,
  427. output_hidden_states: Optional[bool] = None,
  428. return_dict: Optional[bool] = None,
  429. ) -> BackboneOutput:
  430. """
  431. Returns:
  432. Examples:
  433. ```python
  434. >>> from transformers import AutoImageProcessor, AutoBackbone
  435. >>> import torch
  436. >>> from PIL import Image
  437. >>> import requests
  438. >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
  439. >>> image = Image.open(requests.get(url, stream=True).raw)
  440. >>> processor = AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224")
  441. >>> model = AutoBackbone.from_pretrained("facebook/convnextv2-tiny-1k-224")
  442. >>> inputs = processor(image, return_tensors="pt")
  443. >>> outputs = model(**inputs)
  444. ```"""
  445. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  446. output_hidden_states = (
  447. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  448. )
  449. embedding_output = self.embeddings(pixel_values)
  450. outputs = self.encoder(
  451. embedding_output,
  452. output_hidden_states=True,
  453. return_dict=return_dict,
  454. )
  455. hidden_states = outputs.hidden_states if return_dict else outputs[1]
  456. feature_maps = ()
  457. for stage, hidden_state in zip(self.stage_names, hidden_states):
  458. if stage in self.out_features:
  459. hidden_state = self.hidden_states_norms[stage](hidden_state)
  460. feature_maps += (hidden_state,)
  461. if not return_dict:
  462. output = (feature_maps,)
  463. if output_hidden_states:
  464. output += (hidden_states,)
  465. return output
  466. return BackboneOutput(
  467. feature_maps=feature_maps,
  468. hidden_states=hidden_states if output_hidden_states else None,
  469. attentions=None,
  470. )