configuration_vit.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. # coding=utf-8
  2. # Copyright 2021 Google AI 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. """ViT 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 ViTConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`ViTModel`]. It is used to instantiate an ViT
  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 ViT
  28. [google/vit-base-patch16-224](https://huggingface.co/google/vit-base-patch16-224) 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. hidden_size (`int`, *optional*, defaults to 768):
  33. Dimensionality of the encoder layers and the pooler layer.
  34. num_hidden_layers (`int`, *optional*, defaults to 12):
  35. Number of hidden layers in the Transformer encoder.
  36. num_attention_heads (`int`, *optional*, defaults to 12):
  37. Number of attention heads for each attention layer in the Transformer encoder.
  38. intermediate_size (`int`, *optional*, defaults to 3072):
  39. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  40. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  41. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  42. `"relu"`, `"selu"` and `"gelu_new"` are supported.
  43. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  44. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  45. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
  46. The dropout ratio for the attention probabilities.
  47. initializer_range (`float`, *optional*, defaults to 0.02):
  48. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  49. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  50. The epsilon used by the layer normalization layers.
  51. image_size (`int`, *optional*, defaults to 224):
  52. The size (resolution) of each image.
  53. patch_size (`int`, *optional*, defaults to 16):
  54. The size (resolution) of each patch.
  55. num_channels (`int`, *optional*, defaults to 3):
  56. The number of input channels.
  57. qkv_bias (`bool`, *optional*, defaults to `True`):
  58. Whether to add a bias to the queries, keys and values.
  59. encoder_stride (`int`, *optional*, defaults to 16):
  60. Factor to increase the spatial resolution by in the decoder head for masked image modeling.
  61. pooler_output_size (`int`, *optional*):
  62. Dimensionality of the pooler layer. If None, defaults to `hidden_size`.
  63. pooler_act (`str`, *optional*, defaults to `"tanh"`):
  64. The activation function to be used by the pooler. Keys of ACT2FN are supported for Flax and
  65. Pytorch, and elements of https://www.tensorflow.org/api_docs/python/tf/keras/activations are
  66. supported for Tensorflow.
  67. Example:
  68. ```python
  69. >>> from transformers import ViTConfig, ViTModel
  70. >>> # Initializing a ViT vit-base-patch16-224 style configuration
  71. >>> configuration = ViTConfig()
  72. >>> # Initializing a model (with random weights) from the vit-base-patch16-224 style configuration
  73. >>> model = ViTModel(configuration)
  74. >>> # Accessing the model configuration
  75. >>> configuration = model.config
  76. ```"""
  77. model_type = "vit"
  78. def __init__(
  79. self,
  80. hidden_size=768,
  81. num_hidden_layers=12,
  82. num_attention_heads=12,
  83. intermediate_size=3072,
  84. hidden_act="gelu",
  85. hidden_dropout_prob=0.0,
  86. attention_probs_dropout_prob=0.0,
  87. initializer_range=0.02,
  88. layer_norm_eps=1e-12,
  89. image_size=224,
  90. patch_size=16,
  91. num_channels=3,
  92. qkv_bias=True,
  93. encoder_stride=16,
  94. pooler_output_size=None,
  95. pooler_act="tanh",
  96. **kwargs,
  97. ):
  98. super().__init__(**kwargs)
  99. self.hidden_size = hidden_size
  100. self.num_hidden_layers = num_hidden_layers
  101. self.num_attention_heads = num_attention_heads
  102. self.intermediate_size = intermediate_size
  103. self.hidden_act = hidden_act
  104. self.hidden_dropout_prob = hidden_dropout_prob
  105. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  106. self.initializer_range = initializer_range
  107. self.layer_norm_eps = layer_norm_eps
  108. self.image_size = image_size
  109. self.patch_size = patch_size
  110. self.num_channels = num_channels
  111. self.qkv_bias = qkv_bias
  112. self.encoder_stride = encoder_stride
  113. self.pooler_output_size = pooler_output_size if pooler_output_size else hidden_size
  114. self.pooler_act = pooler_act
  115. class ViTOnnxConfig(OnnxConfig):
  116. torch_onnx_minimum_version = version.parse("1.11")
  117. @property
  118. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  119. return OrderedDict(
  120. [
  121. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  122. ]
  123. )
  124. @property
  125. def atol_for_validation(self) -> float:
  126. return 1e-4
  127. __all__ = ["ViTConfig", "ViTOnnxConfig"]