configuration_flava.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. # Copyright 2022 Meta Platforms authors and The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """FLAVA model configurations"""
  15. from typing import Any
  16. from huggingface_hub.dataclasses import strict
  17. from ...configuration_utils import PreTrainedConfig
  18. from ...utils import auto_docstring, logging
  19. logger = logging.get_logger(__name__)
  20. @auto_docstring(checkpoint="facebook/flava-full")
  21. @strict
  22. class FlavaImageConfig(PreTrainedConfig):
  23. r"""
  24. mask_token (`bool`, *optional*, defaults to `True`):
  25. Whether to use a mask token or not. Used in MIM (Masked Image Modeling) loss for FLAVA.
  26. Example:
  27. ```python
  28. >>> from transformers import FlavaImageConfig, FlavaImageModel
  29. >>> # Initializing a FlavaImageModel with style configuration
  30. >>> configuration = FlavaImageConfig()
  31. >>> # Initializing a FlavaImageModel model (with random weights) from the style configuration
  32. >>> model = FlavaImageModel(configuration)
  33. >>> # Accessing the model configuration
  34. >>> configuration = model.config
  35. ```"""
  36. model_type = "flava_image_model"
  37. base_config_key = "image_config"
  38. hidden_size: int = 768
  39. num_hidden_layers: int = 12
  40. num_attention_heads: int = 12
  41. intermediate_size: int = 3072
  42. hidden_act: str = "gelu"
  43. hidden_dropout_prob: float | int = 0.0
  44. attention_probs_dropout_prob: float | int = 0.0
  45. initializer_range: float = 0.02
  46. layer_norm_eps: float = 1e-12
  47. image_size: int | list[int] | tuple[int, int] = 224
  48. patch_size: int | list[int] | tuple[int, int] = 16
  49. num_channels: int = 3
  50. qkv_bias: bool = True
  51. mask_token: bool = True
  52. vocab_size: int = 8192
  53. @auto_docstring(checkpoint="facebook/flava-full")
  54. @strict
  55. class FlavaTextConfig(PreTrainedConfig):
  56. r"""
  57. Example:
  58. ```python
  59. >>> from transformers import FlavaTextConfig, FlavaTextModel
  60. >>> # Initializing a FlavaTextModel with style configuration
  61. >>> configuration = FlavaTextConfig()
  62. >>> # Initializing a FlavaTextModel model (with random weights) from the style configuration
  63. >>> model = FlavaTextModel(configuration)
  64. >>> # Accessing the model configuration
  65. >>> configuration = model.config
  66. ```"""
  67. model_type = "flava_text_model"
  68. base_config_key = "text_config"
  69. vocab_size: int = 30522
  70. type_vocab_size: int = 2
  71. max_position_embeddings: int = 512
  72. hidden_size: int = 768
  73. num_hidden_layers: int = 12
  74. num_attention_heads: int = 12
  75. intermediate_size: int = 3072
  76. hidden_act: str = "gelu"
  77. hidden_dropout_prob: float | int = 0.0
  78. attention_probs_dropout_prob: float | int = 0.0
  79. initializer_range: float = 0.02
  80. layer_norm_eps: float = 1e-12
  81. pad_token_id: int | None = 0
  82. qkv_bias: bool = True
  83. @auto_docstring(checkpoint="facebook/flava-full")
  84. @strict
  85. class FlavaMultimodalConfig(PreTrainedConfig):
  86. r"""
  87. use_cls_token (`bool`, *optional*, defaults to `True`):
  88. Whether to use an extra CLS token for multimodal settings. Usually needed by the FLAVA model.
  89. Example:
  90. ```python
  91. >>> from transformers import FlavaMultimodalConfig, FlavaMultimodalModel
  92. >>> # Initializing a FlavaMultimodalModel with style configuration
  93. >>> configuration = FlavaMultimodalConfig()
  94. >>> # Initializing a FlavaMultimodalModel model (with random weights) from the style configuration
  95. >>> model = FlavaMultimodalModel(configuration)
  96. >>> # Accessing the model configuration
  97. >>> configuration = model.config
  98. ```"""
  99. model_type = "flava_multimodal_model"
  100. base_config_key = "multimodal_config"
  101. hidden_size: int = 768
  102. num_hidden_layers: int = 6
  103. num_attention_heads: int = 12
  104. intermediate_size: int = 3072
  105. hidden_act: str = "gelu"
  106. hidden_dropout_prob: float | int = 0.0
  107. attention_probs_dropout_prob: float | int = 0.0
  108. initializer_range: float = 0.02
  109. layer_norm_eps: float = 1e-12
  110. qkv_bias: bool = True
  111. use_cls_token: bool = True
  112. @auto_docstring(checkpoint="facebook/flava-full")
  113. @strict
  114. class FlavaImageCodebookConfig(PreTrainedConfig):
  115. r"""
  116. num_groups (`int`, *optional*, defaults to 4):
  117. Number of groups to be created. This parameter as of now doesn't affect the model and is used for some
  118. internal calculation and estimations.
  119. num_blocks_per_group (`int`, *optional*, defaults to 2):
  120. Number of conv-based blocks per group.
  121. freeze (`bool`, defaults to `True`):
  122. Whether to freeze the weights of the model.
  123. Example:
  124. ```python
  125. >>> from transformers import FlavaImageCodebookConfig, FlavaImageCodebook
  126. >>> # Initializing a FlavaImageCodebook with style configuration
  127. >>> configuration = FlavaImageCodebookConfig()
  128. >>> # Initializing a FlavaImageCodebook model (with random weights) from the style configuration
  129. >>> model = FlavaImageCodebook(configuration)
  130. >>> # Accessing the model configuration
  131. >>> configuration = model.config
  132. ```
  133. """
  134. num_groups: int = 4
  135. input_channels: int = 3
  136. num_blocks_per_group: int = 2
  137. hidden_size: int = 256
  138. vocab_size: int = 8192
  139. freeze: bool = True
  140. initializer_range: float = 0.02
  141. @auto_docstring(checkpoint="facebook/flava-full")
  142. @strict
  143. class FlavaConfig(PreTrainedConfig):
  144. r"""
  145. image_config (`dict`, *optional*):
  146. Dictionary of configuration options used to initialize [`FlavaImageConfig`].
  147. multimodal_config (`dict`, *optional*):
  148. Dictionary of configuration options used to initialize [`FlavaMultimodalConfig`].
  149. image_codebook_config (`dict`, *optional*):
  150. Dictionary of configuration options used to initialize [`FlavaCodebookConfig`].
  151. init_codebook (`bool`, *optional*, defaults to `True`):
  152. Whether to initialize the codebook
  153. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  154. The initial value of the *logit_scale* parameter. Default is used as per the original FLAVA/CLIP
  155. implementation.
  156. ce_ignore_index (`int`, *optional*, defaults to -100):
  157. Cross entropy index to ignore.
  158. mim_weight (`float`, *optional*, defaults to 1.0):
  159. Weight to be assigned to MIM (Masked Image Modeling) unimodal loss
  160. mlm_weight (`float`, *optional*, defaults to 1.0):
  161. Weight to be assigned to MLM (Masked Language Modeling) unimodal loss
  162. global_contrastive_weight (`float`, *optional*, defaults to 1.0):
  163. Weight to be assigned to global contrastive cross-alignment loss.
  164. itm_weight (`float`, *optional*, defaults to 1.0):
  165. Weight to be assigned to image-text matching multimodal loss.
  166. mmm_image_weight (`float`, *optional*, defaults to 1.0):
  167. Weight to be assigned to MMM loss's image part.
  168. mmm_text_weight (`float`, *optional*, defaults to 1.0):
  169. Weight to be assigned to MMM loss's text part.
  170. global_backprop_contrastive (`bool`, *optional*, defaults to `True`):
  171. Whether to use global backpropgation through all workers in contrastive loss.
  172. skip_unmasked_multimodal_encoder (`bool`, *optional*, defaults to `True`):
  173. Whether to skip running unmasked multimodal encoder whose outputs are not used by FLAVA losses.
  174. return_loss (`bool`, *optional*, defaults to `True`):
  175. Whether to return loss or not
  176. Example:
  177. ```python
  178. >>> from transformers import FlavaConfig, FlavaModel, FlavaForPreTraining
  179. >>> # Initializing a FlavaConfig with style configuration
  180. >>> configuration = FlavaConfig()
  181. >>> # Initializing a FlavaModel and FlavaForPreTraining model (with random weights) from the style configuration
  182. >>> model = FlavaModel(configuration)
  183. >>> model_pre = FlavaForPreTraining(configuration)
  184. >>> # Accessing the model configuration
  185. >>> configuration = model.config
  186. >>> configuration_pre = model_pre.config
  187. ```
  188. """
  189. model_type = "flava"
  190. sub_configs = {
  191. "text_config": FlavaTextConfig,
  192. "image_config": FlavaImageConfig,
  193. "multimodal_config": FlavaMultimodalConfig,
  194. "image_codebook_config": FlavaImageCodebookConfig,
  195. }
  196. image_config: dict[str, Any] | PreTrainedConfig | None = None
  197. text_config: dict[str, Any] | PreTrainedConfig | None = None
  198. multimodal_config: dict[str, Any] | PreTrainedConfig | None = None
  199. image_codebook_config: dict[str, Any] | PreTrainedConfig | None = None
  200. hidden_size: int = 768
  201. layer_norm_eps: float = 1e-12
  202. projection_dim: int = 768
  203. init_codebook: bool = True
  204. logit_scale_init_value: float = 2.6592
  205. initializer_range: float = 0.02
  206. ce_ignore_index: int = -100
  207. mim_weight: float = 1.0
  208. mlm_weight: float = 1.0
  209. global_contrastive_weight: float = 1.0
  210. itm_weight: float = 1.0
  211. mmm_image_weight: float = 1.0
  212. mmm_text_weight: float = 1.0
  213. global_backprop_contrastive: bool = True
  214. skip_unmasked_multimodal_encoder: bool = True
  215. return_loss: bool = True
  216. tie_word_embeddings: bool = True
  217. initializer_factor: float = 1.0
  218. def __post_init__(self, **kwargs):
  219. if self.text_config is None:
  220. text_config = {}
  221. logger.info("`text_config` is `None`. Initializing the `FlavaTextConfig` with default values.")
  222. elif isinstance(self.text_config, FlavaTextConfig):
  223. text_config = self.text_config.to_dict()
  224. else:
  225. text_config = self.text_config
  226. if self.image_config is None:
  227. image_config = {}
  228. logger.info("`image_config` is `None`. initializing the `FlavaImageConfig` with default values.")
  229. elif isinstance(self.image_config, FlavaImageConfig):
  230. image_config = self.image_config.to_dict()
  231. else:
  232. image_config = self.image_config
  233. if self.multimodal_config is None:
  234. multimodal_config = {}
  235. logger.info("`multimodal_config` is `None`. Initializing the `FlavaMultimodalConfig` with default values.")
  236. elif isinstance(self.multimodal_config, FlavaMultimodalConfig):
  237. multimodal_config = self.multimodal_config.to_dict()
  238. else:
  239. multimodal_config = self.multimodal_config
  240. if self.image_codebook_config is None:
  241. image_codebook_config = {}
  242. logger.info(
  243. "`image_codebook_config` is `None`. initializing the `FlavaImageCodebookConfig` with default values."
  244. )
  245. elif isinstance(self.image_codebook_config, FlavaImageCodebookConfig):
  246. image_codebook_config = self.image_codebook_config.to_dict()
  247. else:
  248. image_codebook_config = self.image_codebook_config
  249. # If `_config_dict` exist, we use them for the backward compatibility.
  250. text_config_dict = kwargs.pop("text_config_dict", None)
  251. image_config_dict = kwargs.pop("image_config_dict", None)
  252. multimodal_config_dict = kwargs.pop("multimodal_config_dict", None)
  253. image_codebook_config_dict = kwargs.pop("image_codebook_config_dict", None)
  254. # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
  255. # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
  256. # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
  257. if text_config_dict is not None:
  258. # This is the complete result when using `text_config_dict`.
  259. _text_config_dict = FlavaTextConfig(**text_config_dict).to_dict()
  260. # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
  261. for key, value in _text_config_dict.items():
  262. if key in text_config and value != text_config[key] and key != "transformers_version":
  263. # If specified in `text_config_dict`
  264. if key in text_config_dict:
  265. message = (
  266. f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
  267. f'The value `text_config_dict["{key}"]` will be used instead.'
  268. )
  269. # If inferred from default argument values (just to be super careful)
  270. else:
  271. message = (
  272. f"`text_config_dict` is provided which will be used to initialize `FlavaTextConfig`. The "
  273. f'value `text_config["{key}"]` will be overridden.'
  274. )
  275. logger.info(message)
  276. # Update all values in `text_config` with the ones in `_text_config_dict`.
  277. text_config.update(_text_config_dict)
  278. if image_config_dict is not None:
  279. # This is the complete result when using `image_config_dict`.
  280. _image_config_dict = FlavaImageConfig(**image_config_dict).to_dict()
  281. # convert keys to string instead of integer
  282. if "id2label" in _image_config_dict:
  283. _image_config_dict["id2label"] = {
  284. str(key): value for key, value in _image_config_dict["id2label"].items()
  285. }
  286. # Give a warning if the values exist in both `_image_config_dict` and `image_config` but being different.
  287. for key, value in _image_config_dict.items():
  288. if key in image_config and value != image_config[key] and key != "transformers_version":
  289. # If specified in `image_config_dict`
  290. if key in image_config_dict:
  291. message = (
  292. f"`{key}` is found in both `image_config_dict` and `image_config` but with different "
  293. f'values. The value `image_config_dict["{key}"]` will be used instead.'
  294. )
  295. # If inferred from default argument values (just to be super careful)
  296. else:
  297. message = (
  298. f"`image_config_dict` is provided which will be used to initialize `FlavaImageConfig`. "
  299. f'The value `image_config["{key}"]` will be overridden.'
  300. )
  301. logger.info(message)
  302. # Update all values in `image_config` with the ones in `_image_config_dict`.
  303. image_config.update(_image_config_dict)
  304. if multimodal_config_dict is not None:
  305. # This is the complete result when using `multimodal_config_dict`.
  306. _multimodal_config_dict = FlavaMultimodalConfig(**multimodal_config_dict).to_dict()
  307. # Give a warning if the values exist in both `_multimodal_config_dict` and `multimodal_config` but being
  308. # different.
  309. for key, value in _multimodal_config_dict.items():
  310. if key in multimodal_config and value != multimodal_config[key] and key != "transformers_version":
  311. # If specified in `multimodal_config_dict`
  312. if key in multimodal_config_dict:
  313. message = (
  314. f"`{key}` is found in both `multimodal_config_dict` and `multimodal_config` but with "
  315. f'different values. The value `multimodal_config_dict["{key}"]` will be used instead.'
  316. )
  317. # If inferred from default argument values (just to be super careful)
  318. else:
  319. message = (
  320. f"`multimodal_config_dict` is provided which will be used to initialize "
  321. f'`FlavaMultimodalConfig`. The value `multimodal_config["{key}"]` will be overridden.'
  322. )
  323. logger.info(message)
  324. # Update all values in `multimodal_config` with the ones in `_multimodal_config_dict`.
  325. multimodal_config.update(_multimodal_config_dict)
  326. if image_codebook_config_dict is not None:
  327. # This is the complete result when using `image_codebook_config_dict`.
  328. _image_codebook_config_dict = FlavaImageCodebookConfig(**image_codebook_config_dict).to_dict()
  329. # Give a warning if the values exist in both `_image_codebook_config_dict` and `image_codebook_config` but
  330. # being different.
  331. for key, value in _image_codebook_config_dict.items():
  332. if (
  333. key in image_codebook_config
  334. and value != image_codebook_config[key]
  335. and key != "transformers_version"
  336. ):
  337. # If specified in `image_codebook_config_dict`
  338. if key in image_codebook_config_dict:
  339. message = (
  340. f"`{key}` is found in both `image_codebook_config_dict` and `image_codebook_config` but "
  341. f'with different values. The value `image_codebook_config_dict["{key}"]` will be used '
  342. "instead."
  343. )
  344. # If inferred from default argument values (just to be super careful)
  345. else:
  346. message = (
  347. f"`image_codebook_config_dict` is provided which will be used to initialize "
  348. f'`FlavaImageCodebookConfig`. The value `image_codebook_config["{key}"]` will be overridden.'
  349. )
  350. logger.info(message)
  351. # Update all values in `image_codebook_config` with the ones in `_image_codebook_config_dict`.
  352. image_codebook_config.update(_image_codebook_config_dict)
  353. # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
  354. self.text_config = FlavaTextConfig(**text_config)
  355. self.image_config = FlavaImageConfig(**image_config)
  356. self.multimodal_config = FlavaMultimodalConfig(**multimodal_config)
  357. self.image_codebook_config = FlavaImageCodebookConfig(**image_codebook_config)
  358. super().__post_init__(**kwargs)
  359. __all__ = ["FlavaConfig", "FlavaImageCodebookConfig", "FlavaImageConfig", "FlavaMultimodalConfig", "FlavaTextConfig"]