configuration_instructblip.py 15 KB

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