configuration_pix2struct.py 15 KB

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