configuration_owlvit.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. """OWL-ViT model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import TYPE_CHECKING, Any, Optional
  19. if TYPE_CHECKING:
  20. from ...processing_utils import ProcessorMixin
  21. from ...utils import TensorType
  22. from ...configuration_utils import PretrainedConfig
  23. from ...onnx import OnnxConfig
  24. from ...utils import logging
  25. logger = logging.get_logger(__name__)
  26. class OwlViTTextConfig(PretrainedConfig):
  27. r"""
  28. This is the configuration class to store the configuration of an [`OwlViTTextModel`]. It is used to instantiate an
  29. OwlViT text encoder according to the specified arguments, defining the model architecture. Instantiating a
  30. configuration with the defaults will yield a similar configuration to that of the OwlViT
  31. [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.
  32. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  33. documentation from [`PretrainedConfig`] for more information.
  34. Args:
  35. vocab_size (`int`, *optional*, defaults to 49408):
  36. Vocabulary size of the OWL-ViT text model. Defines the number of different tokens that can be represented
  37. by the `inputs_ids` passed when calling [`OwlViTTextModel`].
  38. hidden_size (`int`, *optional*, defaults to 512):
  39. Dimensionality of the encoder layers and the pooler layer.
  40. intermediate_size (`int`, *optional*, defaults to 2048):
  41. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  42. num_hidden_layers (`int`, *optional*, defaults to 12):
  43. Number of hidden layers in the Transformer encoder.
  44. num_attention_heads (`int`, *optional*, defaults to 8):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. max_position_embeddings (`int`, *optional*, defaults to 16):
  47. The maximum sequence length that this model might ever be used with. Typically set this to something large
  48. just in case (e.g., 512 or 1024 or 2048).
  49. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  50. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  51. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  52. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  53. The epsilon used by the layer normalization layers.
  54. attention_dropout (`float`, *optional*, defaults to 0.0):
  55. The dropout ratio for the attention probabilities.
  56. initializer_range (`float`, *optional*, defaults to 0.02):
  57. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  58. initializer_factor (`float`, *optional*, defaults to 1.0):
  59. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  60. testing).
  61. pad_token_id (`int`, *optional*, defaults to 0):
  62. The id of the padding token in the input sequences.
  63. bos_token_id (`int`, *optional*, defaults to 49406):
  64. The id of the beginning-of-sequence token in the input sequences.
  65. eos_token_id (`int`, *optional*, defaults to 49407):
  66. The id of the end-of-sequence token in the input sequences.
  67. Example:
  68. ```python
  69. >>> from transformers import OwlViTTextConfig, OwlViTTextModel
  70. >>> # Initializing a OwlViTTextModel with google/owlvit-base-patch32 style configuration
  71. >>> configuration = OwlViTTextConfig()
  72. >>> # Initializing a OwlViTTextConfig from the google/owlvit-base-patch32 style configuration
  73. >>> model = OwlViTTextModel(configuration)
  74. >>> # Accessing the model configuration
  75. >>> configuration = model.config
  76. ```"""
  77. model_type = "owlvit_text_model"
  78. base_config_key = "text_config"
  79. def __init__(
  80. self,
  81. vocab_size=49408,
  82. hidden_size=512,
  83. intermediate_size=2048,
  84. num_hidden_layers=12,
  85. num_attention_heads=8,
  86. max_position_embeddings=16,
  87. hidden_act="quick_gelu",
  88. layer_norm_eps=1e-5,
  89. attention_dropout=0.0,
  90. initializer_range=0.02,
  91. initializer_factor=1.0,
  92. pad_token_id=0,
  93. bos_token_id=49406,
  94. eos_token_id=49407,
  95. **kwargs,
  96. ):
  97. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  98. self.vocab_size = vocab_size
  99. self.hidden_size = hidden_size
  100. self.intermediate_size = intermediate_size
  101. self.num_hidden_layers = num_hidden_layers
  102. self.num_attention_heads = num_attention_heads
  103. self.max_position_embeddings = max_position_embeddings
  104. self.hidden_act = hidden_act
  105. self.layer_norm_eps = layer_norm_eps
  106. self.attention_dropout = attention_dropout
  107. self.initializer_range = initializer_range
  108. self.initializer_factor = initializer_factor
  109. class OwlViTVisionConfig(PretrainedConfig):
  110. r"""
  111. This is the configuration class to store the configuration of an [`OwlViTVisionModel`]. It is used to instantiate
  112. an OWL-ViT image encoder according to the specified arguments, defining the model architecture. Instantiating a
  113. configuration with the defaults will yield a similar configuration to that of the OWL-ViT
  114. [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.
  115. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  116. documentation from [`PretrainedConfig`] for more information.
  117. Args:
  118. hidden_size (`int`, *optional*, defaults to 768):
  119. Dimensionality of the encoder layers and the pooler layer.
  120. intermediate_size (`int`, *optional*, defaults to 3072):
  121. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  122. num_hidden_layers (`int`, *optional*, defaults to 12):
  123. Number of hidden layers in the Transformer encoder.
  124. num_attention_heads (`int`, *optional*, defaults to 12):
  125. Number of attention heads for each attention layer in the Transformer encoder.
  126. num_channels (`int`, *optional*, defaults to 3):
  127. Number of channels in the input images.
  128. image_size (`int`, *optional*, defaults to 768):
  129. The size (resolution) of each image.
  130. patch_size (`int`, *optional*, defaults to 32):
  131. The size (resolution) of each patch.
  132. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  133. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  134. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  135. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  136. The epsilon used by the layer normalization layers.
  137. attention_dropout (`float`, *optional*, defaults to 0.0):
  138. The dropout ratio for the attention probabilities.
  139. initializer_range (`float`, *optional*, defaults to 0.02):
  140. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  141. initializer_factor (`float`, *optional*, defaults to 1.0):
  142. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  143. testing).
  144. Example:
  145. ```python
  146. >>> from transformers import OwlViTVisionConfig, OwlViTVisionModel
  147. >>> # Initializing a OwlViTVisionModel with google/owlvit-base-patch32 style configuration
  148. >>> configuration = OwlViTVisionConfig()
  149. >>> # Initializing a OwlViTVisionModel model from the google/owlvit-base-patch32 style configuration
  150. >>> model = OwlViTVisionModel(configuration)
  151. >>> # Accessing the model configuration
  152. >>> configuration = model.config
  153. ```"""
  154. model_type = "owlvit_vision_model"
  155. base_config_key = "vision_config"
  156. def __init__(
  157. self,
  158. hidden_size=768,
  159. intermediate_size=3072,
  160. num_hidden_layers=12,
  161. num_attention_heads=12,
  162. num_channels=3,
  163. image_size=768,
  164. patch_size=32,
  165. hidden_act="quick_gelu",
  166. layer_norm_eps=1e-5,
  167. attention_dropout=0.0,
  168. initializer_range=0.02,
  169. initializer_factor=1.0,
  170. **kwargs,
  171. ):
  172. super().__init__(**kwargs)
  173. self.hidden_size = hidden_size
  174. self.intermediate_size = intermediate_size
  175. self.num_hidden_layers = num_hidden_layers
  176. self.num_attention_heads = num_attention_heads
  177. self.num_channels = num_channels
  178. self.image_size = image_size
  179. self.patch_size = patch_size
  180. self.hidden_act = hidden_act
  181. self.layer_norm_eps = layer_norm_eps
  182. self.attention_dropout = attention_dropout
  183. self.initializer_range = initializer_range
  184. self.initializer_factor = initializer_factor
  185. class OwlViTConfig(PretrainedConfig):
  186. r"""
  187. [`OwlViTConfig`] is the configuration class to store the configuration of an [`OwlViTModel`]. It is used to
  188. instantiate an OWL-ViT model according to the specified arguments, defining the text model and vision model
  189. configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the OWL-ViT
  190. [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.
  191. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  192. documentation from [`PretrainedConfig`] for more information.
  193. Args:
  194. text_config (`dict`, *optional*):
  195. Dictionary of configuration options used to initialize [`OwlViTTextConfig`].
  196. vision_config (`dict`, *optional*):
  197. Dictionary of configuration options used to initialize [`OwlViTVisionConfig`].
  198. projection_dim (`int`, *optional*, defaults to 512):
  199. Dimensionality of text and vision projection layers.
  200. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  201. The initial value of the *logit_scale* parameter. Default is used as per the original OWL-ViT
  202. implementation.
  203. return_dict (`bool`, *optional*, defaults to `True`):
  204. Whether or not the model should return a dictionary. If `False`, returns a tuple.
  205. kwargs (*optional*):
  206. Dictionary of keyword arguments.
  207. """
  208. model_type = "owlvit"
  209. sub_configs = {"text_config": OwlViTTextConfig, "vision_config": OwlViTVisionConfig}
  210. def __init__(
  211. self,
  212. text_config=None,
  213. vision_config=None,
  214. projection_dim=512,
  215. logit_scale_init_value=2.6592,
  216. return_dict=True,
  217. **kwargs,
  218. ):
  219. super().__init__(**kwargs)
  220. if text_config is None:
  221. text_config = {}
  222. logger.info("text_config is None. Initializing the OwlViTTextConfig with default values.")
  223. if vision_config is None:
  224. vision_config = {}
  225. logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values.")
  226. self.text_config = OwlViTTextConfig(**text_config)
  227. self.vision_config = OwlViTVisionConfig(**vision_config)
  228. self.projection_dim = projection_dim
  229. self.logit_scale_init_value = logit_scale_init_value
  230. self.return_dict = return_dict
  231. self.initializer_factor = 1.0
  232. @classmethod
  233. def from_text_vision_configs(cls, text_config: dict, vision_config: dict, **kwargs):
  234. r"""
  235. Instantiate a [`OwlViTConfig`] (or a derived class) from owlvit text model configuration and owlvit vision
  236. model configuration.
  237. Returns:
  238. [`OwlViTConfig`]: An instance of a configuration object
  239. """
  240. config_dict = {}
  241. config_dict["text_config"] = text_config
  242. config_dict["vision_config"] = vision_config
  243. return cls.from_dict(config_dict, **kwargs)
  244. class OwlViTOnnxConfig(OnnxConfig):
  245. @property
  246. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  247. return OrderedDict(
  248. [
  249. ("input_ids", {0: "batch", 1: "sequence"}),
  250. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  251. ("attention_mask", {0: "batch", 1: "sequence"}),
  252. ]
  253. )
  254. @property
  255. def outputs(self) -> Mapping[str, Mapping[int, str]]:
  256. return OrderedDict(
  257. [
  258. ("logits_per_image", {0: "batch"}),
  259. ("logits_per_text", {0: "batch"}),
  260. ("text_embeds", {0: "batch"}),
  261. ("image_embeds", {0: "batch"}),
  262. ]
  263. )
  264. @property
  265. def atol_for_validation(self) -> float:
  266. return 1e-4
  267. def generate_dummy_inputs(
  268. self,
  269. processor: "ProcessorMixin",
  270. batch_size: int = -1,
  271. seq_length: int = -1,
  272. framework: Optional["TensorType"] = None,
  273. ) -> Mapping[str, Any]:
  274. text_input_dict = super().generate_dummy_inputs(
  275. processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
  276. )
  277. image_input_dict = super().generate_dummy_inputs(
  278. processor.image_processor, batch_size=batch_size, framework=framework
  279. )
  280. return {**text_input_dict, **image_input_dict}
  281. @property
  282. def default_onnx_opset(self) -> int:
  283. return 14
  284. __all__ = ["OwlViTConfig", "OwlViTOnnxConfig", "OwlViTTextConfig", "OwlViTVisionConfig"]