modeling_convnext.py 21 KB

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