configuration_instructblipvideo.py 18 KB

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