configuration_altclip.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. # coding=utf-8
  2. # Copyright 2022 WenXiang ZhongzhiCheng LedellWu LiuGuang BoWenZhang 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. """AltCLIP model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class AltCLIPTextConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`AltCLIPTextModel`]. It is used to instantiate a
  22. AltCLIP text model according to the specified arguments, defining the model architecture. Instantiating a
  23. configuration with the defaults will yield a similar configuration to that of the AltCLIP
  24. [BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
  25. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  26. documentation from [`PretrainedConfig`] for more information.
  27. Args:
  28. vocab_size (`int`, *optional*, defaults to 250002):
  29. Vocabulary size of the AltCLIP model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`AltCLIPTextModel`].
  31. hidden_size (`int`, *optional*, defaults to 1024):
  32. Dimensionality of the encoder layers and the pooler layer.
  33. num_hidden_layers (`int`, *optional*, defaults to 24):
  34. Number of hidden layers in the Transformer encoder.
  35. num_attention_heads (`int`, *optional*, defaults to 16):
  36. Number of attention heads for each attention layer in the Transformer encoder.
  37. intermediate_size (`int`, *optional*, defaults to 4096):
  38. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  39. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  40. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  41. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  42. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  43. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  44. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  45. The dropout ratio for the attention probabilities.
  46. max_position_embeddings (`int`, *optional*, defaults to 514):
  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. type_vocab_size (`int`, *optional*, defaults to 1):
  50. The vocabulary size of the `token_type_ids` passed when calling [`AltCLIPTextModel`]
  51. initializer_range (`float`, *optional*, defaults to 0.02):
  52. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  53. initializer_factor (`float`, *optional*, defaults to 0.02):
  54. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  55. testing).
  56. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  57. The epsilon used by the layer normalization layers.
  58. pad_token_id (`int`, *optional*, defaults to 1): The id of the *padding* token.
  59. bos_token_id (`int`, *optional*, defaults to 0): The id of the *beginning-of-sequence* token.
  60. eos_token_id (`Union[int, list[int]]`, *optional*, defaults to 2):
  61. The id of the *end-of-sequence* token. Optionally, use a list to set multiple *end-of-sequence* tokens.
  62. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  63. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  64. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  65. [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
  66. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  67. with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
  68. use_cache (`bool`, *optional*, defaults to `True`):
  69. Whether or not the model should return the last key/values attentions (not used by all models). Only
  70. relevant if `config.is_decoder=True`.
  71. project_dim (`int`, *optional*, defaults to 768):
  72. The dimensions of the teacher model before the mapping layer.
  73. Examples:
  74. ```python
  75. >>> from transformers import AltCLIPTextModel, AltCLIPTextConfig
  76. >>> # Initializing a AltCLIPTextConfig with BAAI/AltCLIP style configuration
  77. >>> configuration = AltCLIPTextConfig()
  78. >>> # Initializing a AltCLIPTextModel (with random weights) from the BAAI/AltCLIP style configuration
  79. >>> model = AltCLIPTextModel(configuration)
  80. >>> # Accessing the model configuration
  81. >>> configuration = model.config
  82. ```"""
  83. model_type = "altclip_text_model"
  84. def __init__(
  85. self,
  86. vocab_size=250002,
  87. hidden_size=1024,
  88. num_hidden_layers=24,
  89. num_attention_heads=16,
  90. intermediate_size=4096,
  91. hidden_act="gelu",
  92. hidden_dropout_prob=0.1,
  93. attention_probs_dropout_prob=0.1,
  94. max_position_embeddings=514,
  95. type_vocab_size=1,
  96. initializer_range=0.02,
  97. initializer_factor=0.02,
  98. layer_norm_eps=1e-05,
  99. pad_token_id=1,
  100. bos_token_id=0,
  101. eos_token_id=2,
  102. position_embedding_type="absolute",
  103. use_cache=True,
  104. project_dim=768,
  105. **kwargs,
  106. ):
  107. super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  108. self.vocab_size = vocab_size
  109. self.hidden_size = hidden_size
  110. self.num_hidden_layers = num_hidden_layers
  111. self.num_attention_heads = num_attention_heads
  112. self.hidden_act = hidden_act
  113. self.intermediate_size = intermediate_size
  114. self.hidden_dropout_prob = hidden_dropout_prob
  115. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  116. self.max_position_embeddings = max_position_embeddings
  117. self.type_vocab_size = type_vocab_size
  118. self.initializer_range = initializer_range
  119. self.initializer_factor = initializer_factor
  120. self.layer_norm_eps = layer_norm_eps
  121. self.position_embedding_type = position_embedding_type
  122. self.use_cache = use_cache
  123. self.project_dim = project_dim
  124. class AltCLIPVisionConfig(PretrainedConfig):
  125. r"""
  126. This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
  127. AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
  128. with the defaults will yield a similar configuration to that of the AltCLIP
  129. [BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
  130. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  131. documentation from [`PretrainedConfig`] for more information.
  132. Args:
  133. hidden_size (`int`, *optional*, defaults to 768):
  134. Dimensionality of the encoder layers and the pooler layer.
  135. intermediate_size (`int`, *optional*, defaults to 3072):
  136. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  137. projection_dim (`int`, *optional*, defaults to 512):
  138. Dimensionality of text and vision projection layers.
  139. num_hidden_layers (`int`, *optional*, defaults to 12):
  140. Number of hidden layers in the Transformer encoder.
  141. num_attention_heads (`int`, *optional*, defaults to 12):
  142. Number of attention heads for each attention layer in the Transformer encoder.
  143. num_channels (`int`, *optional*, defaults to 3):
  144. The number of input channels.
  145. image_size (`int`, *optional*, defaults to 224):
  146. The size (resolution) of each image.
  147. patch_size (`int`, *optional*, defaults to 32):
  148. The size (resolution) of each patch.
  149. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  150. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  151. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  152. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  153. The epsilon used by the layer normalization layers.
  154. attention_dropout (`float`, *optional*, defaults to 0.0):
  155. The dropout ratio for the attention probabilities.
  156. initializer_range (`float`, *optional*, defaults to 0.02):
  157. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  158. initializer_factor (`float`, *optional*, defaults to 1.0):
  159. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  160. testing).
  161. Example:
  162. ```python
  163. >>> from transformers import AltCLIPVisionConfig, AltCLIPVisionModel
  164. >>> # Initializing a AltCLIPVisionConfig with BAAI/AltCLIP style configuration
  165. >>> configuration = AltCLIPVisionConfig()
  166. >>> # Initializing a AltCLIPVisionModel (with random weights) from the BAAI/AltCLIP style configuration
  167. >>> model = AltCLIPVisionModel(configuration)
  168. >>> # Accessing the model configuration
  169. >>> configuration = model.config
  170. ```"""
  171. model_type = "altclip_vision_model"
  172. base_config_key = "vision_config"
  173. def __init__(
  174. self,
  175. hidden_size=768,
  176. intermediate_size=3072,
  177. projection_dim=512,
  178. num_hidden_layers=12,
  179. num_attention_heads=12,
  180. num_channels=3,
  181. image_size=224,
  182. patch_size=32,
  183. hidden_act="quick_gelu",
  184. layer_norm_eps=1e-5,
  185. attention_dropout=0.0,
  186. initializer_range=0.02,
  187. initializer_factor=1.0,
  188. **kwargs,
  189. ):
  190. super().__init__(**kwargs)
  191. self.hidden_size = hidden_size
  192. self.intermediate_size = intermediate_size
  193. self.projection_dim = projection_dim
  194. self.num_hidden_layers = num_hidden_layers
  195. self.num_attention_heads = num_attention_heads
  196. self.num_channels = num_channels
  197. self.patch_size = patch_size
  198. self.image_size = image_size
  199. self.initializer_range = initializer_range
  200. self.initializer_factor = initializer_factor
  201. self.attention_dropout = attention_dropout
  202. self.layer_norm_eps = layer_norm_eps
  203. self.hidden_act = hidden_act
  204. class AltCLIPConfig(PretrainedConfig):
  205. r"""
  206. This is the configuration class to store the configuration of a [`AltCLIPModel`]. It is used to instantiate an
  207. AltCLIP model according to the specified arguments, defining the model architecture. Instantiating a configuration
  208. with the defaults will yield a similar configuration to that of the AltCLIP
  209. [BAAI/AltCLIP](https://huggingface.co/BAAI/AltCLIP) architecture.
  210. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  211. documentation from [`PretrainedConfig`] for more information.
  212. Args:
  213. text_config (`dict`, *optional*):
  214. Dictionary of configuration options used to initialize [`AltCLIPTextConfig`].
  215. vision_config (`dict`, *optional*):
  216. Dictionary of configuration options used to initialize [`AltCLIPVisionConfig`].
  217. projection_dim (`int`, *optional*, defaults to 768):
  218. Dimensionality 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 CLIP implementation.
  221. kwargs (*optional*):
  222. Dictionary of keyword arguments.
  223. Example:
  224. ```python
  225. >>> from transformers import AltCLIPConfig, AltCLIPModel
  226. >>> # Initializing a AltCLIPConfig with BAAI/AltCLIP style configuration
  227. >>> configuration = AltCLIPConfig()
  228. >>> # Initializing a AltCLIPModel (with random weights) from the BAAI/AltCLIP style configuration
  229. >>> model = AltCLIPModel(configuration)
  230. >>> # Accessing the model configuration
  231. >>> configuration = model.config
  232. >>> # We can also initialize a AltCLIPConfig from a AltCLIPTextConfig and a AltCLIPVisionConfig
  233. >>> # Initializing a AltCLIPText and AltCLIPVision configuration
  234. >>> config_text = AltCLIPTextConfig()
  235. >>> config_vision = AltCLIPVisionConfig()
  236. >>> config = AltCLIPConfig.from_text_vision_configs(config_text, config_vision)
  237. ```"""
  238. model_type = "altclip"
  239. sub_configs = {"text_config": AltCLIPTextConfig, "vision_config": AltCLIPVisionConfig}
  240. def __init__(
  241. self, text_config=None, vision_config=None, projection_dim=768, logit_scale_init_value=2.6592, **kwargs
  242. ):
  243. # If `_config_dict` exist, we use them for the backward compatibility.
  244. # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
  245. # of confusion!).
  246. text_config_dict = kwargs.pop("text_config_dict", None)
  247. vision_config_dict = kwargs.pop("vision_config_dict", None)
  248. super().__init__(**kwargs)
  249. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  250. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  251. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  252. if text_config_dict is not None:
  253. if text_config is None:
  254. text_config = {}
  255. # This is the complete result when using `text_config_dict`.
  256. _text_config_dict = AltCLIPTextConfig(**text_config_dict).to_dict()
  257. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  258. for key, value in _text_config_dict.items():
  259. if key in text_config and value != text_config[key] and key != "transformers_version":
  260. # If specified in `text_config_dict`
  261. if key in text_config_dict:
  262. message = (
  263. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  264. f'The value `text_config_dict["{key}"]` will be used instead.'
  265. )
  266. # If inferred from default argument values (just to be super careful)
  267. else:
  268. message = (
  269. f"`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The "
  270. f'value `text_config["{key}"]` will be overridden.'
  271. )
  272. logger.info(message)
  273. # Update all values in `text_config` with the ones in `_text_config_dict`.
  274. text_config.update(_text_config_dict)
  275. if vision_config_dict is not None:
  276. if vision_config is None:
  277. vision_config = {}
  278. # This is the complete result when using `vision_config_dict`.
  279. _vision_config_dict = AltCLIPVisionConfig(**vision_config_dict).to_dict()
  280. # convert keys to string instead of integer
  281. if "id2label" in _vision_config_dict:
  282. _vision_config_dict["id2label"] = {
  283. str(key): value for key, value in _vision_config_dict["id2label"].items()
  284. }
  285. # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
  286. for key, value in _vision_config_dict.items():
  287. if key in vision_config and value != vision_config[key] and key != "transformers_version":
  288. # If specified in `vision_config_dict`
  289. if key in vision_config_dict:
  290. message = (
  291. f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
  292. f'values. The value `vision_config_dict["{key}"]` will be used instead.'
  293. )
  294. # If inferred from default argument values (just to be super careful)
  295. else:
  296. message = (
  297. f"`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. "
  298. f'The value `vision_config["{key}"]` will be overridden.'
  299. )
  300. logger.info(message)
  301. # Update all values in `vision_config` with the ones in `_vision_config_dict`.
  302. vision_config.update(_vision_config_dict)
  303. if text_config is None:
  304. text_config = {}
  305. logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values.")
  306. if vision_config is None:
  307. vision_config = {}
  308. logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values.")
  309. self.text_config = AltCLIPTextConfig(**text_config)
  310. self.vision_config = AltCLIPVisionConfig(**vision_config)
  311. self.projection_dim = projection_dim
  312. self.logit_scale_init_value = logit_scale_init_value
  313. self.initializer_factor = 1.0
  314. __all__ = ["AltCLIPTextConfig", "AltCLIPVisionConfig", "AltCLIPConfig"]