configuration_data2vec_vision.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # coding=utf-8
  2. # Copyright Meta Platforms 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. """Data2VecVision 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 Data2VecVisionConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`Data2VecVisionModel`]. It is used to instantiate
  26. an Data2VecVision 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 Data2VecVision
  28. [facebook/data2vec-vision-base](https://huggingface.co/facebook/data2vec-vision-base) architecture.
  29. Args:
  30. hidden_size (`int`, *optional*, defaults to 768):
  31. Dimensionality of the encoder layers and the pooler layer.
  32. num_hidden_layers (`int`, *optional*, defaults to 12):
  33. Number of hidden layers in the Transformer encoder.
  34. num_attention_heads (`int`, *optional*, defaults to 12):
  35. Number of attention heads for each attention layer in the Transformer encoder.
  36. intermediate_size (`int`, *optional*, defaults to 3072):
  37. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  38. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  39. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  40. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  41. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  42. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  43. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
  44. The dropout ratio for the attention probabilities.
  45. initializer_range (`float`, *optional*, defaults to 0.02):
  46. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  47. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  48. The epsilon used by the layer normalization layers.
  49. image_size (`int`, *optional*, defaults to 224):
  50. The size (resolution) of each image.
  51. patch_size (`int`, *optional*, defaults to 16):
  52. The size (resolution) of each patch.
  53. num_channels (`int`, *optional*, defaults to 3):
  54. The number of input channels.
  55. use_mask_token (`bool`, *optional*, defaults to `False`):
  56. Whether to use a mask token for masked image modeling.
  57. use_absolute_position_embeddings (`bool`, *optional*, defaults to `False`):
  58. Whether to use BERT-style absolute position embeddings.
  59. use_relative_position_bias (`bool`, *optional*, defaults to `False`):
  60. Whether to use T5-style relative position embeddings in the self-attention layers.
  61. use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
  62. Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
  63. layer_scale_init_value (`float`, *optional*, defaults to 0.1):
  64. Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
  65. drop_path_rate (`float`, *optional*, defaults to 0.1):
  66. Stochastic depth rate per sample (when applied in the main path of residual layers).
  67. use_mean_pooling (`bool`, *optional*, defaults to `True`):
  68. Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
  69. CLS token, before applying the classification head.
  70. out_indices (`List[int]`, *optional*, defaults to `[3, 5, 7, 11]`):
  71. Indices of the feature maps to use for semantic segmentation.
  72. pool_scales (`Tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
  73. Pooling scales used in Pooling Pyramid Module applied on the last feature map.
  74. use_auxiliary_head (`bool`, *optional*, defaults to `True`):
  75. Whether to use an auxiliary head during training.
  76. auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
  77. Weight of the cross-entropy loss of the auxiliary head.
  78. auxiliary_channels (`int`, *optional*, defaults to 256):
  79. Number of channels to use in the auxiliary head.
  80. auxiliary_num_convs (`int`, *optional*, defaults to 1):
  81. Number of convolutional layers to use in the auxiliary head.
  82. auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
  83. Whether to concatenate the output of the auxiliary head with the input before the classification layer.
  84. semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
  85. The index that is ignored by the loss function of the semantic segmentation model.
  86. Example:
  87. ```python
  88. >>> from transformers import Data2VecVisionConfig, Data2VecVisionModel
  89. >>> # Initializing a Data2VecVision data2vec_vision-base-patch16-224-in22k style configuration
  90. >>> configuration = Data2VecVisionConfig()
  91. >>> # Initializing a model (with random weights) from the data2vec_vision-base-patch16-224-in22k style configuration
  92. >>> model = Data2VecVisionModel(configuration)
  93. >>> # Accessing the model configuration
  94. >>> configuration = model.config
  95. ```"""
  96. model_type = "data2vec-vision"
  97. def __init__(
  98. self,
  99. hidden_size=768,
  100. num_hidden_layers=12,
  101. num_attention_heads=12,
  102. intermediate_size=3072,
  103. hidden_act="gelu",
  104. hidden_dropout_prob=0.0,
  105. attention_probs_dropout_prob=0.0,
  106. initializer_range=0.02,
  107. layer_norm_eps=1e-12,
  108. image_size=224,
  109. patch_size=16,
  110. num_channels=3,
  111. use_mask_token=False,
  112. use_absolute_position_embeddings=False,
  113. use_relative_position_bias=False,
  114. use_shared_relative_position_bias=False,
  115. layer_scale_init_value=0.1,
  116. drop_path_rate=0.1,
  117. use_mean_pooling=True,
  118. out_indices=[3, 5, 7, 11],
  119. pool_scales=[1, 2, 3, 6],
  120. use_auxiliary_head=True,
  121. auxiliary_loss_weight=0.4,
  122. auxiliary_channels=256,
  123. auxiliary_num_convs=1,
  124. auxiliary_concat_input=False,
  125. semantic_loss_ignore_index=255,
  126. **kwargs,
  127. ):
  128. super().__init__(**kwargs)
  129. self.hidden_size = hidden_size
  130. self.num_hidden_layers = num_hidden_layers
  131. self.num_attention_heads = num_attention_heads
  132. self.intermediate_size = intermediate_size
  133. self.hidden_act = hidden_act
  134. self.hidden_dropout_prob = hidden_dropout_prob
  135. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  136. self.initializer_range = initializer_range
  137. self.layer_norm_eps = layer_norm_eps
  138. self.image_size = image_size
  139. self.patch_size = patch_size
  140. self.num_channels = num_channels
  141. self.use_mask_token = use_mask_token
  142. self.use_absolute_position_embeddings = use_absolute_position_embeddings
  143. self.use_relative_position_bias = use_relative_position_bias
  144. self.use_shared_relative_position_bias = use_shared_relative_position_bias
  145. self.layer_scale_init_value = layer_scale_init_value
  146. self.drop_path_rate = drop_path_rate
  147. self.use_mean_pooling = use_mean_pooling
  148. # decode head attributes (semantic segmentation)
  149. self.out_indices = out_indices
  150. self.pool_scales = pool_scales
  151. # auxiliary head attributes (semantic segmentation)
  152. self.use_auxiliary_head = use_auxiliary_head
  153. self.auxiliary_loss_weight = auxiliary_loss_weight
  154. self.auxiliary_channels = auxiliary_channels
  155. self.auxiliary_num_convs = auxiliary_num_convs
  156. self.auxiliary_concat_input = auxiliary_concat_input
  157. self.semantic_loss_ignore_index = semantic_loss_ignore_index
  158. # Copied from transformers.models.vit.configuration_vit.ViTOnnxConfig
  159. class Data2VecVisionOnnxConfig(OnnxConfig):
  160. torch_onnx_minimum_version = version.parse("1.11")
  161. @property
  162. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  163. return OrderedDict(
  164. [
  165. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  166. ]
  167. )
  168. @property
  169. def atol_for_validation(self) -> float:
  170. return 1e-4