configuration_mobilevitv2.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # coding=utf-8
  2. # Copyright 2023 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. """MobileViTV2 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. logger = logging.get_logger(__name__)
  23. class MobileViTV2Config(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`MobileViTV2Model`]. It is used to instantiate a
  26. MobileViTV2 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 MobileViTV2
  28. [apple/mobilevitv2-1.0](https://huggingface.co/apple/mobilevitv2-1.0) 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 256):
  35. The size (resolution) of each image.
  36. patch_size (`int`, *optional*, defaults to 2):
  37. The size (resolution) of each patch.
  38. expand_ratio (`float`, *optional*, defaults to 2.0):
  39. Expansion factor for the MobileNetv2 layers.
  40. hidden_act (`str` or `function`, *optional*, defaults to `"swish"`):
  41. The non-linear activation function (function or string) in the Transformer encoder and convolution layers.
  42. conv_kernel_size (`int`, *optional*, defaults to 3):
  43. The size of the convolutional kernel in the MobileViTV2 layer.
  44. output_stride (`int`, *optional*, defaults to 32):
  45. The ratio of the spatial resolution of the output to the resolution of the input image.
  46. classifier_dropout_prob (`float`, *optional*, defaults to 0.1):
  47. The dropout ratio for attached classifiers.
  48. initializer_range (`float`, *optional*, defaults to 0.02):
  49. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  50. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  51. The epsilon used by the layer normalization layers.
  52. aspp_out_channels (`int`, *optional*, defaults to 512):
  53. Number of output channels used in the ASPP layer for semantic segmentation.
  54. atrous_rates (`list[int]`, *optional*, defaults to `[6, 12, 18]`):
  55. Dilation (atrous) factors used in the ASPP layer for semantic segmentation.
  56. aspp_dropout_prob (`float`, *optional*, defaults to 0.1):
  57. The dropout ratio for the ASPP layer for semantic segmentation.
  58. semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
  59. The index that is ignored by the loss function of the semantic segmentation model.
  60. n_attn_blocks (`list[int]`, *optional*, defaults to `[2, 4, 3]`):
  61. The number of attention blocks in each MobileViTV2Layer
  62. base_attn_unit_dims (`list[int]`, *optional*, defaults to `[128, 192, 256]`):
  63. The base multiplier for dimensions of attention blocks in each MobileViTV2Layer
  64. width_multiplier (`float`, *optional*, defaults to 1.0):
  65. The width multiplier for MobileViTV2.
  66. ffn_multiplier (`int`, *optional*, defaults to 2):
  67. The FFN multiplier for MobileViTV2.
  68. attn_dropout (`float`, *optional*, defaults to 0.0):
  69. The dropout in the attention layer.
  70. ffn_dropout (`float`, *optional*, defaults to 0.0):
  71. The dropout between FFN layers.
  72. Example:
  73. ```python
  74. >>> from transformers import MobileViTV2Config, MobileViTV2Model
  75. >>> # Initializing a mobilevitv2-small style configuration
  76. >>> configuration = MobileViTV2Config()
  77. >>> # Initializing a model from the mobilevitv2-small style configuration
  78. >>> model = MobileViTV2Model(configuration)
  79. >>> # Accessing the model configuration
  80. >>> configuration = model.config
  81. ```"""
  82. model_type = "mobilevitv2"
  83. def __init__(
  84. self,
  85. num_channels=3,
  86. image_size=256,
  87. patch_size=2,
  88. expand_ratio=2.0,
  89. hidden_act="swish",
  90. conv_kernel_size=3,
  91. output_stride=32,
  92. classifier_dropout_prob=0.1,
  93. initializer_range=0.02,
  94. layer_norm_eps=1e-5,
  95. aspp_out_channels=512,
  96. atrous_rates=[6, 12, 18],
  97. aspp_dropout_prob=0.1,
  98. semantic_loss_ignore_index=255,
  99. n_attn_blocks=[2, 4, 3],
  100. base_attn_unit_dims=[128, 192, 256],
  101. width_multiplier=1.0,
  102. ffn_multiplier=2,
  103. attn_dropout=0.0,
  104. ffn_dropout=0.0,
  105. **kwargs,
  106. ):
  107. super().__init__(**kwargs)
  108. self.num_channels = num_channels
  109. self.image_size = image_size
  110. self.patch_size = patch_size
  111. self.expand_ratio = expand_ratio
  112. self.hidden_act = hidden_act
  113. self.conv_kernel_size = conv_kernel_size
  114. self.output_stride = output_stride
  115. self.initializer_range = initializer_range
  116. self.layer_norm_eps = layer_norm_eps
  117. self.n_attn_blocks = n_attn_blocks
  118. self.base_attn_unit_dims = base_attn_unit_dims
  119. self.width_multiplier = width_multiplier
  120. self.ffn_multiplier = ffn_multiplier
  121. self.ffn_dropout = ffn_dropout
  122. self.attn_dropout = attn_dropout
  123. self.classifier_dropout_prob = classifier_dropout_prob
  124. # decode head attributes for semantic segmentation
  125. self.aspp_out_channels = aspp_out_channels
  126. self.atrous_rates = atrous_rates
  127. self.aspp_dropout_prob = aspp_dropout_prob
  128. self.semantic_loss_ignore_index = semantic_loss_ignore_index
  129. class MobileViTV2OnnxConfig(OnnxConfig):
  130. torch_onnx_minimum_version = version.parse("1.11")
  131. @property
  132. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  133. return OrderedDict([("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"})])
  134. @property
  135. def outputs(self) -> Mapping[str, Mapping[int, str]]:
  136. if self.task == "image-classification":
  137. return OrderedDict([("logits", {0: "batch"})])
  138. else:
  139. return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})])
  140. @property
  141. def atol_for_validation(self) -> float:
  142. return 1e-4
  143. __all__ = ["MobileViTV2Config", "MobileViTV2OnnxConfig"]