configuration_instructblipvideo.py 17 KB

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