configuration_instructblip.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. # coding=utf-8
  2. # Copyright 2023 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. """InstructBLIP model configuration"""
  16. import os
  17. from typing import Union
  18. from ...configuration_utils import PretrainedConfig
  19. from ...models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
  20. from ...utils import logging
  21. from ..auto import CONFIG_MAPPING
  22. logger = logging.get_logger(__name__)
  23. class InstructBlipVisionConfig(PretrainedConfig):
  24. r"""
  25. This is the configuration class to store the configuration of a [`InstructBlipVisionModel`]. It is used to
  26. instantiate a InstructBLIP vision encoder according to the specified arguments, defining the model architecture.
  27. Instantiating a configuration defaults will yield a similar configuration to that of the InstructBLIP
  28. [Salesforce/instruct-blip-flan-t5](https://huggingface.co/Salesforce/instruct-blip-flan-t5) architecture.
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information.
  31. Args:
  32. hidden_size (`int`, *optional*, defaults to 1408):
  33. Dimensionality of the encoder layers and the pooler layer.
  34. intermediate_size (`int`, *optional*, defaults to 6144):
  35. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  36. num_hidden_layers (`int`, *optional*, defaults to 39):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 16):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. image_size (`int`, *optional*, defaults to 224):
  41. The size (resolution) of each image.
  42. patch_size (`int`, *optional*, defaults to 14):
  43. The size (resolution) of each patch.
  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. to 1e-5): The epsilon used by the layer
  47. normalization layers.
  48. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  49. The epsilon used by the layer normalization layers.
  50. attention_dropout (`float`, *optional*, defaults to 0.0):
  51. The dropout ratio for the attention probabilities.
  52. initializer_range (`float`, *optional*, defaults to 1e-10):
  53. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  54. qkv_bias (`bool`, *optional*, defaults to `True`):
  55. Whether to add a bias to the queries and values in the self-attention layers.
  56. Example:
  57. ```python
  58. >>> from transformers import InstructBlipVisionConfig, InstructBlipVisionModel
  59. >>> # Initializing a InstructBlipVisionConfig with Salesforce/instruct-blip-flan-t5 style configuration
  60. >>> configuration = InstructBlipVisionConfig()
  61. >>> # Initializing a InstructBlipVisionModel (with random weights) from the Salesforce/instruct-blip-flan-t5 style configuration
  62. >>> model = InstructBlipVisionModel(configuration)
  63. >>> # Accessing the model configuration
  64. >>> configuration = model.config
  65. ```"""
  66. model_type = "instructblip_vision_model"
  67. def __init__(
  68. self,
  69. hidden_size=1408,
  70. intermediate_size=6144,
  71. num_hidden_layers=39,
  72. num_attention_heads=16,
  73. image_size=224,
  74. patch_size=14,
  75. hidden_act="gelu",
  76. layer_norm_eps=1e-6,
  77. attention_dropout=0.0,
  78. initializer_range=1e-10,
  79. qkv_bias=True,
  80. **kwargs,
  81. ):
  82. super().__init__(**kwargs)
  83. self.hidden_size = hidden_size
  84. self.intermediate_size = intermediate_size
  85. self.num_hidden_layers = num_hidden_layers
  86. self.num_attention_heads = num_attention_heads
  87. self.patch_size = patch_size
  88. self.image_size = image_size
  89. self.initializer_range = initializer_range
  90. self.attention_dropout = attention_dropout
  91. self.layer_norm_eps = layer_norm_eps
  92. self.hidden_act = hidden_act
  93. self.qkv_bias = qkv_bias
  94. @classmethod
  95. def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
  96. cls._set_token_in_kwargs(kwargs)
  97. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  98. # get the vision config dict if we are loading from InstructBlipConfig
  99. if config_dict.get("model_type") == "instructblip":
  100. config_dict = config_dict["vision_config"]
  101. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  102. logger.warning(
  103. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  104. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  105. )
  106. return cls.from_dict(config_dict, **kwargs)
  107. class InstructBlipQFormerConfig(PretrainedConfig):
  108. r"""
  109. This is the configuration class to store the configuration of a [`InstructBlipQFormerModel`]. It is used to
  110. instantiate a InstructBLIP Querying Transformer (Q-Former) model according to the specified arguments, defining the
  111. model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
  112. the InstructBLIP [Salesforce/instruct-blip-flan-t5](https://huggingface.co/Salesforce/instruct-blip-flan-t5)
  113. architecture. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs.
  114. Read the documentation from [`PretrainedConfig`] for more information.
  115. Note that [`InstructBlipQFormerModel`] is very similar to [`BertLMHeadModel`] with interleaved cross-attention.
  116. Args:
  117. vocab_size (`int`, *optional*, defaults to 30522):
  118. Vocabulary size of the Q-Former model. Defines the number of different tokens that can be represented by
  119. the `inputs_ids` passed when calling the model.
  120. hidden_size (`int`, *optional*, defaults to 768):
  121. Dimensionality of the encoder layers and the pooler layer.
  122. num_hidden_layers (`int`, *optional*, defaults to 12):
  123. Number of hidden layers in the Transformer encoder.
  124. num_attention_heads (`int`, *optional*, defaults to 12):
  125. Number of attention heads for each attention layer in the Transformer encoder.
  126. intermediate_size (`int`, *optional*, defaults to 3072):
  127. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  128. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  129. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  130. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  131. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  132. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  133. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  134. The dropout ratio for the attention probabilities.
  135. max_position_embeddings (`int`, *optional*, defaults to 512):
  136. The maximum sequence length that this model might ever be used with. Typically set this to something large
  137. just in case (e.g., 512 or 1024 or 2048).
  138. initializer_range (`float`, *optional*, defaults to 0.02):
  139. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  140. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  141. The epsilon used by the layer normalization layers.
  142. pad_token_id (`int`, *optional*, defaults to 0):
  143. Token id used for padding sequences.
  144. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  145. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  146. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  147. [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
  148. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  149. with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
  150. cross_attention_frequency (`int`, *optional*, defaults to 2):
  151. The frequency of adding cross-attention to the Transformer layers.
  152. encoder_hidden_size (`int`, *optional*, defaults to 1408):
  153. The hidden size of the hidden states for cross-attention.
  154. Examples:
  155. ```python
  156. >>> from transformers import InstructBlipQFormerConfig, InstructBlipQFormerModel
  157. >>> # Initializing a InstructBLIP Salesforce/instruct-blip-flan-t5 style configuration
  158. >>> configuration = InstructBlipQFormerConfig()
  159. >>> # Initializing a model (with random weights) from the Salesforce/instruct-blip-flan-t5 style configuration
  160. >>> model = InstructBlipQFormerModel(configuration)
  161. >>> # Accessing the model configuration
  162. >>> configuration = model.config
  163. ```"""
  164. model_type = "instructblip_qformer"
  165. def __init__(
  166. self,
  167. vocab_size=30522,
  168. hidden_size=768,
  169. num_hidden_layers=12,
  170. num_attention_heads=12,
  171. intermediate_size=3072,
  172. hidden_act="gelu",
  173. hidden_dropout_prob=0.1,
  174. attention_probs_dropout_prob=0.1,
  175. max_position_embeddings=512,
  176. initializer_range=0.02,
  177. layer_norm_eps=1e-12,
  178. pad_token_id=0,
  179. position_embedding_type="absolute",
  180. cross_attention_frequency=2,
  181. encoder_hidden_size=1408,
  182. **kwargs,
  183. ):
  184. super().__init__(pad_token_id=pad_token_id, **kwargs)
  185. self.vocab_size = vocab_size
  186. self.hidden_size = hidden_size
  187. self.num_hidden_layers = num_hidden_layers
  188. self.num_attention_heads = num_attention_heads
  189. self.hidden_act = hidden_act
  190. self.intermediate_size = intermediate_size
  191. self.hidden_dropout_prob = hidden_dropout_prob
  192. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  193. self.max_position_embeddings = max_position_embeddings
  194. self.initializer_range = initializer_range
  195. self.layer_norm_eps = layer_norm_eps
  196. self.position_embedding_type = position_embedding_type
  197. self.cross_attention_frequency = cross_attention_frequency
  198. self.encoder_hidden_size = encoder_hidden_size
  199. @classmethod
  200. def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
  201. cls._set_token_in_kwargs(kwargs)
  202. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  203. # get the qformer config dict if we are loading from InstructBlipConfig
  204. if config_dict.get("model_type") == "instructblip":
  205. config_dict = config_dict["qformer_config"]
  206. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  207. logger.warning(
  208. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  209. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  210. )
  211. return cls.from_dict(config_dict, **kwargs)
  212. class InstructBlipConfig(PretrainedConfig):
  213. r"""
  214. [`InstructBlipConfig`] is the configuration class to store the configuration of a
  215. [`InstructBlipForConditionalGeneration`]. It is used to instantiate a InstructBLIP model according to the specified
  216. arguments, defining the vision model, Q-Former model and language model configs. Instantiating a configuration with
  217. the defaults will yield a similar configuration to that of the InstructBLIP
  218. [Salesforce/instruct-blip-flan-t5](https://huggingface.co/Salesforce/instruct-blip-flan-t5) architecture.
  219. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  220. documentation from [`PretrainedConfig`] for more information.
  221. Args:
  222. vision_config (`dict`, *optional*):
  223. Dictionary of configuration options used to initialize [`InstructBlipVisionConfig`].
  224. qformer_config (`dict`, *optional*):
  225. Dictionary of configuration options used to initialize [`InstructBlipQFormerConfig`].
  226. text_config (`dict`, *optional*):
  227. Dictionary of configuration options used to initialize any [`PretrainedConfig`].
  228. num_query_tokens (`int`, *optional*, defaults to 32):
  229. The number of query tokens passed through the Transformer.
  230. image_token_index (`int`, *optional*):
  231. Token index of special image token.
  232. kwargs (*optional*):
  233. Dictionary of keyword arguments.
  234. Example:
  235. ```python
  236. >>> from transformers import (
  237. ... InstructBlipVisionConfig,
  238. ... InstructBlipQFormerConfig,
  239. ... OPTConfig,
  240. ... InstructBlipConfig,
  241. ... InstructBlipForConditionalGeneration,
  242. ... )
  243. >>> # Initializing a InstructBlipConfig with Salesforce/instruct-blip-flan-t5 style configuration
  244. >>> configuration = InstructBlipConfig()
  245. >>> # Initializing a InstructBlipForConditionalGeneration (with random weights) from the Salesforce/instruct-blip-flan-t5 style configuration
  246. >>> model = InstructBlipForConditionalGeneration(configuration)
  247. >>> # Accessing the model configuration
  248. >>> configuration = model.config
  249. >>> # We can also initialize a InstructBlipConfig from a InstructBlipVisionConfig, InstructBlipQFormerConfig and any PretrainedConfig
  250. >>> # Initializing InstructBLIP vision, InstructBLIP Q-Former and language model configurations
  251. >>> vision_config = InstructBlipVisionConfig()
  252. >>> qformer_config = InstructBlipQFormerConfig()
  253. >>> text_config = OPTConfig()
  254. >>> config = InstructBlipConfig.from_text_vision_configs(vision_config, qformer_config, text_config)
  255. ```"""
  256. model_type = "instructblip"
  257. def __init__(
  258. self,
  259. vision_config=None,
  260. qformer_config=None,
  261. text_config=None,
  262. num_query_tokens=32,
  263. image_token_index=None,
  264. **kwargs,
  265. ):
  266. super().__init__(**kwargs)
  267. if vision_config is None:
  268. vision_config = {}
  269. logger.info("vision_config is None. initializing the InstructBlipVisionConfig with default values.")
  270. if qformer_config is None:
  271. qformer_config = {}
  272. logger.info("qformer_config is None. Initializing the InstructBlipQFormerConfig with default values.")
  273. if text_config is None:
  274. text_config = {}
  275. logger.info("text_config is None. Initializing the text config with default values (`OPTConfig`).")
  276. self.vision_config = InstructBlipVisionConfig(**vision_config)
  277. self.qformer_config = InstructBlipQFormerConfig(**qformer_config)
  278. text_model_type = text_config["model_type"] if "model_type" in text_config else "opt"
  279. self.text_config = CONFIG_MAPPING[text_model_type](**text_config)
  280. self.tie_word_embeddings = self.text_config.tie_word_embeddings
  281. self.is_encoder_decoder = self.text_config.is_encoder_decoder
  282. self.num_query_tokens = num_query_tokens
  283. self.image_token_index = image_token_index
  284. self.qformer_config.encoder_hidden_size = self.vision_config.hidden_size
  285. self.use_decoder_only_language_model = self.text_config.model_type in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
  286. self.initializer_factor = 1.0
  287. self.initializer_range = 0.02
  288. @classmethod
  289. def from_vision_qformer_text_configs(
  290. cls,
  291. vision_config: InstructBlipVisionConfig,
  292. qformer_config: InstructBlipQFormerConfig,
  293. text_config: PretrainedConfig,
  294. **kwargs,
  295. ):
  296. r"""
  297. Instantiate a [`InstructBlipConfig`] (or a derived class) from a InstructBLIP vision model, Q-Former and
  298. language model configurations.
  299. Returns:
  300. [`InstructBlipConfig`]: An instance of a configuration object
  301. """
  302. return cls(
  303. vision_config=vision_config.to_dict(),
  304. qformer_config=qformer_config.to_dict(),
  305. text_config=text_config.to_dict(),
  306. **kwargs,
  307. )