configuration_idefics.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. # coding=utf-8
  2. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. """Idefics model configuration"""
  21. from ...configuration_utils import PretrainedConfig
  22. from ...utils import logging
  23. logger = logging.get_logger(__name__)
  24. class IdeficsVisionConfig(PretrainedConfig):
  25. r"""
  26. This is the configuration class to store the configuration of a [`IdeficsModel`]. It is used to instantiate an
  27. Idefics model according to the specified arguments, defining the model architecture. Instantiating a configuration
  28. with the defaults will yield a similar configuration to that of the Idefics-9B.
  29. e.g. [HuggingFaceM4/idefics-9b](https://huggingface.co/HuggingFaceM4/idefics-9b)
  30. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  31. documentation from [`PretrainedConfig`] for more information.
  32. Args:
  33. embed_dim (`int`, *optional*, defaults to 768):
  34. Dimensionality of the encoder layers and the pooler layer. (elsewhere referred to as `hidden_size`)
  35. image_size (`int`, *optional*, defaults to 224):
  36. The size (resolution) of each image.
  37. intermediate_size (`int`, *optional*, defaults to 5120):
  38. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  39. patch_size (`int`, *optional*, defaults to 14):
  40. The size (resolution) of each patch.
  41. num_hidden_layers (`int`, *optional*, defaults to 32):
  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. num_channels (`int`, *optional*, defaults to 3):
  46. Number of image channels.
  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"` `"quick_gelu"` are supported.
  50. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  51. The epsilon used by the layer normalization layers.
  52. attention_dropout (`float`, *optional*, defaults to 0.0):
  53. The dropout ratio for the attention probabilities.
  54. initializer_range (`float`, *optional*, defaults to 0.02):
  55. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  56. initializer_factor (`float`, *optional*, defaults to 1.0):
  57. A factor for initializing all weight matrices (should be kept to 1.0, used internally for initialization
  58. testing).
  59. """
  60. model_type = "idefics_vision"
  61. attribute_map = {
  62. "hidden_size": "embed_dim",
  63. }
  64. def __init__(
  65. self,
  66. embed_dim=768,
  67. image_size=224,
  68. intermediate_size=5120,
  69. patch_size=14,
  70. num_hidden_layers=32,
  71. num_attention_heads=16,
  72. num_channels=3,
  73. hidden_act="gelu",
  74. layer_norm_eps=1e-5,
  75. attention_dropout=0.0,
  76. initializer_range=0.02,
  77. initializer_factor=1.0,
  78. **kwargs,
  79. ):
  80. self.embed_dim = embed_dim
  81. self.image_size = image_size
  82. self.intermediate_size = intermediate_size
  83. self.patch_size = patch_size
  84. self.num_hidden_layers = num_hidden_layers
  85. self.num_attention_heads = num_attention_heads
  86. self.num_channels = num_channels
  87. self.layer_norm_eps = layer_norm_eps
  88. self.attention_dropout = attention_dropout
  89. self.initializer_range = initializer_range
  90. self.initializer_factor = initializer_factor
  91. self.hidden_act = hidden_act
  92. super().__init__(**kwargs)
  93. class IdeficsPerceiverConfig(PretrainedConfig):
  94. r"""
  95. This is the configuration class to store the configuration of a [`IdeficsModel`]. It is used to instantiate an
  96. Idefics model according to the specified arguments, defining the model architecture. Instantiating a configuration
  97. with the defaults will yield a similar configuration to that of the Idefics-9B.
  98. e.g. [HuggingFaceM4/idefics-9b](https://huggingface.co/HuggingFaceM4/idefics-9b)
  99. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  100. documentation from [`PretrainedConfig`] for more information.
  101. Args:
  102. use_resampler (`bool`, *optional*, defaults to `False`):
  103. Whether or not to use the resampler
  104. resampler_n_latents (`int`, *optional*, defaults to 64):
  105. Number of latent embeddings to resample ("compress") the input sequence to (usually < 128).
  106. resampler_depth (`int`, *optional*, defaults to 6):
  107. Depth of the Perceiver Resampler (Transformer w/ cross attention). Should be shallow (< 3).
  108. resampler_n_heads (`int`, *optional*, defaults to 16):
  109. Number of heads in each Transformer block (for multi-headed self-attention).
  110. resampler_head_dim (`int`, *optional*, defaults to 96):
  111. Dimensionality of each head projection in the Transformer block.
  112. qk_layer_norms_perceiver (`bool`, *optional*, defaults to `False`):
  113. Whether or not to use qk layer norms in perceiver
  114. """
  115. model_type = "idefics_perciever"
  116. def __init__(
  117. self,
  118. use_resampler=False,
  119. resampler_n_latents=64,
  120. resampler_depth=6,
  121. resampler_n_heads=16,
  122. resampler_head_dim=96,
  123. qk_layer_norms_perceiver=False,
  124. **kwargs,
  125. ):
  126. self.use_resampler = use_resampler
  127. self.resampler_n_latents = resampler_n_latents
  128. self.resampler_depth = resampler_depth
  129. self.resampler_n_heads = resampler_n_heads
  130. self.resampler_head_dim = resampler_head_dim
  131. self.qk_layer_norms_perceiver = qk_layer_norms_perceiver
  132. super().__init__(**kwargs)
  133. class IdeficsConfig(PretrainedConfig):
  134. r"""
  135. This is the configuration class to store the configuration of a [`IdeficsModel`]. It is used to instantiate an
  136. Idefics model according to the specified arguments, defining the model architecture. Instantiating a configuration
  137. with the defaults will yield a similar configuration to that of the Idefics-9B.
  138. e.g. [HuggingFaceM4/idefics-9b](https://huggingface.co/HuggingFaceM4/idefics-9b)
  139. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  140. documentation from [`PretrainedConfig`] for more information.
  141. Args:
  142. additional_vocab_size (`int`, *optional*, defaults to 0):
  143. Additional vocabulary size of the model, typically for the special "<img>" token. Additional vocab tokens
  144. are always trainable whereas regular vocab tokens can be frozen or not.
  145. vocab_size (`int`, *optional*, defaults to 32000):
  146. Vocabulary size of the Idefics model. Defines the number of different tokens that can be represented by the
  147. `inputs_ids` passed when calling [`~IdeficsModel`]
  148. hidden_size (`int`, *optional*, defaults to 4096):
  149. Dimension of the hidden representations.
  150. intermediate_size (`int`, *optional*, defaults to 11008):
  151. Dimension of the MLP representations.
  152. num_hidden_layers (`int`, *optional*, defaults to 32):
  153. Number of hidden layers in the Transformer encoder.
  154. num_attention_heads (`int`, *optional*, defaults to 32):
  155. Number of attention heads for each attention layer in the Transformer encoder.
  156. dropout (`float`, *optional*, defaults to 0.0):
  157. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  158. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  159. The non-linear activation function (function or string) in the decoder.
  160. initializer_range (`float`, *optional*, defaults to 0.02):
  161. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  162. alpha_initializer (`str`, *optional*, defaults to `"zeros"`):
  163. Initialization type for the alphas.
  164. alphas_initializer_range (`float`, *optional*, defaults to 0.0):
  165. The standard deviation of the truncated_normal_initializer for initializing the alphas in the Gated Cross
  166. Attention.
  167. alpha_type (`str`, *optional*, defaults to `"float"`):
  168. Whether the gating alphas should be vectors or single floats.
  169. rms_norm_eps (`float`, *optional*, defaults to 1e-6):
  170. The epsilon used by the rms normalization layers.
  171. use_cache (`bool`, *optional*, defaults to `True`):
  172. Whether or not the model should return the last key/values attentions (not used by all models). Only
  173. relevant if `config.is_decoder=True`.
  174. pad_token_id (`int`, *optional*, defaults to 0)
  175. Padding token id.
  176. bos_token_id (`int`, *optional*, defaults to 1)
  177. Beginning of stream token id.
  178. eos_token_id (`int`, *optional*, defaults to 2)
  179. End of stream token id.
  180. tie_word_embeddings(`bool`, *optional*, defaults to `False`):
  181. Whether to tie weight embeddings
  182. cross_layer_interval (`int`, *optional*, default to 1)
  183. Interval for cross attention (from text to image) layers.
  184. qk_layer_norms (`bool`, *optional*, defaults to `False`): Whether to add layer norm after q and k
  185. freeze_text_layers (`bool`, *optional*, defaults to `True`): Whether to freeze text layers
  186. freeze_text_module_exceptions (`bool`, *optional*, defaults to `[]`):
  187. Exceptions to freezing text layers when `freeze_text_layers` is `True`
  188. freeze_lm_head (`bool`, *optional*, defaults to `False`): Whether to freeze lm head
  189. freeze_vision_layers (`bool`, *optional*, defaults to `True`): Whether to freeze vision layers
  190. freeze_vision_module_exceptions (`bool`, *optional*, defaults to `[]`):
  191. Exceptions to freezing vision layers when `freeze_vision_layers` is `True`
  192. use_resampler (`bool`, *optional*, defaults to `False`): Whether to use the Resampler
  193. vision_config (`IdeficsVisionConfig`, *optional*): Custom vision config or dict
  194. perceiver_config (`IdeficsPerceiverConfig`, *optional*): Custom perceiver config or dict
  195. Example:
  196. ```python
  197. >>> from transformers import IdeficsModel, IdeficsConfig
  198. >>> # Initializing a Idefics idefics-9b style configuration
  199. >>> configuration = IdeficsConfig()
  200. >>> # Initializing a model from the idefics-9b style configuration
  201. >>> model = IdeficsModel(configuration)
  202. >>> # Accessing the model configuration
  203. >>> configuration = model.config
  204. ```"""
  205. model_type = "idefics"
  206. sub_configs = {"perceiver_config": IdeficsPerceiverConfig, "vision_config": IdeficsVisionConfig}
  207. def __init__(
  208. self,
  209. vocab_size=32000,
  210. additional_vocab_size=0,
  211. hidden_size=4096,
  212. intermediate_size=11008,
  213. num_hidden_layers=32,
  214. num_attention_heads=32,
  215. dropout=0.0,
  216. hidden_act="silu",
  217. initializer_range=0.02,
  218. alpha_initializer="zeros",
  219. alphas_initializer_range=0.0,
  220. alpha_type="float",
  221. rms_norm_eps=1e-6,
  222. use_cache=True,
  223. pad_token_id=0,
  224. bos_token_id=1,
  225. eos_token_id=2,
  226. tie_word_embeddings=False,
  227. cross_layer_interval=1,
  228. qk_layer_norms=False,
  229. freeze_text_layers=True,
  230. freeze_text_module_exceptions=[],
  231. freeze_lm_head=False,
  232. freeze_vision_layers=True,
  233. freeze_vision_module_exceptions=[],
  234. use_resampler=False,
  235. vision_config=None,
  236. perceiver_config=None,
  237. **kwargs,
  238. ):
  239. self.vocab_size = vocab_size
  240. self.additional_vocab_size = additional_vocab_size
  241. self.hidden_size = hidden_size
  242. self.intermediate_size = intermediate_size
  243. self.num_hidden_layers = num_hidden_layers
  244. self.num_attention_heads = num_attention_heads
  245. self.dropout = dropout
  246. self.hidden_act = hidden_act
  247. self.initializer_range = initializer_range
  248. self.alpha_initializer = alpha_initializer
  249. self.alphas_initializer_range = alphas_initializer_range
  250. self.alpha_type = alpha_type
  251. self.rms_norm_eps = rms_norm_eps
  252. self.use_cache = use_cache
  253. self.cross_layer_interval = cross_layer_interval
  254. self.qk_layer_norms = qk_layer_norms
  255. self.freeze_vision_layers = freeze_vision_layers
  256. self.freeze_text_layers = freeze_text_layers
  257. self.freeze_text_module_exceptions = freeze_text_module_exceptions
  258. self.freeze_vision_module_exceptions = freeze_vision_module_exceptions
  259. self.freeze_lm_head = freeze_lm_head
  260. self.use_resampler = use_resampler
  261. if perceiver_config is None:
  262. self.perceiver_config = IdeficsPerceiverConfig()
  263. elif isinstance(perceiver_config, dict):
  264. self.perceiver_config = IdeficsPerceiverConfig(**perceiver_config)
  265. elif isinstance(perceiver_config, IdeficsPerceiverConfig):
  266. self.perceiver_config = perceiver_config
  267. if vision_config is None:
  268. self.vision_config = IdeficsVisionConfig()
  269. elif isinstance(vision_config, dict):
  270. self.vision_config = IdeficsVisionConfig(**vision_config)
  271. elif isinstance(vision_config, IdeficsVisionConfig):
  272. self.vision_config = vision_config
  273. super().__init__(
  274. pad_token_id=pad_token_id,
  275. bos_token_id=bos_token_id,
  276. eos_token_id=eos_token_id,
  277. tie_word_embeddings=tie_word_embeddings,
  278. **kwargs,
  279. )
  280. # IMPORTANT: Do not do any __init__ args-based checks in the constructor, since
  281. # PretrainedConfig.from_dict first instantiates the class with the config dict and only then
  282. # updates the config object with `kwargs` from from_pretrained, so during the instantiation
  283. # of this object many attributes have default values and haven't yet been overridden.
  284. # Do any required checks inside `from_pretrained` once the superclass' `from_pretrained` was run.
  285. __all__ = ["IdeficsConfig"]