configuration_convnext.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. """ConvNeXT model configuration"""
  16. from collections import OrderedDict
  17. from typing import Mapping
  18. from packaging import version
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
  23. logger = logging.get_logger(__name__)
  24. class ConvNextConfig(BackboneConfigMixin, PretrainedConfig):
  25. r"""
  26. This is the configuration class to store the configuration of a [`ConvNextModel`]. It is used to instantiate an
  27. ConvNeXT model according to the specified arguments, defining the model architecture. Instantiating a configuration
  28. with the defaults will yield a similar configuration to that of the ConvNeXT
  29. [facebook/convnext-tiny-224](https://huggingface.co/facebook/convnext-tiny-224) architecture.
  30. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  31. documentation from [`PretrainedConfig`] for more information.
  32. Args:
  33. num_channels (`int`, *optional*, defaults to 3):
  34. The number of input channels.
  35. patch_size (`int`, *optional*, defaults to 4):
  36. Patch size to use in the patch embedding layer.
  37. num_stages (`int`, *optional*, defaults to 4):
  38. The number of stages in the model.
  39. hidden_sizes (`List[int]`, *optional*, defaults to [96, 192, 384, 768]):
  40. Dimensionality (hidden size) at each stage.
  41. depths (`List[int]`, *optional*, defaults to [3, 3, 9, 3]):
  42. Depth (number of blocks) for each stage.
  43. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  44. The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
  45. `"selu"` and `"gelu_new"` are supported.
  46. initializer_range (`float`, *optional*, defaults to 0.02):
  47. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  48. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  49. The epsilon used by the layer normalization layers.
  50. layer_scale_init_value (`float`, *optional*, defaults to 1e-6):
  51. The initial value for the layer scale.
  52. drop_path_rate (`float`, *optional*, defaults to 0.0):
  53. The drop rate for stochastic depth.
  54. out_features (`List[str]`, *optional*):
  55. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  56. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  57. corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
  58. same order as defined in the `stage_names` attribute.
  59. out_indices (`List[int]`, *optional*):
  60. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  61. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  62. If unset and `out_features` is unset, will default to the last stage. Must be in the
  63. same order as defined in the `stage_names` attribute.
  64. Example:
  65. ```python
  66. >>> from transformers import ConvNextConfig, ConvNextModel
  67. >>> # Initializing a ConvNext convnext-tiny-224 style configuration
  68. >>> configuration = ConvNextConfig()
  69. >>> # Initializing a model (with random weights) from the convnext-tiny-224 style configuration
  70. >>> model = ConvNextModel(configuration)
  71. >>> # Accessing the model configuration
  72. >>> configuration = model.config
  73. ```"""
  74. model_type = "convnext"
  75. def __init__(
  76. self,
  77. num_channels=3,
  78. patch_size=4,
  79. num_stages=4,
  80. hidden_sizes=None,
  81. depths=None,
  82. hidden_act="gelu",
  83. initializer_range=0.02,
  84. layer_norm_eps=1e-12,
  85. layer_scale_init_value=1e-6,
  86. drop_path_rate=0.0,
  87. image_size=224,
  88. out_features=None,
  89. out_indices=None,
  90. **kwargs,
  91. ):
  92. super().__init__(**kwargs)
  93. self.num_channels = num_channels
  94. self.patch_size = patch_size
  95. self.num_stages = num_stages
  96. self.hidden_sizes = [96, 192, 384, 768] if hidden_sizes is None else hidden_sizes
  97. self.depths = [3, 3, 9, 3] if depths is None else depths
  98. self.hidden_act = hidden_act
  99. self.initializer_range = initializer_range
  100. self.layer_norm_eps = layer_norm_eps
  101. self.layer_scale_init_value = layer_scale_init_value
  102. self.drop_path_rate = drop_path_rate
  103. self.image_size = image_size
  104. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(self.depths) + 1)]
  105. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  106. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  107. )
  108. class ConvNextOnnxConfig(OnnxConfig):
  109. torch_onnx_minimum_version = version.parse("1.11")
  110. @property
  111. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  112. return OrderedDict(
  113. [
  114. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  115. ]
  116. )
  117. @property
  118. def atol_for_validation(self) -> float:
  119. return 1e-5