configuration_vit.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 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 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. Example:
  62. ```python
  63. >>> from transformers import ViTConfig, ViTModel
  64. >>> # Initializing a ViT vit-base-patch16-224 style configuration
  65. >>> configuration = ViTConfig()
  66. >>> # Initializing a model (with random weights) from the vit-base-patch16-224 style configuration
  67. >>> model = ViTModel(configuration)
  68. >>> # Accessing the model configuration
  69. >>> configuration = model.config
  70. ```"""
  71. model_type = "vit"
  72. def __init__(
  73. self,
  74. hidden_size=768,
  75. num_hidden_layers=12,
  76. num_attention_heads=12,
  77. intermediate_size=3072,
  78. hidden_act="gelu",
  79. hidden_dropout_prob=0.0,
  80. attention_probs_dropout_prob=0.0,
  81. initializer_range=0.02,
  82. layer_norm_eps=1e-12,
  83. image_size=224,
  84. patch_size=16,
  85. num_channels=3,
  86. qkv_bias=True,
  87. encoder_stride=16,
  88. **kwargs,
  89. ):
  90. super().__init__(**kwargs)
  91. self.hidden_size = hidden_size
  92. self.num_hidden_layers = num_hidden_layers
  93. self.num_attention_heads = num_attention_heads
  94. self.intermediate_size = intermediate_size
  95. self.hidden_act = hidden_act
  96. self.hidden_dropout_prob = hidden_dropout_prob
  97. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  98. self.initializer_range = initializer_range
  99. self.layer_norm_eps = layer_norm_eps
  100. self.image_size = image_size
  101. self.patch_size = patch_size
  102. self.num_channels = num_channels
  103. self.qkv_bias = qkv_bias
  104. self.encoder_stride = encoder_stride
  105. class ViTOnnxConfig(OnnxConfig):
  106. torch_onnx_minimum_version = version.parse("1.11")
  107. @property
  108. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  109. return OrderedDict(
  110. [
  111. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  112. ]
  113. )
  114. @property
  115. def atol_for_validation(self) -> float:
  116. return 1e-4