configuration_pix2struct.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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. """Pix2Struct model configuration"""
  16. import os
  17. from typing import Union
  18. from ...configuration_utils import PretrainedConfig
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. class Pix2StructTextConfig(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`Pix2StructTextModel`]. It is used to instantiate
  24. a Pix2Struct text model according to the specified arguments, defining the model architecture. Instantiating a
  25. configuration with the defaults will yield a similar configuration to that of the Pix2Struct text decoder used by
  26. the [google/pix2struct-base](https://huggingface.co/google/pix2struct-base) 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. vocab_size (`int`, *optional*, defaults to 50244):
  31. Vocabulary size of the `Pix2Struct` text model. Defines the number of different tokens that can be
  32. represented by the `inputs_ids` passed when calling [`Pix2StructTextModel`].
  33. hidden_size (`int`, *optional*, defaults to 768):
  34. Dimensionality of the encoder layers and the pooler layer.
  35. d_kv (`int`, *optional*, defaults to 64):
  36. Dimensionality of the key, query, value projections in each attention head.
  37. d_ff (`int`, *optional*, defaults to 2048):
  38. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  39. num_layers (`int`, *optional*, defaults to 12):
  40. Number of hidden layers in the Transformer encoder.
  41. num_heads (`int`, *optional*, defaults to 12):
  42. Number of attention heads for each attention layer in the Transformer encoder.
  43. relative_attention_num_buckets (`int`, *optional*, defaults to 32):
  44. The number of buckets to use for each attention layer.
  45. relative_attention_max_distance (`int`, *optional*, defaults to 128):
  46. The maximum distance of the longer sequences for the bucket separation.
  47. dropout_rate (`float`, *optional*, defaults to 0.1):
  48. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  49. layer_norm_epsilon (`float`, *optional*, defaults to 1e-6):
  50. The epsilon used by the layer normalization layers.
  51. initializer_factor (`float`, *optional*, defaults to 1.0):
  52. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  53. testing).
  54. dense_act_fn (`Union[Callable, str]`, *optional*, defaults to `"gelu_new"`):
  55. The non-linear activation function (function or string).
  56. decoder_start_token_id (`int`, *optional*, defaults to 0):
  57. The id of the `decoder_start_token_id` token.
  58. use_cache (`bool`, *optional*, defaults to `False`):
  59. Whether or not the model should return the last key/values attentions (not used by all models).
  60. pad_token_id (`int`, *optional*, defaults to 0):
  61. The id of the `padding` token.
  62. eos_token_id (`int`, *optional*, defaults to 1):
  63. The id of the `end-of-sequence` token.
  64. Example:
  65. ```python
  66. >>> from transformers import Pix2StructTextConfig, Pix2StructTextModel
  67. >>> # Initializing a Pix2StructTextConfig with google/pix2struct-base style configuration
  68. >>> configuration = Pix2StructTextConfig()
  69. >>> # Initializing a Pix2StructTextModel (with random weights) from the google/pix2struct-base style configuration
  70. >>> model = Pix2StructTextModel(configuration)
  71. >>> # Accessing the model configuration
  72. >>> configuration = model.config
  73. ```"""
  74. model_type = "pix2struct_text_model"
  75. keys_to_ignore_at_inference = ["past_key_values"]
  76. attribute_map = {
  77. "hidden_size": "hidden_size",
  78. "num_attention_heads": "num_heads",
  79. "num_hidden_layers": "num_layers",
  80. }
  81. def __init__(
  82. self,
  83. vocab_size=50244,
  84. hidden_size=768,
  85. d_kv=64,
  86. d_ff=2048,
  87. num_layers=12,
  88. num_heads=12,
  89. relative_attention_num_buckets=32,
  90. relative_attention_max_distance=128,
  91. dropout_rate=0.1,
  92. layer_norm_epsilon=1e-6,
  93. initializer_factor=1.0,
  94. dense_act_fn="gelu_new",
  95. decoder_start_token_id=0,
  96. use_cache=False,
  97. pad_token_id=0,
  98. eos_token_id=1,
  99. tie_word_embeddings=False,
  100. is_decoder=True,
  101. **kwargs,
  102. ):
  103. self.vocab_size = vocab_size
  104. self.hidden_size = hidden_size
  105. self.d_kv = d_kv
  106. self.d_ff = d_ff
  107. self.num_layers = num_layers
  108. self.num_heads = num_heads
  109. self.relative_attention_num_buckets = relative_attention_num_buckets
  110. self.relative_attention_max_distance = relative_attention_max_distance
  111. self.dropout_rate = dropout_rate
  112. self.layer_norm_epsilon = layer_norm_epsilon
  113. self.initializer_factor = initializer_factor
  114. self.use_cache = use_cache
  115. self.eos_token_id = eos_token_id
  116. self.decoder_start_token_id = decoder_start_token_id
  117. # for backwards compatibility
  118. self.dense_act_fn = dense_act_fn
  119. super().__init__(
  120. pad_token_id=pad_token_id,
  121. eos_token_id=eos_token_id,
  122. decoder_start_token_id=decoder_start_token_id,
  123. tie_word_embeddings=tie_word_embeddings,
  124. is_decoder=is_decoder,
  125. **kwargs,
  126. )
  127. @classmethod
  128. def from_pretrained(
  129. cls, pretrainehidden_size_name_or_path: Union[str, os.PathLike], **kwargs
  130. ) -> "PretrainedConfig":
  131. cls._set_token_in_kwargs(kwargs)
  132. config_dict, kwargs = cls.get_config_dict(pretrainehidden_size_name_or_path, **kwargs)
  133. # get the text config dict if we are loading from Pix2StructConfig
  134. if config_dict.get("model_type") == "pix2struct":
  135. config_dict = config_dict["text_config"]
  136. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  137. logger.warning(
  138. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  139. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  140. )
  141. return cls.from_dict(config_dict, **kwargs)
  142. class Pix2StructVisionConfig(PretrainedConfig):
  143. r"""
  144. This is the configuration class to store the configuration of a [`Pix2StructVisionModel`]. It is used to
  145. instantiate a Pix2Struct vision model according to the specified arguments, defining the model architecture.
  146. Instantiating a configuration defaults will yield a similar configuration to that of the Pix2Struct-base
  147. [google/pix2struct-base](https://huggingface.co/google/pix2struct-base) architecture.
  148. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  149. documentation from [`PretrainedConfig`] for more information.
  150. Args:
  151. hidden_size (`int`, *optional*, defaults to 768):
  152. Dimensionality of the encoder layers and the pooler layer.
  153. patch_embed_hidden_size (`int`, *optional*, defaults to 768):
  154. Dimensionality of the input patch_embedding layer in the Transformer encoder.
  155. d_ff (`int`, *optional*, defaults to 2048):
  156. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  157. d_kv (`int`, *optional*, defaults to 64):
  158. Dimensionality of the key, query, value projections per attention head.
  159. num_hidden_layers (`int`, *optional*, defaults to 12):
  160. Number of hidden layers in the Transformer encoder.
  161. num_attention_heads (`int`, *optional*, defaults to 12):
  162. Number of attention heads for each attention layer in the Transformer encoder.
  163. dense_act_fn (`str` or `function`, *optional*, defaults to `"gelu_new"`):
  164. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  165. `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
  166. layer_norm_eps (`float`, *optional*, defaults to 1e-06):
  167. The epsilon used by the layer normalization layers.
  168. dropout_rate (`float`, *optional*, defaults to 0.0):
  169. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  170. attention_dropout (`float`, *optional*, defaults to 0.0):
  171. The dropout ratio for the attention probabilities.
  172. initializer_range (`float`, *optional*, defaults to 1e-10):
  173. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  174. initializer_factor (`float`, *optional*, defaults to 1.0):
  175. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  176. testing).
  177. seq_len (`int`, *optional*, defaults to 4096):
  178. Maximum sequence length (here number of patches) supported by the model.
  179. relative_attention_num_buckets (`int`, *optional*, defaults to 32):
  180. The number of buckets to use for each attention layer.
  181. relative_attention_max_distance (`int`, *optional*, defaults to 128):
  182. The maximum distance (in tokens) to use for each attention layer.
  183. Example:
  184. ```python
  185. >>> from transformers import Pix2StructVisionConfig, Pix2StructVisionModel
  186. >>> # Initializing a Pix2StructVisionConfig with google/pix2struct-base style configuration
  187. >>> configuration = Pix2StructVisionConfig()
  188. >>> # Initializing a Pix2StructVisionModel (with random weights) from the google/pix2struct-base style configuration
  189. >>> model = Pix2StructVisionModel(configuration)
  190. >>> # Accessing the model configuration
  191. >>> configuration = model.config
  192. ```"""
  193. model_type = "pix2struct_vision_model"
  194. def __init__(
  195. self,
  196. hidden_size=768,
  197. patch_embed_hidden_size=768,
  198. d_ff=2048,
  199. d_kv=64,
  200. num_hidden_layers=12,
  201. num_attention_heads=12,
  202. dense_act_fn="gelu_new",
  203. layer_norm_eps=1e-6,
  204. dropout_rate=0.0,
  205. attention_dropout=0.0,
  206. initializer_range=1e-10,
  207. initializer_factor=1.0,
  208. seq_len=4096,
  209. relative_attention_num_buckets=32,
  210. relative_attention_max_distance=128,
  211. **kwargs,
  212. ):
  213. super().__init__(**kwargs)
  214. self.hidden_size = hidden_size
  215. self.patch_embed_hidden_size = patch_embed_hidden_size
  216. self.d_ff = d_ff
  217. self.dropout_rate = dropout_rate
  218. self.num_hidden_layers = num_hidden_layers
  219. self.num_attention_heads = num_attention_heads
  220. self.initializer_range = initializer_range
  221. self.initializer_factor = initializer_factor
  222. self.attention_dropout = attention_dropout
  223. self.layer_norm_eps = layer_norm_eps
  224. self.dense_act_fn = dense_act_fn
  225. self.seq_len = seq_len
  226. self.relative_attention_num_buckets = relative_attention_num_buckets
  227. self.relative_attention_max_distance = relative_attention_max_distance
  228. self.d_kv = d_kv
  229. @classmethod
  230. def from_pretrained(
  231. cls, pretrainehidden_size_name_or_path: Union[str, os.PathLike], **kwargs
  232. ) -> "PretrainedConfig":
  233. cls._set_token_in_kwargs(kwargs)
  234. config_dict, kwargs = cls.get_config_dict(pretrainehidden_size_name_or_path, **kwargs)
  235. # get the vision config dict if we are loading from Pix2StructConfig
  236. if config_dict.get("model_type") == "pix2struct":
  237. config_dict = config_dict["vision_config"]
  238. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  239. logger.warning(
  240. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  241. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  242. )
  243. return cls.from_dict(config_dict, **kwargs)
  244. class Pix2StructConfig(PretrainedConfig):
  245. r"""
  246. [`Pix2StructConfig`] is the configuration class to store the configuration of a
  247. [`Pix2StructForConditionalGeneration`]. It is used to instantiate a Pix2Struct model according to the specified
  248. arguments, defining the text model and vision model configs. Instantiating a configuration with the defaults will
  249. yield a similar configuration to that of the Pix2Struct-base
  250. [google/pix2struct-base](https://huggingface.co/google/pix2struct-base) architecture.
  251. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  252. documentation from [`PretrainedConfig`] for more information.
  253. Args:
  254. text_config (`dict`, *optional*):
  255. Dictionary of configuration options used to initialize [`Pix2StructTextConfig`].
  256. vision_config (`dict`, *optional*):
  257. Dictionary of configuration options used to initialize [`Pix2StructVisionConfig`].
  258. initializer_factor (`float`, *optional*, defaults to 1.0):
  259. Factor to multiply the initialization range with.
  260. initializer_range (`float`, *optional*, defaults to 0.02):
  261. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  262. is_vqa (`bool`, *optional*, defaults to `False`):
  263. Whether the model has been fine-tuned for VQA or not.
  264. kwargs (*optional*):
  265. Dictionary of keyword arguments.
  266. Example:
  267. ```python
  268. >>> from transformers import Pix2StructConfig, Pix2StructForConditionalGeneration
  269. >>> # Initializing a Pix2StructConfig with google/pix2struct-base style configuration
  270. >>> configuration = Pix2StructConfig()
  271. >>> # Initializing a Pix2StructForConditionalGeneration (with random weights) from the google/pix2struct-base style configuration
  272. >>> model = Pix2StructForConditionalGeneration(configuration)
  273. >>> # Accessing the model configuration
  274. >>> configuration = model.config
  275. >>> # We can also initialize a Pix2StructConfig from a Pix2StructTextConfig and a Pix2StructVisionConfig
  276. >>> # Initializing a Pix2Struct text and Pix2Struct vision configuration
  277. >>> config_text = Pix2StructTextConfig()
  278. >>> config_vision = Pix2StructVisionConfig()
  279. >>> config = Pix2StructConfig.from_text_vision_configs(config_text, config_vision)
  280. ```"""
  281. model_type = "pix2struct"
  282. def __init__(
  283. self,
  284. text_config=None,
  285. vision_config=None,
  286. initializer_factor=1.0,
  287. initializer_range=0.02,
  288. is_vqa=False,
  289. tie_word_embeddings=False,
  290. is_encoder_decoder=True,
  291. **kwargs,
  292. ):
  293. super().__init__(tie_word_embeddings=tie_word_embeddings, is_encoder_decoder=is_encoder_decoder, **kwargs)
  294. if text_config is None:
  295. text_config = {}
  296. logger.info("text_config is None. Initializing the Pix2StructTextConfig with default values.")
  297. if vision_config is None:
  298. vision_config = {}
  299. logger.info("vision_config is None. Initializing the Pix2StructVisionConfig with default values.")
  300. self.text_config = Pix2StructTextConfig(**text_config)
  301. self.vision_config = Pix2StructVisionConfig(**vision_config)
  302. self.decoder_start_token_id = self.text_config.decoder_start_token_id
  303. self.pad_token_id = self.text_config.pad_token_id
  304. self.eos_token_id = self.text_config.eos_token_id
  305. self.initializer_factor = initializer_factor
  306. self.initializer_range = initializer_range
  307. self.text_config.initializer_range = self.initializer_range
  308. self.vision_config.initializer_range = self.initializer_range
  309. self.is_vqa = is_vqa
  310. @classmethod
  311. def from_text_vision_configs(
  312. cls, text_config: Pix2StructTextConfig, vision_config: Pix2StructVisionConfig, **kwargs
  313. ):
  314. r"""
  315. Instantiate a [`Pix2StructConfig`] (or a derived class) from pix2struct text model configuration and pix2struct
  316. vision model configuration.
  317. Returns:
  318. [`Pix2StructConfig`]: An instance of a configuration object
  319. """
  320. return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)