configuration_owlv2.py 13 KB

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