configuration_pix2struct.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. # Copyright 2023 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Pix2Struct model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...utils import auto_docstring, logging
  18. logger = logging.get_logger(__name__)
  19. @auto_docstring(checkpoint="google/pix2struct-base")
  20. @strict
  21. class Pix2StructTextConfig(PreTrainedConfig):
  22. r"""
  23. relative_attention_num_buckets (`int`, *optional*, defaults to 32):
  24. The number of buckets to use for each attention layer.
  25. relative_attention_max_distance (`int`, *optional*, defaults to 128):
  26. The maximum distance of the longer sequences for the bucket separation.
  27. dense_act_fn (`Union[Callable, str]`, *optional*, defaults to `"gelu_new"`):
  28. The non-linear activation function (function or string).
  29. Example:
  30. ```python
  31. >>> from transformers import Pix2StructTextConfig, Pix2StructTextModel
  32. >>> # Initializing a Pix2StructTextConfig with google/pix2struct-base style configuration
  33. >>> configuration = Pix2StructTextConfig()
  34. >>> # Initializing a Pix2StructTextModel (with random weights) from the google/pix2struct-base style configuration
  35. >>> model = Pix2StructTextModel(configuration)
  36. >>> # Accessing the model configuration
  37. >>> configuration = model.config
  38. ```"""
  39. model_type = "pix2struct_text_model"
  40. keys_to_ignore_at_inference = ["past_key_values"]
  41. attribute_map = {
  42. "hidden_size": "hidden_size",
  43. "num_attention_heads": "num_heads",
  44. "num_hidden_layers": "num_layers",
  45. "decoder_attention_heads": "num_heads",
  46. "encoder_attention_heads": "num_heads",
  47. "encoder_layers": "num_layers",
  48. "decoder_layers": "num_layers",
  49. }
  50. vocab_size: int = 50244
  51. hidden_size: int = 768
  52. d_kv: int = 64
  53. d_ff: int = 2048
  54. num_layers: int = 12
  55. num_heads: int = 12
  56. relative_attention_num_buckets: int = 32
  57. relative_attention_max_distance: int = 128
  58. dropout_rate: float | int = 0.1
  59. layer_norm_epsilon: float = 1e-6
  60. initializer_factor: float = 1.0
  61. dense_act_fn: str = "gelu_new"
  62. decoder_start_token_id: int = 0
  63. use_cache: bool = False
  64. pad_token_id: int | None = 0
  65. eos_token_id: int | list[int] | None = 1
  66. bos_token_id: int | None = None
  67. tie_word_embeddings: bool = False
  68. is_decoder: bool = True
  69. add_cross_attention: bool = False
  70. @auto_docstring(checkpoint="google/pix2struct-base")
  71. @strict
  72. class Pix2StructVisionConfig(PreTrainedConfig):
  73. r"""
  74. patch_embed_hidden_size (`int`, *optional*, defaults to 768):
  75. Dimensionality of the input patch_embedding layer in the Transformer encoder.
  76. d_ff (`int`, *optional*, defaults to 2048):
  77. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  78. d_kv (`int`, *optional*, defaults to 64):
  79. Dimensionality of the key, query, value projections per attention head.
  80. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  81. `"relu"`, `"selu"` and `"gelu_new"` `"gelu"` are supported.
  82. dense_act_fn (`Union[Callable, str]`, *optional*, defaults to `"gelu_new"`):
  83. The non-linear activation function (function or string).
  84. seq_len (`int`, *optional*, defaults to 4096):
  85. Maximum sequence length (here number of patches) supported by the model.
  86. relative_attention_num_buckets (`int`, *optional*, defaults to 32):
  87. The number of buckets to use for each attention layer.
  88. relative_attention_max_distance (`int`, *optional*, defaults to 128):
  89. The maximum distance (in tokens) to use for each attention layer.
  90. Example:
  91. ```python
  92. >>> from transformers import Pix2StructVisionConfig, Pix2StructVisionModel
  93. >>> # Initializing a Pix2StructVisionConfig with google/pix2struct-base style configuration
  94. >>> configuration = Pix2StructVisionConfig()
  95. >>> # Initializing a Pix2StructVisionModel (with random weights) from the google/pix2struct-base style configuration
  96. >>> model = Pix2StructVisionModel(configuration)
  97. >>> # Accessing the model configuration
  98. >>> configuration = model.config
  99. ```"""
  100. model_type = "pix2struct_vision_model"
  101. hidden_size: int = 768
  102. patch_embed_hidden_size: int = 768
  103. d_ff: int = 2048
  104. d_kv: int = 64
  105. num_hidden_layers: int = 12
  106. num_attention_heads: int = 12
  107. dense_act_fn: str = "gelu_new"
  108. layer_norm_eps: float = 1e-6
  109. dropout_rate: float | int = 0.0
  110. attention_dropout: float | int = 0.0
  111. initializer_range: float = 1e-10
  112. initializer_factor: float = 1.0
  113. seq_len: int = 4096
  114. relative_attention_num_buckets: int = 32
  115. relative_attention_max_distance: int = 128
  116. @auto_docstring(checkpoint="google/pix2struct-base")
  117. @strict
  118. class Pix2StructConfig(PreTrainedConfig):
  119. r"""
  120. is_vqa (`bool`, *optional*, defaults to `False`):
  121. Whether the model has been fine-tuned for VQA or not.
  122. Example:
  123. ```python
  124. >>> from transformers import Pix2StructConfig, Pix2StructForConditionalGeneration
  125. >>> # Initializing a Pix2StructConfig with google/pix2struct-base style configuration
  126. >>> configuration = Pix2StructConfig()
  127. >>> # Initializing a Pix2StructForConditionalGeneration (with random weights) from the google/pix2struct-base style configuration
  128. >>> model = Pix2StructForConditionalGeneration(configuration)
  129. >>> # Accessing the model configuration
  130. >>> configuration = model.config
  131. >>> # We can also initialize a Pix2StructConfig from a Pix2StructTextConfig and a Pix2StructVisionConfig
  132. >>> # Initializing a Pix2Struct text and Pix2Struct vision configuration
  133. >>> config_text = Pix2StructTextConfig()
  134. >>> config_vision = Pix2StructVisionConfig()
  135. >>> config = Pix2StructConfig(text_config=config_text, vision_config=config_vision)
  136. ```"""
  137. model_type = "pix2struct"
  138. sub_configs = {"text_config": Pix2StructTextConfig, "vision_config": Pix2StructVisionConfig}
  139. text_config: dict | PreTrainedConfig | None = None
  140. vision_config: dict | PreTrainedConfig | None = None
  141. initializer_factor: float = 1.0
  142. initializer_range: float = 0.02
  143. is_vqa: bool = False
  144. tie_word_embeddings: bool = False
  145. is_encoder_decoder: bool = True
  146. def __post_init__(self, **kwargs):
  147. if self.text_config is None:
  148. self.text_config = Pix2StructTextConfig(
  149. is_encoder_decoder=self.is_encoder_decoder,
  150. tie_word_embeddings=self.tie_word_embeddings,
  151. )
  152. logger.info("`text_config` is `None`. initializing the `Pix2StructTextConfig` with default values.")
  153. elif isinstance(self.text_config, dict):
  154. self.text_config["is_encoder_decoder"] = self.is_encoder_decoder
  155. self.text_config["tie_word_embeddings"] = self.tie_word_embeddings
  156. self.text_config = Pix2StructTextConfig(**self.text_config)
  157. if self.vision_config is None:
  158. self.vision_config = Pix2StructVisionConfig()
  159. logger.info("`vision_config` is `None`. initializing the `Pix2StructVisionConfig` with default values.")
  160. elif isinstance(self.vision_config, dict):
  161. self.vision_config = Pix2StructVisionConfig(**self.vision_config)
  162. self.decoder_start_token_id = self.text_config.decoder_start_token_id
  163. self.pad_token_id = self.text_config.pad_token_id
  164. self.eos_token_id = self.text_config.eos_token_id
  165. self.text_config.initializer_range = self.initializer_range
  166. self.vision_config.initializer_range = self.initializer_range
  167. super().__post_init__(**kwargs)
  168. __all__ = ["Pix2StructConfig", "Pix2StructTextConfig", "Pix2StructVisionConfig"]