configuration_groupvit.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. """GroupViT model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import TYPE_CHECKING, Any, Optional
  19. from ...configuration_utils import PretrainedConfig
  20. from ...onnx import OnnxConfig
  21. from ...utils import logging
  22. if TYPE_CHECKING:
  23. from ...processing_utils import ProcessorMixin
  24. from ...utils import TensorType
  25. logger = logging.get_logger(__name__)
  26. class GroupViTTextConfig(PretrainedConfig):
  27. r"""
  28. This is the configuration class to store the configuration of a [`GroupViTTextModel`]. It is used to instantiate an
  29. GroupViT model according to the specified arguments, defining the model architecture. Instantiating a configuration
  30. with the defaults will yield a similar configuration to that of the GroupViT
  31. [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) 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 GroupViT text model. Defines the number of different tokens that can be represented
  37. by the `inputs_ids` passed when calling [`GroupViTModel`].
  38. hidden_size (`int`, *optional*, defaults to 256):
  39. Dimensionality of the encoder layers and the pooler layer.
  40. intermediate_size (`int`, *optional*, defaults to 1024):
  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 4):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. max_position_embeddings (`int`, *optional*, defaults to 77):
  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-5):
  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. dropout (`float`, *optional*, defaults to 0.0):
  57. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  58. initializer_range (`float`, *optional*, defaults to 0.02):
  59. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  60. initializer_factor (`float`, *optional*, defaults to 1.0):
  61. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  62. testing).
  63. Example:
  64. ```python
  65. >>> from transformers import GroupViTTextConfig, GroupViTTextModel
  66. >>> # Initializing a GroupViTTextModel with nvidia/groupvit-gcc-yfcc style configuration
  67. >>> configuration = GroupViTTextConfig()
  68. >>> model = GroupViTTextModel(configuration)
  69. >>> # Accessing the model configuration
  70. >>> configuration = model.config
  71. ```"""
  72. model_type = "groupvit_text_model"
  73. base_config_key = "text_config"
  74. def __init__(
  75. self,
  76. vocab_size=49408,
  77. hidden_size=256,
  78. intermediate_size=1024,
  79. num_hidden_layers=12,
  80. num_attention_heads=4,
  81. max_position_embeddings=77,
  82. hidden_act="quick_gelu",
  83. layer_norm_eps=1e-5,
  84. dropout=0.0,
  85. attention_dropout=0.0,
  86. initializer_range=0.02,
  87. initializer_factor=1.0,
  88. pad_token_id=1,
  89. bos_token_id=49406,
  90. eos_token_id=49407,
  91. **kwargs,
  92. ):
  93. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  94. self.vocab_size = vocab_size
  95. self.hidden_size = hidden_size
  96. self.intermediate_size = intermediate_size
  97. self.dropout = dropout
  98. self.num_hidden_layers = num_hidden_layers
  99. self.num_attention_heads = num_attention_heads
  100. self.max_position_embeddings = max_position_embeddings
  101. self.layer_norm_eps = layer_norm_eps
  102. self.hidden_act = hidden_act
  103. self.initializer_range = initializer_range
  104. self.initializer_factor = initializer_factor
  105. self.attention_dropout = attention_dropout
  106. class GroupViTVisionConfig(PretrainedConfig):
  107. r"""
  108. This is the configuration class to store the configuration of a [`GroupViTVisionModel`]. It is used to instantiate
  109. an GroupViT model according to the specified arguments, defining the model architecture. Instantiating a
  110. configuration with the defaults will yield a similar configuration to that of the GroupViT
  111. [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) architecture.
  112. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  113. documentation from [`PretrainedConfig`] for more information.
  114. Args:
  115. hidden_size (`int`, *optional*, defaults to 384):
  116. Dimensionality of the encoder layers and the pooler layer.
  117. intermediate_size (`int`, *optional*, defaults to 1536):
  118. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  119. depths (`list[int]`, *optional*, defaults to [6, 3, 3]):
  120. The number of layers in each encoder block.
  121. num_group_tokens (`list[int]`, *optional*, defaults to [64, 8, 0]):
  122. The number of group tokens for each stage.
  123. num_output_groups (`list[int]`, *optional*, defaults to [64, 8, 8]):
  124. The number of output groups for each stage, 0 means no group.
  125. num_attention_heads (`int`, *optional*, defaults to 6):
  126. Number of attention heads for each attention layer in the Transformer encoder.
  127. image_size (`int`, *optional*, defaults to 224):
  128. The size (resolution) of each image.
  129. patch_size (`int`, *optional*, defaults to 16):
  130. The size (resolution) of each patch.
  131. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  132. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  133. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  134. layer_norm_eps (`float`, *optional*, defaults to 1e-5):
  135. The epsilon used by the layer normalization layers.
  136. dropout (`float`, *optional*, defaults to 0.0):
  137. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  138. attention_dropout (`float`, *optional*, defaults to 0.0):
  139. The dropout ratio for the attention probabilities.
  140. initializer_range (`float`, *optional*, defaults to 0.02):
  141. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  142. initializer_factor (`float`, *optional*, defaults to 1.0):
  143. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  144. testing).
  145. Example:
  146. ```python
  147. >>> from transformers import GroupViTVisionConfig, GroupViTVisionModel
  148. >>> # Initializing a GroupViTVisionModel with nvidia/groupvit-gcc-yfcc style configuration
  149. >>> configuration = GroupViTVisionConfig()
  150. >>> model = GroupViTVisionModel(configuration)
  151. >>> # Accessing the model configuration
  152. >>> configuration = model.config
  153. ```"""
  154. model_type = "groupvit_vision_model"
  155. base_config_key = "vision_config"
  156. def __init__(
  157. self,
  158. hidden_size=384,
  159. intermediate_size=1536,
  160. depths=[6, 3, 3],
  161. num_hidden_layers=12,
  162. num_group_tokens=[64, 8, 0],
  163. num_output_groups=[64, 8, 8],
  164. num_attention_heads=6,
  165. image_size=224,
  166. patch_size=16,
  167. num_channels=3,
  168. hidden_act="gelu",
  169. layer_norm_eps=1e-5,
  170. dropout=0.0,
  171. attention_dropout=0.0,
  172. initializer_range=0.02,
  173. initializer_factor=1.0,
  174. assign_eps=1.0,
  175. assign_mlp_ratio=[0.5, 4],
  176. **kwargs,
  177. ):
  178. super().__init__(**kwargs)
  179. self.hidden_size = hidden_size
  180. self.intermediate_size = intermediate_size
  181. self.depths = depths
  182. if num_hidden_layers != sum(depths):
  183. logger.warning(
  184. f"Manually setting num_hidden_layers to {num_hidden_layers}, but we expect num_hidden_layers ="
  185. f" sum(depth) = {sum(depths)}"
  186. )
  187. self.num_hidden_layers = num_hidden_layers
  188. self.num_group_tokens = num_group_tokens
  189. self.num_output_groups = num_output_groups
  190. self.num_attention_heads = num_attention_heads
  191. self.image_size = image_size
  192. self.patch_size = patch_size
  193. self.num_channels = num_channels
  194. self.hidden_act = hidden_act
  195. self.layer_norm_eps = layer_norm_eps
  196. self.dropout = dropout
  197. self.attention_dropout = attention_dropout
  198. self.initializer_range = initializer_range
  199. self.initializer_factor = initializer_factor
  200. self.assign_eps = assign_eps
  201. self.assign_mlp_ratio = assign_mlp_ratio
  202. class GroupViTConfig(PretrainedConfig):
  203. r"""
  204. [`GroupViTConfig`] is the configuration class to store the configuration of a [`GroupViTModel`]. It is used to
  205. instantiate a GroupViT model according to the specified arguments, defining the text model and vision model
  206. configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the GroupViT
  207. [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) architecture.
  208. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  209. documentation from [`PretrainedConfig`] for more information.
  210. Args:
  211. text_config (`dict`, *optional*):
  212. Dictionary of configuration options used to initialize [`GroupViTTextConfig`].
  213. vision_config (`dict`, *optional*):
  214. Dictionary of configuration options used to initialize [`GroupViTVisionConfig`].
  215. projection_dim (`int`, *optional*, defaults to 256):
  216. Dimensionality of text and vision projection layers.
  217. projection_intermediate_dim (`int`, *optional*, defaults to 4096):
  218. Dimensionality of intermediate layer of text and vision projection layers.
  219. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  220. The initial value of the *logit_scale* parameter. Default is used as per the original GroupViT
  221. implementation.
  222. kwargs (*optional*):
  223. Dictionary of keyword arguments.
  224. """
  225. model_type = "groupvit"
  226. sub_configs = {"text_config": GroupViTTextConfig, "vision_config": GroupViTVisionConfig}
  227. def __init__(
  228. self,
  229. text_config=None,
  230. vision_config=None,
  231. projection_dim=256,
  232. projection_intermediate_dim=4096,
  233. logit_scale_init_value=2.6592,
  234. **kwargs,
  235. ):
  236. # If `_config_dict` exist, we use them for the backward compatibility.
  237. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
  238. # of confusion!).
  239. text_config_dict = kwargs.pop("text_config_dict", None)
  240. vision_config_dict = kwargs.pop("vision_config_dict", None)
  241. super().__init__(**kwargs)
  242. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  243. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  244. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  245. if text_config_dict is not None:
  246. if text_config is None:
  247. text_config = {}
  248. # This is the complete result when using `text_config_dict`.
  249. _text_config_dict = GroupViTTextConfig(**text_config_dict).to_dict()
  250. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  251. for key, value in _text_config_dict.items():
  252. if key in text_config and value != text_config[key] and key != "transformers_version":
  253. # If specified in `text_config_dict`
  254. if key in text_config_dict:
  255. message = (
  256. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  257. f'The value `text_config_dict["{key}"]` will be used instead.'
  258. )
  259. # If inferred from default argument values (just to be super careful)
  260. else:
  261. message = (
  262. f"`text_config_dict` is provided which will be used to initialize `GroupViTTextConfig`. "
  263. f'The value `text_config["{key}"]` will be overridden.'
  264. )
  265. logger.info(message)
  266. # Update all values in `text_config` with the ones in `_text_config_dict`.
  267. text_config.update(_text_config_dict)
  268. if vision_config_dict is not None:
  269. if vision_config is None:
  270. vision_config = {}
  271. # This is the complete result when using `vision_config_dict`.
  272. _vision_config_dict = GroupViTVisionConfig(**vision_config_dict).to_dict()
  273. # convert keys to string instead of integer
  274. if "id2label" in _vision_config_dict:
  275. _vision_config_dict["id2label"] = {
  276. str(key): value for key, value in _vision_config_dict["id2label"].items()
  277. }
  278. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  279. for key, value in _vision_config_dict.items():
  280. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  281. # If specified in `vision_config_dict`
  282. if key in vision_config_dict:
  283. message = (
  284. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  285. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  286. )
  287. # If inferred from default argument values (just to be super careful)
  288. else:
  289. message = (
  290. f"`vision_config_dict` is provided which will be used to initialize `GroupViTVisionConfig`."
  291. f' The value `vision_config["{key}"]` will be overridden.'
  292. )
  293. logger.info(message)
  294. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  295. vision_config.update(_vision_config_dict)
  296. if text_config is None:
  297. text_config = {}
  298. logger.info("`text_config` is `None`. Initializing the `GroupViTTextConfig` with default values.")
  299. if vision_config is None:
  300. vision_config = {}
  301. logger.info("`vision_config` is `None`. initializing the `GroupViTVisionConfig` with default values.")
  302. self.text_config = GroupViTTextConfig(**text_config)
  303. self.vision_config = GroupViTVisionConfig(**vision_config)
  304. self.projection_dim = projection_dim
  305. self.projection_intermediate_dim = projection_intermediate_dim
  306. self.logit_scale_init_value = logit_scale_init_value
  307. self.initializer_range = 0.02
  308. self.initializer_factor = 1.0
  309. self.output_segmentation = False
  310. class GroupViTOnnxConfig(OnnxConfig):
  311. @property
  312. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  313. return OrderedDict(
  314. [
  315. ("input_ids", {0: "batch", 1: "sequence"}),
  316. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  317. ("attention_mask", {0: "batch", 1: "sequence"}),
  318. ]
  319. )
  320. @property
  321. def outputs(self) -> Mapping[str, Mapping[int, str]]:
  322. return OrderedDict(
  323. [
  324. ("logits_per_image", {0: "batch"}),
  325. ("logits_per_text", {0: "batch"}),
  326. ("text_embeds", {0: "batch"}),
  327. ("image_embeds", {0: "batch"}),
  328. ]
  329. )
  330. @property
  331. def atol_for_validation(self) -> float:
  332. return 1e-4
  333. def generate_dummy_inputs(
  334. self,
  335. processor: "ProcessorMixin",
  336. batch_size: int = -1,
  337. seq_length: int = -1,
  338. framework: Optional["TensorType"] = None,
  339. ) -> Mapping[str, Any]:
  340. text_input_dict = super().generate_dummy_inputs(
  341. processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
  342. )
  343. image_input_dict = super().generate_dummy_inputs(
  344. processor.image_processor, batch_size=batch_size, framework=framework
  345. )
  346. return {**text_input_dict, **image_input_dict}
  347. @property
  348. def default_onnx_opset(self) -> int:
  349. return 14
  350. __all__ = ["GroupViTConfig", "GroupViTOnnxConfig", "GroupViTTextConfig", "GroupViTVisionConfig"]