configuration_bridgetower.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # coding=utf-8
  2. # Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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. """BridgeTower model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class BridgeTowerVisionConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the vision configuration of a [`BridgeTowerModel`]. Instantiating a
  22. configuration with the defaults will yield a similar configuration to that of the bridgetower-base
  23. [BridgeTower/bridgetower-base](https://huggingface.co/BridgeTower/bridgetower-base/) architecture.
  24. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  25. documentation from [`PretrainedConfig`] for more information.
  26. Args:
  27. hidden_size (`int`, *optional*, defaults to 768):
  28. Dimensionality of the encoder layers and the pooler layer.
  29. num_hidden_layers (`int`, *optional*, defaults to 12):
  30. Number of hidden layers in visual encoder model.
  31. patch_size (`int`, *optional*, defaults to 16):
  32. The size (resolution) of each patch.
  33. image_size (`int`, *optional*, defaults to 288):
  34. The size (resolution) of each image.
  35. initializer_factor (`float`, *optional*, defaults to 1):
  36. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  37. testing).
  38. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  39. The epsilon used by the layer normalization layers.
  40. stop_gradient (`bool`, *optional*, defaults to `False`):
  41. Whether to stop gradient for training.
  42. share_layernorm (`bool`, *optional*, defaults to `True`):
  43. Whether LayerNorm layers are shared.
  44. remove_last_layer (`bool`, *optional*, defaults to `False`):
  45. Whether to remove the last layer from the vision encoder.
  46. Example:
  47. ```python
  48. >>> from transformers import BridgeTowerVisionConfig
  49. >>> # Initializing a BridgeTower BridgeTower/bridgetower-base style configuration for the vision model
  50. >>> configuration = BridgeTowerVisionConfig()
  51. >>> # Accessing the configuration
  52. >>> configuration
  53. ```"""
  54. model_type = "bridgetower_vision_model"
  55. base_config_key = "vision_config"
  56. def __init__(
  57. self,
  58. hidden_size=768,
  59. num_hidden_layers=12,
  60. num_channels=3,
  61. patch_size=16,
  62. image_size=288,
  63. initializer_factor=1,
  64. layer_norm_eps=1e-05,
  65. stop_gradient=False,
  66. share_layernorm=True,
  67. remove_last_layer=False,
  68. **kwargs,
  69. ):
  70. super().__init__(**kwargs)
  71. self.hidden_size = hidden_size
  72. self.num_hidden_layers = num_hidden_layers
  73. self.num_channels = num_channels
  74. self.patch_size = patch_size
  75. self.image_size = image_size
  76. self.initializer_factor = initializer_factor
  77. self.layer_norm_eps = layer_norm_eps
  78. self.stop_gradient = stop_gradient
  79. self.share_layernorm = share_layernorm
  80. self.remove_last_layer = remove_last_layer
  81. class BridgeTowerTextConfig(PretrainedConfig):
  82. r"""
  83. This is the configuration class to store the text configuration of a [`BridgeTowerModel`]. The default values here
  84. are copied from RoBERTa. Instantiating a configuration with the defaults will yield a similar configuration to that
  85. of the bridgetower-base [BridegTower/bridgetower-base](https://huggingface.co/BridgeTower/bridgetower-base/)
  86. architecture.
  87. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  88. documentation from [`PretrainedConfig`] for more information.
  89. Args:
  90. vocab_size (`int`, *optional*, defaults to 50265):
  91. Vocabulary size of the text part of the model. Defines the number of different tokens that can be
  92. represented by the `inputs_ids` passed when calling [`BridgeTowerModel`].
  93. hidden_size (`int`, *optional*, defaults to 768):
  94. Dimensionality of the encoder layers and the pooler layer.
  95. num_hidden_layers (`int`, *optional*, defaults to 12):
  96. Number of hidden layers in the Transformer encoder.
  97. num_attention_heads (`int`, *optional*, defaults to 12):
  98. Number of attention heads for each attention layer in the Transformer encoder.
  99. intermediate_size (`int`, *optional*, defaults to 3072):
  100. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  101. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  102. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  103. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  104. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  105. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  106. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  107. The dropout ratio for the attention probabilities.
  108. max_position_embeddings (`int`, *optional*, defaults to 514):
  109. The maximum sequence length that this model might ever be used with. Typically set this to something large
  110. just in case (e.g., 512 or 1024 or 2048).
  111. type_vocab_size (`int`, *optional*, defaults to 2):
  112. The vocabulary size of the `token_type_ids`.
  113. initializer_factor (`float`, *optional*, defaults to 1):
  114. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  115. testing).
  116. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  117. The epsilon used by the layer normalization layers.
  118. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  119. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  120. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  121. [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
  122. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  123. with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
  124. is_decoder (`bool`, *optional*, defaults to `False`):
  125. Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
  126. use_cache (`bool`, *optional*, defaults to `True`):
  127. Whether or not the model should return the last key/values attentions (not used by all models). Only
  128. relevant if `config.is_decoder=True`.
  129. Example:
  130. ```python
  131. >>> from transformers import BridgeTowerTextConfig
  132. >>> # Initializing a BridgeTower BridgeTower/bridgetower-base style configuration for the text model
  133. >>> configuration = BridgeTowerTextConfig()
  134. >>> # Accessing the configuration
  135. >>> configuration
  136. ```"""
  137. model_type = "bridgetower_text_model"
  138. base_config_key = "text_config"
  139. def __init__(
  140. self,
  141. vocab_size=50265,
  142. hidden_size=768,
  143. num_hidden_layers=12,
  144. num_attention_heads=12,
  145. initializer_factor=1,
  146. intermediate_size=3072,
  147. hidden_act="gelu",
  148. hidden_dropout_prob=0.1,
  149. attention_probs_dropout_prob=0.1,
  150. max_position_embeddings=514,
  151. type_vocab_size=1,
  152. layer_norm_eps=1e-05,
  153. pad_token_id=1,
  154. bos_token_id=0,
  155. eos_token_id=2,
  156. position_embedding_type="absolute",
  157. use_cache=True,
  158. **kwargs,
  159. ):
  160. super().__init__(**kwargs)
  161. self.vocab_size = vocab_size
  162. self.hidden_size = hidden_size
  163. self.num_hidden_layers = num_hidden_layers
  164. self.num_attention_heads = num_attention_heads
  165. self.hidden_act = hidden_act
  166. self.initializer_factor = initializer_factor
  167. self.intermediate_size = intermediate_size
  168. self.hidden_dropout_prob = hidden_dropout_prob
  169. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  170. self.max_position_embeddings = max_position_embeddings
  171. self.type_vocab_size = type_vocab_size
  172. self.layer_norm_eps = layer_norm_eps
  173. self.position_embedding_type = position_embedding_type
  174. self.use_cache = use_cache
  175. self.pad_token_id = pad_token_id
  176. self.bos_token_id = bos_token_id
  177. self.eos_token_id = eos_token_id
  178. class BridgeTowerConfig(PretrainedConfig):
  179. r"""
  180. This is the configuration class to store the configuration of a [`BridgeTowerModel`]. It is used to instantiate a
  181. BridgeTower model according to the specified arguments, defining the model architecture. Instantiating a
  182. configuration with the defaults will yield a similar configuration to that of the bridgetower-base
  183. [BridgeTower/bridgetower-base](https://huggingface.co/BridgeTower/bridgetower-base/) architecture.
  184. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  185. documentation from [`PretrainedConfig`] for more information.
  186. Args:
  187. share_cross_modal_transformer_layers (`bool`, *optional*, defaults to `True`):
  188. Whether cross modal transformer layers are shared.
  189. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  190. The non-linear activation function (function or string) in the encoder and pooler.
  191. hidden_size (`int`, *optional*, defaults to 768):
  192. Dimensionality of the encoder layers and the pooler layer.
  193. initializer_factor (`float`, *optional*, defaults to 1):
  194. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  195. testing).
  196. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  197. The epsilon used by the layer normalization layers.
  198. share_link_tower_layers (`bool`, *optional*, defaults to `False`):
  199. Whether the bride/link tower layers are shared.
  200. link_tower_type (`str`, *optional*, defaults to `"add"`):
  201. Type of the bridge/link layer.
  202. num_attention_heads (`int`, *optional*, defaults to 12):
  203. Number of attention heads for each attention layer in the Transformer encoder.
  204. num_hidden_layers (`int`, *optional*, defaults to 6):
  205. Number of hidden layers in the Transformer encoder.
  206. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  207. Whether to tie input and output embeddings.
  208. init_layernorm_from_vision_encoder (`bool`, *optional*, defaults to `False`):
  209. Whether to init LayerNorm from the vision encoder.
  210. text_config (`dict`, *optional*):
  211. Dictionary of configuration options used to initialize [`BridgeTowerTextConfig`].
  212. vision_config (`dict`, *optional*):
  213. Dictionary of configuration options used to initialize [`BridgeTowerVisionConfig`].
  214. Example:
  215. ```python
  216. >>> from transformers import BridgeTowerModel, BridgeTowerConfig
  217. >>> # Initializing a BridgeTower BridgeTower/bridgetower-base style configuration
  218. >>> configuration = BridgeTowerConfig()
  219. >>> # Initializing a model from the BridgeTower/bridgetower-base style configuration
  220. >>> model = BridgeTowerModel(configuration)
  221. >>> # Accessing the model configuration
  222. >>> configuration = model.config
  223. ```"""
  224. model_type = "bridgetower"
  225. sub_configs = {"text_config": BridgeTowerTextConfig, "vision_config": BridgeTowerVisionConfig}
  226. def __init__(
  227. self,
  228. share_cross_modal_transformer_layers=True,
  229. hidden_act="gelu",
  230. hidden_size=768,
  231. initializer_factor=1,
  232. layer_norm_eps=1e-05,
  233. share_link_tower_layers=False,
  234. link_tower_type="add",
  235. num_attention_heads=12,
  236. num_hidden_layers=6,
  237. tie_word_embeddings=False,
  238. init_layernorm_from_vision_encoder=False,
  239. text_config=None,
  240. vision_config=None,
  241. **kwargs,
  242. ):
  243. # TODO: remove this once the Hub files are updated.
  244. _ = kwargs.pop("text_config_dict", None)
  245. _ = kwargs.pop("vision_config_dict", None)
  246. super().__init__(**kwargs)
  247. self.share_cross_modal_transformer_layers = share_cross_modal_transformer_layers
  248. self.hidden_act = hidden_act
  249. self.hidden_size = hidden_size
  250. self.initializer_factor = initializer_factor
  251. self.layer_norm_eps = layer_norm_eps
  252. self.share_link_tower_layers = share_link_tower_layers
  253. self.link_tower_type = link_tower_type
  254. self.num_attention_heads = num_attention_heads
  255. self.num_hidden_layers = num_hidden_layers
  256. self.tie_word_embeddings = tie_word_embeddings
  257. self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder
  258. if text_config is None:
  259. text_config = {}
  260. logger.info("`text_config` is `None`. Initializing the `BridgeTowerTextConfig` with default values.")
  261. if vision_config is None:
  262. vision_config = {}
  263. logger.info("`vision_config` is `None`. Initializing the `BridgeTowerVisionConfig` with default values.")
  264. self.text_config = BridgeTowerTextConfig(**text_config)
  265. self.vision_config = BridgeTowerVisionConfig(**vision_config)
  266. __all__ = ["BridgeTowerConfig", "BridgeTowerTextConfig", "BridgeTowerVisionConfig"]