configuration_mobilevit.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # coding=utf-8
  2. # Copyright 2022 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. """MobileViT 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. logger = logging.get_logger(__name__)
  23. class MobileViTConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`MobileViTModel`]. It is used to instantiate a
  26. MobileViT 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 MobileViT
  28. [apple/mobilevit-small](https://huggingface.co/apple/mobilevit-small) 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. hidden_sizes (`List[int]`, *optional*, defaults to `[144, 192, 240]`):
  39. Dimensionality (hidden size) of the Transformer encoders at each stage.
  40. neck_hidden_sizes (`List[int]`, *optional*, defaults to `[16, 32, 64, 96, 128, 160, 640]`):
  41. The number of channels for the feature maps of the backbone.
  42. num_attention_heads (`int`, *optional*, defaults to 4):
  43. Number of attention heads for each attention layer in the Transformer encoder.
  44. mlp_ratio (`float`, *optional*, defaults to 2.0):
  45. The ratio of the number of channels in the output of the MLP to the number of channels in the input.
  46. expand_ratio (`float`, *optional*, defaults to 4.0):
  47. Expansion factor for the MobileNetv2 layers.
  48. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  49. The non-linear activation function (function or string) in the Transformer encoder and convolution layers.
  50. conv_kernel_size (`int`, *optional*, defaults to 3):
  51. The size of the convolutional kernel in the MobileViT layer.
  52. output_stride (`int`, *optional*, defaults to 32):
  53. The ratio of the spatial resolution of the output to the resolution of the input image.
  54. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  55. The dropout probability for all fully connected layers in the Transformer encoder.
  56. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
  57. The dropout ratio for the attention probabilities.
  58. classifier_dropout_prob (`float`, *optional*, defaults to 0.1):
  59. The dropout ratio for attached classifiers.
  60. initializer_range (`float`, *optional*, defaults to 0.02):
  61. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  62. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  63. The epsilon used by the layer normalization layers.
  64. qkv_bias (`bool`, *optional*, defaults to `True`):
  65. Whether to add a bias to the queries, keys and values.
  66. aspp_out_channels (`int`, *optional*, defaults to 256):
  67. Number of output channels used in the ASPP layer for semantic segmentation.
  68. atrous_rates (`List[int]`, *optional*, defaults to `[6, 12, 18]`):
  69. Dilation (atrous) factors used in the ASPP layer for semantic segmentation.
  70. aspp_dropout_prob (`float`, *optional*, defaults to 0.1):
  71. The dropout ratio for the ASPP layer for semantic segmentation.
  72. semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
  73. The index that is ignored by the loss function of the semantic segmentation model.
  74. Example:
  75. ```python
  76. >>> from transformers import MobileViTConfig, MobileViTModel
  77. >>> # Initializing a mobilevit-small style configuration
  78. >>> configuration = MobileViTConfig()
  79. >>> # Initializing a model from the mobilevit-small style configuration
  80. >>> model = MobileViTModel(configuration)
  81. >>> # Accessing the model configuration
  82. >>> configuration = model.config
  83. ```"""
  84. model_type = "mobilevit"
  85. def __init__(
  86. self,
  87. num_channels=3,
  88. image_size=256,
  89. patch_size=2,
  90. hidden_sizes=[144, 192, 240],
  91. neck_hidden_sizes=[16, 32, 64, 96, 128, 160, 640],
  92. num_attention_heads=4,
  93. mlp_ratio=2.0,
  94. expand_ratio=4.0,
  95. hidden_act="silu",
  96. conv_kernel_size=3,
  97. output_stride=32,
  98. hidden_dropout_prob=0.1,
  99. attention_probs_dropout_prob=0.0,
  100. classifier_dropout_prob=0.1,
  101. initializer_range=0.02,
  102. layer_norm_eps=1e-5,
  103. qkv_bias=True,
  104. aspp_out_channels=256,
  105. atrous_rates=[6, 12, 18],
  106. aspp_dropout_prob=0.1,
  107. semantic_loss_ignore_index=255,
  108. **kwargs,
  109. ):
  110. super().__init__(**kwargs)
  111. self.num_channels = num_channels
  112. self.image_size = image_size
  113. self.patch_size = patch_size
  114. self.hidden_sizes = hidden_sizes
  115. self.neck_hidden_sizes = neck_hidden_sizes
  116. self.num_attention_heads = num_attention_heads
  117. self.mlp_ratio = mlp_ratio
  118. self.expand_ratio = expand_ratio
  119. self.hidden_act = hidden_act
  120. self.conv_kernel_size = conv_kernel_size
  121. self.output_stride = output_stride
  122. self.hidden_dropout_prob = hidden_dropout_prob
  123. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  124. self.classifier_dropout_prob = classifier_dropout_prob
  125. self.initializer_range = initializer_range
  126. self.layer_norm_eps = layer_norm_eps
  127. self.qkv_bias = qkv_bias
  128. # decode head attributes for semantic segmentation
  129. self.aspp_out_channels = aspp_out_channels
  130. self.atrous_rates = atrous_rates
  131. self.aspp_dropout_prob = aspp_dropout_prob
  132. self.semantic_loss_ignore_index = semantic_loss_ignore_index
  133. class MobileViTOnnxConfig(OnnxConfig):
  134. torch_onnx_minimum_version = version.parse("1.11")
  135. @property
  136. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  137. return OrderedDict([("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"})])
  138. @property
  139. def outputs(self) -> Mapping[str, Mapping[int, str]]:
  140. if self.task == "image-classification":
  141. return OrderedDict([("logits", {0: "batch"})])
  142. else:
  143. return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})])
  144. @property
  145. def atol_for_validation(self) -> float:
  146. return 1e-4