configuration_clip.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # coding=utf-8
  2. # Copyright 2021 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. """CLIP 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 CLIPTextConfig(PretrainedConfig):
  27. r"""
  28. This is the configuration class to store the configuration of a [`CLIPTextModel`]. It is used to instantiate a CLIP
  29. text encoder 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 text encoder of the CLIP
  31. [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-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 CLIP text model. Defines the number of different tokens that can be represented by
  37. the `inputs_ids` passed when calling [`CLIPModel`].
  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. projection_dim (`int`, *optional*, defaults to 512):
  43. Dimensionality of text and vision projection layers.
  44. num_hidden_layers (`int`, *optional*, defaults to 12):
  45. Number of hidden layers in the Transformer encoder.
  46. num_attention_heads (`int`, *optional*, defaults to 8):
  47. Number of attention heads for each attention layer in the Transformer encoder.
  48. max_position_embeddings (`int`, *optional*, defaults to 77):
  49. The maximum sequence length that this model might ever be used with. Typically set this to something large
  50. just in case (e.g., 512 or 1024 or 2048).
  51. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  52. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  53. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  54. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  55. The epsilon used by the layer normalization layers.
  56. attention_dropout (`float`, *optional*, defaults to 0.0):
  57. The dropout ratio for the attention probabilities.
  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. pad_token_id (`int`, *optional*, defaults to 1):
  64. Padding token id.
  65. bos_token_id (`int`, *optional*, defaults to 49406):
  66. Beginning of stream token id.
  67. eos_token_id (`int`, *optional*, defaults to 49407):
  68. End of stream token id.
  69. Example:
  70. ```python
  71. >>> from transformers import CLIPTextConfig, CLIPTextModel
  72. >>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
  73. >>> configuration = CLIPTextConfig()
  74. >>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
  75. >>> model = CLIPTextModel(configuration)
  76. >>> # Accessing the model configuration
  77. >>> configuration = model.config
  78. ```"""
  79. model_type = "clip_text_model"
  80. base_config_key = "text_config"
  81. def __init__(
  82. self,
  83. vocab_size=49408,
  84. hidden_size=512,
  85. intermediate_size=2048,
  86. projection_dim=512,
  87. num_hidden_layers=12,
  88. num_attention_heads=8,
  89. max_position_embeddings=77,
  90. hidden_act="quick_gelu",
  91. layer_norm_eps=1e-5,
  92. attention_dropout=0.0,
  93. initializer_range=0.02,
  94. initializer_factor=1.0,
  95. # This differs from `CLIPTokenizer`'s default and from openai/clip
  96. # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
  97. pad_token_id=1,
  98. bos_token_id=49406,
  99. eos_token_id=49407,
  100. **kwargs,
  101. ):
  102. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  103. self.vocab_size = vocab_size
  104. self.hidden_size = hidden_size
  105. self.intermediate_size = intermediate_size
  106. self.projection_dim = projection_dim
  107. self.num_hidden_layers = num_hidden_layers
  108. self.num_attention_heads = num_attention_heads
  109. self.max_position_embeddings = max_position_embeddings
  110. self.layer_norm_eps = layer_norm_eps
  111. self.hidden_act = hidden_act
  112. self.initializer_range = initializer_range
  113. self.initializer_factor = initializer_factor
  114. self.attention_dropout = attention_dropout
  115. class CLIPVisionConfig(PretrainedConfig):
  116. r"""
  117. This is the configuration class to store the configuration of a [`CLIPVisionModel`]. It is used to instantiate a
  118. CLIP vision encoder according to the specified arguments, defining the model architecture. Instantiating a
  119. configuration with the defaults will yield a similar configuration to that of the vision encoder of the CLIP
  120. [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
  121. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  122. documentation from [`PretrainedConfig`] for more information.
  123. Args:
  124. hidden_size (`int`, *optional*, defaults to 768):
  125. Dimensionality of the encoder layers and the pooler layer.
  126. intermediate_size (`int`, *optional*, defaults to 3072):
  127. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  128. projection_dim (`int`, *optional*, defaults to 512):
  129. Dimensionality of text and vision projection layers.
  130. num_hidden_layers (`int`, *optional*, defaults to 12):
  131. Number of hidden layers in the Transformer encoder.
  132. num_attention_heads (`int`, *optional*, defaults to 12):
  133. Number of attention heads for each attention layer in the Transformer encoder.
  134. num_channels (`int`, *optional*, defaults to 3):
  135. The number of input channels.
  136. image_size (`int`, *optional*, defaults to 224):
  137. The size (resolution) of each image.
  138. patch_size (`int`, *optional*, defaults to 32):
  139. The size (resolution) of each patch.
  140. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  141. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  142. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  143. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  144. The epsilon used by the layer normalization layers.
  145. attention_dropout (`float`, *optional*, defaults to 0.0):
  146. The dropout ratio for the attention probabilities.
  147. initializer_range (`float`, *optional*, defaults to 0.02):
  148. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  149. initializer_factor (`float`, *optional*, defaults to 1.0):
  150. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  151. testing).
  152. Example:
  153. ```python
  154. >>> from transformers import CLIPVisionConfig, CLIPVisionModel
  155. >>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
  156. >>> configuration = CLIPVisionConfig()
  157. >>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
  158. >>> model = CLIPVisionModel(configuration)
  159. >>> # Accessing the model configuration
  160. >>> configuration = model.config
  161. ```"""
  162. model_type = "clip_vision_model"
  163. base_config_key = "vision_config"
  164. def __init__(
  165. self,
  166. hidden_size=768,
  167. intermediate_size=3072,
  168. projection_dim=512,
  169. num_hidden_layers=12,
  170. num_attention_heads=12,
  171. num_channels=3,
  172. image_size=224,
  173. patch_size=32,
  174. hidden_act="quick_gelu",
  175. layer_norm_eps=1e-5,
  176. attention_dropout=0.0,
  177. initializer_range=0.02,
  178. initializer_factor=1.0,
  179. **kwargs,
  180. ):
  181. super().__init__(**kwargs)
  182. self.hidden_size = hidden_size
  183. self.intermediate_size = intermediate_size
  184. self.projection_dim = projection_dim
  185. self.num_hidden_layers = num_hidden_layers
  186. self.num_attention_heads = num_attention_heads
  187. self.num_channels = num_channels
  188. self.patch_size = patch_size
  189. self.image_size = image_size
  190. self.initializer_range = initializer_range
  191. self.initializer_factor = initializer_factor
  192. self.attention_dropout = attention_dropout
  193. self.layer_norm_eps = layer_norm_eps
  194. self.hidden_act = hidden_act
  195. class CLIPConfig(PretrainedConfig):
  196. r"""
  197. [`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
  198. a CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
  199. a configuration with the defaults will yield a similar configuration to that of the CLIP
  200. [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
  201. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  202. documentation from [`PretrainedConfig`] for more information.
  203. Args:
  204. text_config (`dict`, *optional*):
  205. Dictionary of configuration options used to initialize [`CLIPTextConfig`].
  206. vision_config (`dict`, *optional*):
  207. Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
  208. projection_dim (`int`, *optional*, defaults to 512):
  209. Dimensionality of text and vision projection layers.
  210. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  211. The initial value of the *logit_scale* parameter. Default is used as per the original CLIP implementation.
  212. kwargs (*optional*):
  213. Dictionary of keyword arguments.
  214. Example:
  215. ```python
  216. >>> from transformers import CLIPConfig, CLIPModel
  217. >>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
  218. >>> configuration = CLIPConfig()
  219. >>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
  220. >>> model = CLIPModel(configuration)
  221. >>> # Accessing the model configuration
  222. >>> configuration = model.config
  223. >>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
  224. >>> from transformers import CLIPTextConfig, CLIPVisionConfig
  225. >>> # Initializing a CLIPText and CLIPVision configuration
  226. >>> config_text = CLIPTextConfig()
  227. >>> config_vision = CLIPVisionConfig()
  228. >>> config = CLIPConfig.from_text_vision_configs(config_text, config_vision)
  229. ```"""
  230. model_type = "clip"
  231. sub_configs = {"text_config": CLIPTextConfig, "vision_config": CLIPVisionConfig}
  232. def __init__(
  233. self, text_config=None, vision_config=None, projection_dim=512, logit_scale_init_value=2.6592, **kwargs
  234. ):
  235. # If `_config_dict` exist, we use them for the backward compatibility.
  236. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
  237. # of confusion!).
  238. text_config_dict = kwargs.pop("text_config_dict", None)
  239. vision_config_dict = kwargs.pop("vision_config_dict", None)
  240. super().__init__(**kwargs)
  241. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  242. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  243. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  244. if text_config_dict is not None:
  245. if text_config is None:
  246. text_config = {}
  247. # This is the complete result when using `text_config_dict`.
  248. _text_config_dict = CLIPTextConfig(**text_config_dict).to_dict()
  249. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  250. for key, value in _text_config_dict.items():
  251. if key in text_config and value != text_config[key] and key != "transformers_version":
  252. # If specified in `text_config_dict`
  253. if key in text_config_dict:
  254. message = (
  255. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  256. f'The value `text_config_dict["{key}"]` will be used instead.'
  257. )
  258. # If inferred from default argument values (just to be super careful)
  259. else:
  260. message = (
  261. f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
  262. f'value `text_config["{key}"]` will be overridden.'
  263. )
  264. logger.info(message)
  265. # Update all values in `text_config` with the ones in `_text_config_dict`.
  266. text_config.update(_text_config_dict)
  267. if vision_config_dict is not None:
  268. if vision_config is None:
  269. vision_config = {}
  270. # This is the complete result when using `vision_config_dict`.
  271. _vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict()
  272. # convert keys to string instead of integer
  273. if "id2label" in _vision_config_dict:
  274. _vision_config_dict["id2label"] = {
  275. str(key): value for key, value in _vision_config_dict["id2label"].items()
  276. }
  277. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  278. for key, value in _vision_config_dict.items():
  279. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  280. # If specified in `vision_config_dict`
  281. if key in vision_config_dict:
  282. message = (
  283. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  284. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  285. )
  286. # If inferred from default argument values (just to be super careful)
  287. else:
  288. message = (
  289. f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
  290. f'The value `vision_config["{key}"]` will be overridden.'
  291. )
  292. logger.info(message)
  293. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  294. vision_config.update(_vision_config_dict)
  295. if text_config is None:
  296. text_config = {}
  297. logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
  298. if vision_config is None:
  299. vision_config = {}
  300. logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
  301. self.text_config = CLIPTextConfig(**text_config)
  302. self.vision_config = CLIPVisionConfig(**vision_config)
  303. self.projection_dim = projection_dim
  304. self.logit_scale_init_value = logit_scale_init_value
  305. self.initializer_factor = 1.0
  306. class CLIPOnnxConfig(OnnxConfig):
  307. @property
  308. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  309. return OrderedDict(
  310. [
  311. ("input_ids", {0: "batch", 1: "sequence"}),
  312. ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
  313. ("attention_mask", {0: "batch", 1: "sequence"}),
  314. ]
  315. )
  316. @property
  317. def outputs(self) -> Mapping[str, Mapping[int, str]]:
  318. return OrderedDict(
  319. [
  320. ("logits_per_image", {0: "batch"}),
  321. ("logits_per_text", {0: "batch"}),
  322. ("text_embeds", {0: "batch"}),
  323. ("image_embeds", {0: "batch"}),
  324. ]
  325. )
  326. @property
  327. def atol_for_validation(self) -> float:
  328. return 1e-4
  329. def generate_dummy_inputs(
  330. self,
  331. processor: "ProcessorMixin",
  332. batch_size: int = -1,
  333. seq_length: int = -1,
  334. framework: Optional["TensorType"] = None,
  335. ) -> Mapping[str, Any]:
  336. text_input_dict = super().generate_dummy_inputs(
  337. processor.tokenizer, batch_size=batch_size, seq_length=seq_length, framework=framework
  338. )
  339. image_input_dict = super().generate_dummy_inputs(
  340. processor.image_processor, batch_size=batch_size, framework=framework
  341. )
  342. return {**text_input_dict, **image_input_dict}
  343. @property
  344. def default_onnx_opset(self) -> int:
  345. return 14
  346. __all__ = ["CLIPConfig", "CLIPOnnxConfig", "CLIPTextConfig", "CLIPVisionConfig"]