configuration_git.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. # coding=utf-8
  2. # Copyright 2022 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. import os
  16. from typing import Union
  17. from ...configuration_utils import PretrainedConfig
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class GitVisionConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`GitVisionModel`]. It is used to instantiate a GIT
  23. vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
  24. with the defaults will yield a similar configuration to that of the vision encoder of the GIT
  25. [microsoft/git-base](https://huggingface.co/microsoft/git-base) architecture.
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  27. documentation from [`PretrainedConfig`] for more information.
  28. Args:
  29. hidden_size (`int`, *optional*, defaults to 768):
  30. Dimensionality of the encoder layers and the pooler layer.
  31. intermediate_size (`int`, *optional*, defaults to 3072):
  32. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  33. num_hidden_layers (`int`, *optional*, defaults to 12):
  34. Number of hidden layers in the Transformer encoder.
  35. num_attention_heads (`int`, *optional*, defaults to 12):
  36. Number of attention heads for each attention layer in the Transformer encoder.
  37. image_size (`int`, *optional*, defaults to 224):
  38. The size (resolution) of each image.
  39. patch_size (`int`, *optional*, defaults to 16):
  40. The size (resolution) of each patch.
  41. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  42. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  43. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  44. layer_norm_eps (`float`, *optional*, defaults to 1e-5):
  45. The epsilon used by the layer normalization layers.
  46. attention_dropout (`float`, *optional*, defaults to 0.0):
  47. The dropout ratio for the attention probabilities.
  48. initializer_range (`float`, *optional*, defaults to 0.02):
  49. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  50. Example:
  51. ```python
  52. >>> from transformers import GitVisionConfig, GitVisionModel
  53. >>> # Initializing a GitVisionConfig with microsoft/git-base style configuration
  54. >>> configuration = GitVisionConfig()
  55. >>> # Initializing a GitVisionModel (with random weights) from the microsoft/git-base style configuration
  56. >>> model = GitVisionModel(configuration)
  57. >>> # Accessing the model configuration
  58. >>> configuration = model.config
  59. ```"""
  60. model_type = "git_vision_model"
  61. def __init__(
  62. self,
  63. hidden_size=768,
  64. intermediate_size=3072,
  65. num_hidden_layers=12,
  66. num_attention_heads=12,
  67. num_channels=3,
  68. image_size=224,
  69. patch_size=16,
  70. hidden_act="quick_gelu",
  71. layer_norm_eps=1e-5,
  72. attention_dropout=0.0,
  73. initializer_range=0.02,
  74. **kwargs,
  75. ):
  76. super().__init__(**kwargs)
  77. self.hidden_size = hidden_size
  78. self.intermediate_size = intermediate_size
  79. self.num_hidden_layers = num_hidden_layers
  80. self.num_attention_heads = num_attention_heads
  81. self.num_channels = num_channels
  82. self.patch_size = patch_size
  83. self.image_size = image_size
  84. self.initializer_range = initializer_range
  85. self.attention_dropout = attention_dropout
  86. self.layer_norm_eps = layer_norm_eps
  87. self.hidden_act = hidden_act
  88. @classmethod
  89. def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs) -> "PretrainedConfig":
  90. cls._set_token_in_kwargs(kwargs)
  91. config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
  92. # get the vision config dict if we are loading from GITConfig
  93. if config_dict.get("model_type") == "git":
  94. config_dict = config_dict["vision_config"]
  95. if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
  96. logger.warning(
  97. f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
  98. f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
  99. )
  100. return cls.from_dict(config_dict, **kwargs)
  101. class GitConfig(PretrainedConfig):
  102. r"""
  103. This is the configuration class to store the configuration of a [`GitModel`]. It is used to instantiate a GIT model
  104. according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  105. defaults will yield a similar configuration to that of the GIT
  106. [microsoft/git-base](https://huggingface.co/microsoft/git-base) architecture.
  107. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  108. documentation from [`PretrainedConfig`] for more information.
  109. Args:
  110. vision_config (`dict`, *optional*):
  111. Dictionary of configuration options used to initialize [`GitVisionConfig`].
  112. vocab_size (`int`, *optional*, defaults to 30522):
  113. Vocabulary size of the GIT model. Defines the number of different tokens that can be represented by the
  114. `inputs_ids` passed when calling [`GitModel`].
  115. hidden_size (`int`, *optional*, defaults to 768):
  116. Dimensionality of the encoder layers and the pooler layer.
  117. num_hidden_layers (`int`, *optional*, defaults to 6):
  118. Number of hidden layers in the Transformer encoder.
  119. num_attention_heads (`int`, *optional*, defaults to 12):
  120. Number of attention heads for each attention layer in the Transformer encoder.
  121. intermediate_size (`int`, *optional*, defaults to 3072):
  122. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  123. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  124. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  125. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  126. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  127. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  128. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  129. The dropout ratio for the attention probabilities.
  130. max_position_embeddings (`int`, *optional*, defaults to 1024):
  131. The maximum sequence length that this model might ever be used with. Typically set this to something large
  132. just in case (e.g., 512 or 1024 or 2048).
  133. initializer_range (`float`, *optional*, defaults to 0.02):
  134. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  135. layer_norm_eps (`float`, *optional*, defaults to 1e-12):
  136. The epsilon used by the layer normalization layers.
  137. position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
  138. Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
  139. positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
  140. [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
  141. For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
  142. with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
  143. use_cache (`bool`, *optional*, defaults to `True`):
  144. Whether or not the model should return the last key/values attentions (not used by all models).
  145. num_image_with_embedding (`int`, *optional*):
  146. The number of temporal embeddings to add, in case the model is used for video captioning/VQA.
  147. Examples:
  148. ```python
  149. >>> from transformers import GitConfig, GitModel
  150. >>> # Initializing a GIT microsoft/git-base style configuration
  151. >>> configuration = GitConfig()
  152. >>> # Initializing a model (with random weights) from the microsoft/git-base style configuration
  153. >>> model = GitModel(configuration)
  154. >>> # Accessing the model configuration
  155. >>> configuration = model.config
  156. ```"""
  157. model_type = "git"
  158. def __init__(
  159. self,
  160. vision_config=None,
  161. vocab_size=30522,
  162. hidden_size=768,
  163. num_hidden_layers=6,
  164. num_attention_heads=12,
  165. intermediate_size=3072,
  166. hidden_act="gelu",
  167. hidden_dropout_prob=0.1,
  168. attention_probs_dropout_prob=0.1,
  169. max_position_embeddings=1024,
  170. initializer_range=0.02,
  171. layer_norm_eps=1e-12,
  172. pad_token_id=0,
  173. position_embedding_type="absolute",
  174. use_cache=True,
  175. tie_word_embeddings=False,
  176. bos_token_id=101,
  177. eos_token_id=102,
  178. num_image_with_embedding=None,
  179. **kwargs,
  180. ):
  181. super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, pad_token_id=pad_token_id, **kwargs)
  182. if vision_config is None:
  183. vision_config = {}
  184. logger.info("vision_config is None. initializing the GitVisionConfig with default values.")
  185. self.vision_config = GitVisionConfig(**vision_config)
  186. self.vocab_size = vocab_size
  187. self.hidden_size = hidden_size
  188. self.num_hidden_layers = num_hidden_layers
  189. self.num_attention_heads = num_attention_heads
  190. self.hidden_act = hidden_act
  191. self.intermediate_size = intermediate_size
  192. self.hidden_dropout_prob = hidden_dropout_prob
  193. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  194. self.max_position_embeddings = max_position_embeddings
  195. self.initializer_range = initializer_range
  196. self.layer_norm_eps = layer_norm_eps
  197. self.position_embedding_type = position_embedding_type
  198. self.use_cache = use_cache
  199. self.tie_word_embeddings = tie_word_embeddings
  200. self.num_image_with_embedding = num_image_with_embedding
  201. self.bos_token_id = bos_token_id
  202. self.eos_token_id = eos_token_id