configuration_resnet.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # coding=utf-8
  2. # Copyright 2022 Microsoft Research, 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. """ResNet model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc 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 ResNetConfig(BackboneConfigMixin, PretrainedConfig):
  25. r"""
  26. This is the configuration class to store the configuration of a [`ResNetModel`]. It is used to instantiate an
  27. ResNet 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 ResNet
  29. [microsoft/resnet-50](https://huggingface.co/microsoft/resnet-50) 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. embedding_size (`int`, *optional*, defaults to 64):
  36. Dimensionality (hidden size) for the embedding layer.
  37. hidden_sizes (`list[int]`, *optional*, defaults to `[256, 512, 1024, 2048]`):
  38. Dimensionality (hidden size) at each stage.
  39. depths (`list[int]`, *optional*, defaults to `[3, 4, 6, 3]`):
  40. Depth (number of layers) for each stage.
  41. layer_type (`str`, *optional*, defaults to `"bottleneck"`):
  42. The layer to use, it can be either `"basic"` (used for smaller models, like resnet-18 or resnet-34) or
  43. `"bottleneck"` (used for larger models like resnet-50 and above).
  44. hidden_act (`str`, *optional*, defaults to `"relu"`):
  45. The non-linear activation function in each block. If string, `"gelu"`, `"relu"`, `"selu"` and `"gelu_new"`
  46. are supported.
  47. downsample_in_first_stage (`bool`, *optional*, defaults to `False`):
  48. If `True`, the first stage will downsample the inputs using a `stride` of 2.
  49. downsample_in_bottleneck (`bool`, *optional*, defaults to `False`):
  50. If `True`, the first conv 1x1 in ResNetBottleNeckLayer will downsample the inputs using a `stride` of 2.
  51. out_features (`list[str]`, *optional*):
  52. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  53. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  54. corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
  55. same order as defined in the `stage_names` attribute.
  56. out_indices (`list[int]`, *optional*):
  57. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  58. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  59. If unset and `out_features` is unset, will default to the last stage. Must be in the
  60. same order as defined in the `stage_names` attribute.
  61. Example:
  62. ```python
  63. >>> from transformers import ResNetConfig, ResNetModel
  64. >>> # Initializing a ResNet resnet-50 style configuration
  65. >>> configuration = ResNetConfig()
  66. >>> # Initializing a model (with random weights) from the resnet-50 style configuration
  67. >>> model = ResNetModel(configuration)
  68. >>> # Accessing the model configuration
  69. >>> configuration = model.config
  70. ```
  71. """
  72. model_type = "resnet"
  73. layer_types = ["basic", "bottleneck"]
  74. def __init__(
  75. self,
  76. num_channels=3,
  77. embedding_size=64,
  78. hidden_sizes=[256, 512, 1024, 2048],
  79. depths=[3, 4, 6, 3],
  80. layer_type="bottleneck",
  81. hidden_act="relu",
  82. downsample_in_first_stage=False,
  83. downsample_in_bottleneck=False,
  84. out_features=None,
  85. out_indices=None,
  86. **kwargs,
  87. ):
  88. super().__init__(**kwargs)
  89. if layer_type not in self.layer_types:
  90. raise ValueError(f"layer_type={layer_type} is not one of {','.join(self.layer_types)}")
  91. self.num_channels = num_channels
  92. self.embedding_size = embedding_size
  93. self.hidden_sizes = hidden_sizes
  94. self.depths = depths
  95. self.layer_type = layer_type
  96. self.hidden_act = hidden_act
  97. self.downsample_in_first_stage = downsample_in_first_stage
  98. self.downsample_in_bottleneck = downsample_in_bottleneck
  99. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
  100. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  101. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  102. )
  103. class ResNetOnnxConfig(OnnxConfig):
  104. torch_onnx_minimum_version = version.parse("1.11")
  105. @property
  106. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  107. return OrderedDict(
  108. [
  109. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  110. ]
  111. )
  112. @property
  113. def atol_for_validation(self) -> float:
  114. return 1e-3
  115. __all__ = ["ResNetConfig", "ResNetOnnxConfig"]