configuration_beit.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # coding=utf-8
  2. # Copyright Microsoft Research 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. """BEiT model configuration"""
  16. import warnings
  17. from collections import OrderedDict
  18. from collections.abc import Mapping
  19. from packaging import version
  20. from ...configuration_utils import PretrainedConfig
  21. from ...onnx import OnnxConfig
  22. from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
  23. class BeitConfig(BackboneConfigMixin, PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`BeitModel`]. It is used to instantiate an BEiT
  26. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  27. defaults will yield a similar configuration to that of the BEiT
  28. [microsoft/beit-base-patch16-224-pt22k](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k) architecture.
  29. Args:
  30. vocab_size (`int`, *optional*, defaults to 8192):
  31. Vocabulary size of the BEiT model. Defines the number of different image tokens that can be used during
  32. pre-training.
  33. hidden_size (`int`, *optional*, defaults to 768):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. num_hidden_layers (`int`, *optional*, defaults to 12):
  36. Number of hidden layers in the Transformer encoder.
  37. num_attention_heads (`int`, *optional*, defaults to 12):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. intermediate_size (`int`, *optional*, defaults to 3072):
  40. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  41. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  42. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  43. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  44. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  45. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  46. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
  47. The dropout ratio for the attention probabilities.
  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-12):
  51. The epsilon used by the layer normalization layers.
  52. image_size (`int`, *optional*, defaults to 224):
  53. The size (resolution) of each image.
  54. patch_size (`int`, *optional*, defaults to 16):
  55. The size (resolution) of each patch.
  56. num_channels (`int`, *optional*, defaults to 3):
  57. The number of input channels.
  58. use_mask_token (`bool`, *optional*, defaults to `False`):
  59. Whether to use a mask token for masked image modeling.
  60. use_absolute_position_embeddings (`bool`, *optional*, defaults to `False`):
  61. Whether to use BERT-style absolute position embeddings.
  62. use_relative_position_bias (`bool`, *optional*, defaults to `False`):
  63. Whether to use T5-style relative position embeddings in the self-attention layers.
  64. use_shared_relative_position_bias (`bool`, *optional*, defaults to `False`):
  65. Whether to use the same relative position embeddings across all self-attention layers of the Transformer.
  66. layer_scale_init_value (`float`, *optional*, defaults to 0.1):
  67. Scale to use in the self-attention layers. 0.1 for base, 1e-5 for large. Set 0 to disable layer scale.
  68. drop_path_rate (`float`, *optional*, defaults to 0.1):
  69. Stochastic depth rate per sample (when applied in the main path of residual layers).
  70. use_mean_pooling (`bool`, *optional*, defaults to `True`):
  71. Whether to mean pool the final hidden states of the patches instead of using the final hidden state of the
  72. CLS token, before applying the classification head.
  73. pool_scales (`tuple[int]`, *optional*, defaults to `[1, 2, 3, 6]`):
  74. Pooling scales used in Pooling Pyramid Module applied on the last feature map.
  75. use_auxiliary_head (`bool`, *optional*, defaults to `True`):
  76. Whether to use an auxiliary head during training.
  77. auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
  78. Weight of the cross-entropy loss of the auxiliary head.
  79. auxiliary_channels (`int`, *optional*, defaults to 256):
  80. Number of channels to use in the auxiliary head.
  81. auxiliary_num_convs (`int`, *optional*, defaults to 1):
  82. Number of convolutional layers to use in the auxiliary head.
  83. auxiliary_concat_input (`bool`, *optional*, defaults to `False`):
  84. Whether to concatenate the output of the auxiliary head with the input before the classification layer.
  85. semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
  86. The index that is ignored by the loss function of the semantic segmentation model.
  87. out_features (`list[str]`, *optional*):
  88. If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
  89. (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
  90. corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
  91. same order as defined in the `stage_names` attribute.
  92. out_indices (`list[int]`, *optional*):
  93. If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
  94. many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
  95. If unset and `out_features` is unset, will default to the last stage. Must be in the
  96. same order as defined in the `stage_names` attribute.
  97. add_fpn (`bool`, *optional*, defaults to `False`):
  98. Whether to add a FPN as part of the backbone. Only relevant for [`BeitBackbone`].
  99. reshape_hidden_states (`bool`, *optional*, defaults to `True`):
  100. Whether to reshape the feature maps to 4D tensors of shape `(batch_size, hidden_size, height, width)` in
  101. case the model is used as backbone. If `False`, the feature maps will be 3D tensors of shape `(batch_size,
  102. seq_len, hidden_size)`. Only relevant for [`BeitBackbone`].
  103. Example:
  104. ```python
  105. >>> from transformers import BeitConfig, BeitModel
  106. >>> # Initializing a BEiT beit-base-patch16-224-pt22k style configuration
  107. >>> configuration = BeitConfig()
  108. >>> # Initializing a model (with random weights) from the beit-base-patch16-224-pt22k style configuration
  109. >>> model = BeitModel(configuration)
  110. >>> # Accessing the model configuration
  111. >>> configuration = model.config
  112. ```"""
  113. model_type = "beit"
  114. def __init__(
  115. self,
  116. vocab_size=8192,
  117. hidden_size=768,
  118. num_hidden_layers=12,
  119. num_attention_heads=12,
  120. intermediate_size=3072,
  121. hidden_act="gelu",
  122. hidden_dropout_prob=0.0,
  123. attention_probs_dropout_prob=0.0,
  124. initializer_range=0.02,
  125. layer_norm_eps=1e-12,
  126. image_size=224,
  127. patch_size=16,
  128. num_channels=3,
  129. use_mask_token=False,
  130. use_absolute_position_embeddings=False,
  131. use_relative_position_bias=False,
  132. use_shared_relative_position_bias=False,
  133. layer_scale_init_value=0.1,
  134. drop_path_rate=0.1,
  135. use_mean_pooling=True,
  136. pool_scales=[1, 2, 3, 6],
  137. use_auxiliary_head=True,
  138. auxiliary_loss_weight=0.4,
  139. auxiliary_channels=256,
  140. auxiliary_num_convs=1,
  141. auxiliary_concat_input=False,
  142. semantic_loss_ignore_index=255,
  143. out_features=None,
  144. out_indices=None,
  145. add_fpn=False,
  146. reshape_hidden_states=True,
  147. **kwargs,
  148. ):
  149. super().__init__(**kwargs)
  150. self.vocab_size = vocab_size
  151. self.hidden_size = hidden_size
  152. self.num_hidden_layers = num_hidden_layers
  153. self.num_attention_heads = num_attention_heads
  154. self.intermediate_size = intermediate_size
  155. self.hidden_act = hidden_act
  156. self.hidden_dropout_prob = hidden_dropout_prob
  157. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  158. self.initializer_range = initializer_range
  159. self.layer_norm_eps = layer_norm_eps
  160. self.image_size = image_size
  161. self.patch_size = patch_size
  162. self.num_channels = num_channels
  163. self.use_mask_token = use_mask_token
  164. self.use_absolute_position_embeddings = use_absolute_position_embeddings
  165. self.use_relative_position_bias = use_relative_position_bias
  166. self.use_shared_relative_position_bias = use_shared_relative_position_bias
  167. self.layer_scale_init_value = layer_scale_init_value
  168. self.drop_path_rate = drop_path_rate
  169. self.use_mean_pooling = use_mean_pooling
  170. # decode head attributes (semantic segmentation)
  171. self.pool_scales = pool_scales
  172. # auxiliary head attributes (semantic segmentation)
  173. self.use_auxiliary_head = use_auxiliary_head
  174. self.auxiliary_loss_weight = auxiliary_loss_weight
  175. self.auxiliary_channels = auxiliary_channels
  176. self.auxiliary_num_convs = auxiliary_num_convs
  177. self.auxiliary_concat_input = auxiliary_concat_input
  178. self.semantic_loss_ignore_index = semantic_loss_ignore_index
  179. # handle backwards compatibility
  180. if "segmentation_indices" in kwargs:
  181. warnings.warn(
  182. "The `segmentation_indices` argument is deprecated and will be removed in a future version, use `out_indices` instead.",
  183. FutureWarning,
  184. )
  185. out_indices = kwargs.pop("segmentation_indices")
  186. # backbone attributes
  187. self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, self.num_hidden_layers + 1)]
  188. self._out_features, self._out_indices = get_aligned_output_features_output_indices(
  189. out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
  190. )
  191. self.add_fpn = add_fpn
  192. self.reshape_hidden_states = reshape_hidden_states
  193. # Copied from transformers.models.vit.configuration_vit.ViTOnnxConfig
  194. class BeitOnnxConfig(OnnxConfig):
  195. torch_onnx_minimum_version = version.parse("1.11")
  196. @property
  197. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  198. return OrderedDict(
  199. [
  200. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  201. ]
  202. )
  203. @property
  204. def atol_for_validation(self) -> float:
  205. return 1e-4
  206. __all__ = ["BeitConfig", "BeitOnnxConfig"]