configuration_blip.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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. """Blip model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class BlipTextConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`BlipTextModel`]. It is used to instantiate a BLIP
  22. text model according to the specified arguments, defining the model architecture. Instantiating a configuration
  23. with the defaults will yield a similar configuration to that of the `BlipText` used by the [base
  24. architectures](https://huggingface.co/Salesforce/blip-vqa-base).
  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 30524):
  29. Vocabulary size of the `Blip` text model. Defines the number of different tokens that can be represented by
  30. the `inputs_ids` passed when calling [`BlipModel`].
  31. hidden_size (`int`, *optional*, defaults to 768):
  32. Dimensionality of the encoder layers and the pooler layer.
  33. encoder_hidden_size (`int`, *optional*, defaults to 768):
  34. Dimensionality of the encoder layers from the vision model.
  35. intermediate_size (`int`, *optional*, defaults to 3072):
  36. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  37. num_hidden_layers (`int`, *optional*, defaults to 12):
  38. Number of hidden layers in the Transformer encoder.
  39. num_attention_heads (`int`, *optional*, defaults to 8):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. max_position_embeddings (`int`, *optional*, defaults to 512):
  42. The maximum sequence length that this model might ever be used with. Typically set this to something large
  43. just in case (e.g., 512 or 1024 or 2048).
  44. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  45. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  46. `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
  47. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  48. The epsilon used by the layer normalization layers.
  49. hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
  50. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  51. attention_dropout (`float`, *optional*, defaults to 0.0):
  52. The dropout ratio for the attention probabilities.
  53. initializer_range (`float`, *optional*, defaults to 0.02):
  54. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  55. bos_token_id (`int`, *optional*, defaults to 30522):
  56. The id of the `beginning-of-sequence` token.
  57. eos_token_id (`int`, *optional*, defaults to 2):
  58. The id of the `end-of-sequence` token.
  59. pad_token_id (`int`, *optional*, defaults to 0):
  60. The id of the `padding` token.
  61. sep_token_id (`int`, *optional*, defaults to 102):
  62. The id of the `separator` token.
  63. is_decoder (`bool`, *optional*, defaults to `True`):
  64. Whether the model is used as a decoder.
  65. use_cache (`bool`, *optional*, defaults to `True`):
  66. Whether or not the model should return the last key/values attentions (not used by all models).
  67. label_smoothing (float, *optional*):
  68. A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
  69. become a mixture of the original ground truth and a uniform distribution as described in
  70. `Rethinking the Inception Architecture for Computer Vision <https://huggingface.co/papers/1512.00567>`__. Default: :math:`0.0`.
  71. Example:
  72. ```python
  73. >>> from transformers import BlipTextConfig, BlipTextModel
  74. >>> # Initializing a BlipTextConfig with Salesforce/blip-vqa-base style configuration
  75. >>> configuration = BlipTextConfig()
  76. >>> # Initializing a BlipTextModel (with random weights) from the Salesforce/blip-vqa-base style configuration
  77. >>> model = BlipTextModel(configuration)
  78. >>> # Accessing the model configuration
  79. >>> configuration = model.config
  80. ```"""
  81. model_type = "blip_text_model"
  82. base_config_key = "text_config"
  83. def __init__(
  84. self,
  85. vocab_size=30524,
  86. hidden_size=768,
  87. encoder_hidden_size=768,
  88. intermediate_size=3072,
  89. projection_dim=768,
  90. num_hidden_layers=12,
  91. num_attention_heads=8,
  92. max_position_embeddings=512,
  93. hidden_act="gelu",
  94. layer_norm_eps=1e-12,
  95. hidden_dropout_prob=0.0,
  96. attention_probs_dropout_prob=0.0,
  97. initializer_range=0.02,
  98. bos_token_id=30522,
  99. eos_token_id=2,
  100. pad_token_id=0,
  101. sep_token_id=102,
  102. is_decoder=True,
  103. use_cache=True,
  104. label_smoothing=0.0,
  105. **kwargs,
  106. ):
  107. super().__init__(
  108. pad_token_id=pad_token_id,
  109. bos_token_id=bos_token_id,
  110. eos_token_id=eos_token_id,
  111. sep_token_id=sep_token_id,
  112. **kwargs,
  113. )
  114. self.vocab_size = vocab_size
  115. self.hidden_size = hidden_size
  116. self.encoder_hidden_size = encoder_hidden_size
  117. self.intermediate_size = intermediate_size
  118. self.projection_dim = projection_dim
  119. self.hidden_dropout_prob = hidden_dropout_prob
  120. self.num_hidden_layers = num_hidden_layers
  121. self.num_attention_heads = num_attention_heads
  122. self.max_position_embeddings = max_position_embeddings
  123. self.layer_norm_eps = layer_norm_eps
  124. self.hidden_act = hidden_act
  125. self.initializer_range = initializer_range
  126. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  127. self.is_decoder = is_decoder
  128. self.use_cache = use_cache
  129. self.label_smoothing = label_smoothing
  130. class BlipVisionConfig(PretrainedConfig):
  131. r"""
  132. This is the configuration class to store the configuration of a [`BlipVisionModel`]. It is used to instantiate a
  133. BLIP vision model according to the specified arguments, defining the model architecture. Instantiating a
  134. configuration defaults will yield a similar configuration to that of the Blip-base
  135. [Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
  136. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  137. documentation from [`PretrainedConfig`] for more information.
  138. Args:
  139. hidden_size (`int`, *optional*, defaults to 768):
  140. Dimensionality of the encoder layers and the pooler layer.
  141. intermediate_size (`int`, *optional*, defaults to 3072):
  142. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  143. num_hidden_layers (`int`, *optional*, defaults to 12):
  144. Number of hidden layers in the Transformer encoder.
  145. num_attention_heads (`int`, *optional*, defaults to 12):
  146. Number of attention heads for each attention layer in the Transformer encoder.
  147. image_size (`int`, *optional*, defaults to 384):
  148. The size (resolution) of each image.
  149. patch_size (`int`, *optional*, defaults to 16):
  150. The size (resolution) of each patch.
  151. hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
  152. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  153. `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
  154. layer_norm_eps (`float`, *optional*, defaults to 1e-5):
  155. The epsilon used by the layer normalization layers.
  156. attention_dropout (`float`, *optional*, defaults to 0.0):
  157. The dropout ratio for the attention probabilities.
  158. initializer_range (`float`, *optional*, defaults to 1e-10):
  159. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  160. Example:
  161. ```python
  162. >>> from transformers import BlipVisionConfig, BlipVisionModel
  163. >>> # Initializing a BlipVisionConfig with Salesforce/blip-vqa-base style configuration
  164. >>> configuration = BlipVisionConfig()
  165. >>> # Initializing a BlipVisionModel (with random weights) from the Salesforce/blip-vqa-base style configuration
  166. >>> model = BlipVisionModel(configuration)
  167. >>> # Accessing the model configuration
  168. >>> configuration = model.config
  169. ```"""
  170. model_type = "blip_vision_model"
  171. base_config_key = "vision_config"
  172. def __init__(
  173. self,
  174. hidden_size=768,
  175. intermediate_size=3072,
  176. projection_dim=512,
  177. num_hidden_layers=12,
  178. num_attention_heads=12,
  179. image_size=384,
  180. patch_size=16,
  181. hidden_act="gelu",
  182. layer_norm_eps=1e-5,
  183. attention_dropout=0.0,
  184. initializer_range=1e-10,
  185. **kwargs,
  186. ):
  187. super().__init__(**kwargs)
  188. self.hidden_size = hidden_size
  189. self.intermediate_size = intermediate_size
  190. self.projection_dim = projection_dim
  191. self.num_hidden_layers = num_hidden_layers
  192. self.num_attention_heads = num_attention_heads
  193. self.patch_size = patch_size
  194. self.image_size = image_size
  195. self.initializer_range = initializer_range
  196. self.attention_dropout = attention_dropout
  197. self.layer_norm_eps = layer_norm_eps
  198. self.hidden_act = hidden_act
  199. class BlipConfig(PretrainedConfig):
  200. r"""
  201. [`BlipConfig`] is the configuration class to store the configuration of a [`BlipModel`]. It is used to instantiate
  202. a BLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating
  203. a configuration with the defaults will yield a similar configuration to that of the BLIP-base
  204. [Salesforce/blip-vqa-base](https://huggingface.co/Salesforce/blip-vqa-base) architecture.
  205. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  206. documentation from [`PretrainedConfig`] for more information.
  207. Args:
  208. text_config (`dict`, *optional*):
  209. Dictionary of configuration options used to initialize [`BlipTextConfig`].
  210. vision_config (`dict`, *optional*):
  211. Dictionary of configuration options used to initialize [`BlipVisionConfig`].
  212. projection_dim (`int`, *optional*, defaults to 512):
  213. Dimensionality of text and vision projection layers.
  214. logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
  215. The initial value of the *logit_scale* parameter. Default is used as per the original BLIP implementation.
  216. image_text_hidden_size (`int`, *optional*, defaults to 256):
  217. Dimensionality of the hidden state of the image-text fusion layer.
  218. label_smoothing (float, optional, *optional*, defaults to 0.0):
  219. A float in [0.0, 1.0]. Specifies the amount of smoothing when computing the loss, where 0.0 means no smoothing. The targets
  220. become a mixture of the original ground truth and a uniform distribution as described in
  221. `Rethinking the Inception Architecture for Computer Vision <https://huggingface.co/papers/1512.00567>`__. Default: :math:`0.0`.
  222. kwargs (*optional*):
  223. Dictionary of keyword arguments.
  224. Example:
  225. ```python
  226. >>> from transformers import BlipConfig, BlipModel
  227. >>> # Initializing a BlipConfig with Salesforce/blip-vqa-base style configuration
  228. >>> configuration = BlipConfig()
  229. >>> # Initializing a BlipPModel (with random weights) from the Salesforce/blip-vqa-base style configuration
  230. >>> model = BlipModel(configuration)
  231. >>> # Accessing the model configuration
  232. >>> configuration = model.config
  233. >>> # We can also initialize a BlipConfig from a BlipTextConfig and a BlipVisionConfig
  234. >>> # Initializing a BLIPText and BLIPVision configuration
  235. >>> config_text = BlipTextConfig()
  236. >>> config_vision = BlipVisionConfig()
  237. >>> config = BlipConfig.from_text_vision_configs(config_text, config_vision)
  238. ```"""
  239. model_type = "blip"
  240. sub_configs = {"text_config": BlipTextConfig, "vision_config": BlipVisionConfig}
  241. def __init__(
  242. self,
  243. text_config=None,
  244. vision_config=None,
  245. projection_dim=512,
  246. logit_scale_init_value=2.6592,
  247. image_text_hidden_size=256,
  248. label_smoothing=0.0,
  249. **kwargs,
  250. ):
  251. super().__init__(**kwargs)
  252. if text_config is None:
  253. text_config = {}
  254. logger.info("`text_config` is `None`. Initializing the `BlipTextConfig` with default values.")
  255. if vision_config is None:
  256. vision_config = {}
  257. logger.info("`vision_config` is `None`. Initializing the `BlipVisionConfig` with default values.")
  258. self.text_config = BlipTextConfig(**text_config)
  259. self.vision_config = BlipVisionConfig(**vision_config)
  260. self.text_config.encoder_hidden_size = self.vision_config.hidden_size
  261. self.projection_dim = projection_dim
  262. self.logit_scale_init_value = logit_scale_init_value
  263. self.initializer_factor = 1.0
  264. self.initializer_range = 0.02
  265. self.image_text_hidden_size = image_text_hidden_size
  266. self.label_smoothing = label_smoothing
  267. __all__ = ["BlipConfig", "BlipTextConfig", "BlipVisionConfig"]