configuration_efficientnet.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. # coding=utf-8
  2. # Copyright 2023 Google 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. """EfficientNet model configuration"""
  16. from collections import OrderedDict
  17. from typing import List, Mapping
  18. from packaging import version
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. logger = logging.get_logger(__name__)
  23. class EfficientNetConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`EfficientNetModel`]. It is used to instantiate an
  26. EfficientNet model according to the specified arguments, defining the model architecture. Instantiating a
  27. configuration with the defaults will yield a similar configuration to that of the EfficientNet
  28. [google/efficientnet-b7](https://huggingface.co/google/efficientnet-b7) architecture.
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information.
  31. Args:
  32. num_channels (`int`, *optional*, defaults to 3):
  33. The number of input channels.
  34. image_size (`int`, *optional*, defaults to 600):
  35. The input image size.
  36. width_coefficient (`float`, *optional*, defaults to 2.0):
  37. Scaling coefficient for network width at each stage.
  38. depth_coefficient (`float`, *optional*, defaults to 3.1):
  39. Scaling coefficient for network depth at each stage.
  40. depth_divisor `int`, *optional*, defaults to 8):
  41. A unit of network width.
  42. kernel_sizes (`List[int]`, *optional*, defaults to `[3, 3, 5, 3, 5, 5, 3]`):
  43. List of kernel sizes to be used in each block.
  44. in_channels (`List[int]`, *optional*, defaults to `[32, 16, 24, 40, 80, 112, 192]`):
  45. List of input channel sizes to be used in each block for convolutional layers.
  46. out_channels (`List[int]`, *optional*, defaults to `[16, 24, 40, 80, 112, 192, 320]`):
  47. List of output channel sizes to be used in each block for convolutional layers.
  48. depthwise_padding (`List[int]`, *optional*, defaults to `[]`):
  49. List of block indices with square padding.
  50. strides (`List[int]`, *optional*, defaults to `[1, 2, 2, 2, 1, 2, 1]`):
  51. List of stride sizes to be used in each block for convolutional layers.
  52. num_block_repeats (`List[int]`, *optional*, defaults to `[1, 2, 2, 3, 3, 4, 1]`):
  53. List of the number of times each block is to repeated.
  54. expand_ratios (`List[int]`, *optional*, defaults to `[1, 6, 6, 6, 6, 6, 6]`):
  55. List of scaling coefficient of each block.
  56. squeeze_expansion_ratio (`float`, *optional*, defaults to 0.25):
  57. Squeeze expansion ratio.
  58. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  59. The non-linear activation function (function or string) in each block. If string, `"gelu"`, `"relu"`,
  60. `"selu", `"gelu_new"`, `"silu"` and `"mish"` are supported.
  61. hiddem_dim (`int`, *optional*, defaults to 1280):
  62. The hidden dimension of the layer before the classification head.
  63. pooling_type (`str` or `function`, *optional*, defaults to `"mean"`):
  64. Type of final pooling to be applied before the dense classification head. Available options are [`"mean"`,
  65. `"max"`]
  66. initializer_range (`float`, *optional*, defaults to 0.02):
  67. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  68. batch_norm_eps (`float`, *optional*, defaults to 1e-3):
  69. The epsilon used by the batch normalization layers.
  70. batch_norm_momentum (`float`, *optional*, defaults to 0.99):
  71. The momentum used by the batch normalization layers.
  72. dropout_rate (`float`, *optional*, defaults to 0.5):
  73. The dropout rate to be applied before final classifier layer.
  74. drop_connect_rate (`float`, *optional*, defaults to 0.2):
  75. The drop rate for skip connections.
  76. Example:
  77. ```python
  78. >>> from transformers import EfficientNetConfig, EfficientNetModel
  79. >>> # Initializing a EfficientNet efficientnet-b7 style configuration
  80. >>> configuration = EfficientNetConfig()
  81. >>> # Initializing a model (with random weights) from the efficientnet-b7 style configuration
  82. >>> model = EfficientNetModel(configuration)
  83. >>> # Accessing the model configuration
  84. >>> configuration = model.config
  85. ```"""
  86. model_type = "efficientnet"
  87. def __init__(
  88. self,
  89. num_channels: int = 3,
  90. image_size: int = 600,
  91. width_coefficient: float = 2.0,
  92. depth_coefficient: float = 3.1,
  93. depth_divisor: int = 8,
  94. kernel_sizes: List[int] = [3, 3, 5, 3, 5, 5, 3],
  95. in_channels: List[int] = [32, 16, 24, 40, 80, 112, 192],
  96. out_channels: List[int] = [16, 24, 40, 80, 112, 192, 320],
  97. depthwise_padding: List[int] = [],
  98. strides: List[int] = [1, 2, 2, 2, 1, 2, 1],
  99. num_block_repeats: List[int] = [1, 2, 2, 3, 3, 4, 1],
  100. expand_ratios: List[int] = [1, 6, 6, 6, 6, 6, 6],
  101. squeeze_expansion_ratio: float = 0.25,
  102. hidden_act: str = "swish",
  103. hidden_dim: int = 2560,
  104. pooling_type: str = "mean",
  105. initializer_range: float = 0.02,
  106. batch_norm_eps: float = 0.001,
  107. batch_norm_momentum: float = 0.99,
  108. dropout_rate: float = 0.5,
  109. drop_connect_rate: float = 0.2,
  110. **kwargs,
  111. ):
  112. super().__init__(**kwargs)
  113. self.num_channels = num_channels
  114. self.image_size = image_size
  115. self.width_coefficient = width_coefficient
  116. self.depth_coefficient = depth_coefficient
  117. self.depth_divisor = depth_divisor
  118. self.kernel_sizes = kernel_sizes
  119. self.in_channels = in_channels
  120. self.out_channels = out_channels
  121. self.depthwise_padding = depthwise_padding
  122. self.strides = strides
  123. self.num_block_repeats = num_block_repeats
  124. self.expand_ratios = expand_ratios
  125. self.squeeze_expansion_ratio = squeeze_expansion_ratio
  126. self.hidden_act = hidden_act
  127. self.hidden_dim = hidden_dim
  128. self.pooling_type = pooling_type
  129. self.initializer_range = initializer_range
  130. self.batch_norm_eps = batch_norm_eps
  131. self.batch_norm_momentum = batch_norm_momentum
  132. self.dropout_rate = dropout_rate
  133. self.drop_connect_rate = drop_connect_rate
  134. self.num_hidden_layers = sum(num_block_repeats) * 4
  135. class EfficientNetOnnxConfig(OnnxConfig):
  136. torch_onnx_minimum_version = version.parse("1.11")
  137. @property
  138. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  139. return OrderedDict(
  140. [
  141. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  142. ]
  143. )
  144. @property
  145. def atol_for_validation(self) -> float:
  146. return 1e-5