configuration_kosmos2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. # coding=utf-8
  2. # Copyright 2023 Microsoft Research and 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. """KOSMOS-2 model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class Kosmos2TextConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`Kosmos2TextModel`]. It is used to instantiate a
  22. KOSMOS-2 text decoder 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 text decoder of the KOSMOS-2
  24. [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) 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 65037):
  29. Vocabulary size of the Kosmos2 model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`Kosmos2Model`].
  31. max_position_embeddings (`int`, *optional*, defaults to 2048):
  32. The maximum sequence length that this model might ever be used with. Typically set this to something large
  33. just in case (e.g., 512 or 1024 or 2048).
  34. embed_dim (`int`, *optional*, defaults to 2048):
  35. Dimensionality of the layers and the pooler layer.
  36. layers (`int`, *optional*, defaults to 24):
  37. Number of hidden layers in the Transformer encoder.
  38. ffn_dim (`int`, *optional*, defaults to 8192):
  39. Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
  40. attention_heads (`int`, *optional*, defaults to 32):
  41. Number of attention heads for each attention layer in the Transformer encoder.
  42. activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
  43. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  44. `"relu"`, `"silu"` and `"gelu_new"` are supported.
  45. dropout (`float`, *optional*, defaults to 0.1):
  46. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  47. attention_dropout (`float`, *optional*, defaults to 0.1):
  48. The dropout ratio for the attention probabilities.
  49. activation_dropout (`float`, *optional*, defaults to 0.0):
  50. The dropout ratio for activations inside the fully connected layer.
  51. layerdrop (`float`, *optional*, defaults to 0.0):
  52. The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
  53. for more details.
  54. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  55. The epsilon used by the layer normalization layers.
  56. init_std (`float`, *optional*, defaults to 0.02):
  57. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  58. scale_embedding (`bool`, *optional*, defaults to `True`):
  59. Scale embeddings by diving by sqrt(embed_dim).
  60. use_cache (`bool`, *optional*, defaults to `True`):
  61. Whether or not the model should return the last key/values attentions (not used by all models).
  62. pad_token_id (`int`, *optional*, defaults to 1):
  63. Token id used for padding.
  64. bos_token_id (`int`, *optional*, defaults to 0):
  65. Token id used for beginning of string.
  66. eos_token_id (`int`, *optional*, defaults to 2):
  67. Token id used for end of string.
  68. ```"""
  69. model_type = "kosmos_2_text_model"
  70. base_config_key = "text_config"
  71. keys_to_ignore_at_inference = ["past_key_values"]
  72. attribute_map = {
  73. "num_attention_heads": "attention_heads",
  74. "hidden_size": "embed_dim",
  75. "num_hidden_layers": "layers",
  76. }
  77. def __init__(
  78. self,
  79. vocab_size=65037,
  80. max_position_embeddings=2048,
  81. embed_dim=2048,
  82. layers=24,
  83. ffn_dim=8192,
  84. attention_heads=32,
  85. activation_function="gelu",
  86. dropout=0.1,
  87. attention_dropout=0.1,
  88. activation_dropout=0.0,
  89. layerdrop=0.0,
  90. layer_norm_eps=1e-5,
  91. init_std=0.02,
  92. scale_embedding=True,
  93. use_cache=True,
  94. pad_token_id=1,
  95. bos_token_id=0,
  96. eos_token_id=2,
  97. **kwargs,
  98. ):
  99. super().__init__(
  100. pad_token_id=pad_token_id,
  101. bos_token_id=bos_token_id,
  102. eos_token_id=eos_token_id,
  103. **kwargs,
  104. )
  105. self.vocab_size = vocab_size
  106. self.max_position_embeddings = max_position_embeddings
  107. self.embed_dim = embed_dim
  108. self.layers = layers
  109. self.ffn_dim = ffn_dim
  110. self.attention_heads = attention_heads
  111. self.activation_function = activation_function
  112. self.dropout = dropout
  113. self.attention_dropout = attention_dropout
  114. self.activation_dropout = activation_dropout
  115. self.layerdrop = layerdrop
  116. self.layer_norm_eps = layer_norm_eps
  117. self.init_std = init_std
  118. self.scale_embedding = scale_embedding
  119. self.use_cache = use_cache
  120. class Kosmos2VisionConfig(PretrainedConfig):
  121. r"""
  122. This is the configuration class to store the configuration of a [`Kosmos2VisionModel`]. It is used to instantiate a
  123. KOSMOS-2 vision encoder according to the specified arguments, defining the model architecture. Instantiating a
  124. configuration with the defaults will yield a similar configuration to that of the vision encoder of the KOSMOS-2
  125. [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
  126. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  127. documentation from [`PretrainedConfig`] for more information.
  128. Args:
  129. hidden_size (`int`, *optional*, defaults to 1024):
  130. Dimensionality of the encoder layers and the pooler layer.
  131. intermediate_size (`int`, *optional*, defaults to 4096):
  132. Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
  133. num_hidden_layers (`int`, *optional*, defaults to 24):
  134. Number of hidden layers in the Transformer encoder.
  135. num_attention_heads (`int`, *optional*, defaults to 16):
  136. Number of attention heads for each attention layer in the Transformer encoder.
  137. num_channels (`int`, *optional*, defaults to 3):
  138. The number of input channels.
  139. image_size (`int`, *optional*, defaults to 224):
  140. The size (resolution) of each image.
  141. patch_size (`int`, *optional*, defaults to 14):
  142. The size (resolution) of each patch.
  143. hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
  144. The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
  145. `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
  146. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  147. The epsilon used by the layer normalization layers.
  148. attention_dropout (`float`, *optional*, defaults to 0.0):
  149. The dropout ratio for the attention probabilities.
  150. initializer_range (`float`, *optional*, defaults to 0.02):
  151. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  152. initializer_factor (`float`, *optional*, defaults to 1.0):
  153. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  154. testing).
  155. ```"""
  156. model_type = "kosmos_2_vision_model"
  157. base_config_key = "vision_config"
  158. def __init__(
  159. self,
  160. hidden_size=1024,
  161. intermediate_size=4096,
  162. num_hidden_layers=24,
  163. num_attention_heads=16,
  164. num_channels=3,
  165. image_size=224,
  166. patch_size=14,
  167. hidden_act="quick_gelu",
  168. layer_norm_eps=1e-5,
  169. attention_dropout=0.0,
  170. initializer_range=0.02,
  171. initializer_factor=1.0,
  172. **kwargs,
  173. ):
  174. super().__init__(**kwargs)
  175. self.hidden_size = hidden_size
  176. self.intermediate_size = intermediate_size
  177. self.num_hidden_layers = num_hidden_layers
  178. self.num_attention_heads = num_attention_heads
  179. self.num_channels = num_channels
  180. self.patch_size = patch_size
  181. self.image_size = image_size
  182. self.initializer_range = initializer_range
  183. self.initializer_factor = initializer_factor
  184. self.attention_dropout = attention_dropout
  185. self.layer_norm_eps = layer_norm_eps
  186. self.hidden_act = hidden_act
  187. class Kosmos2Config(PretrainedConfig):
  188. r"""
  189. This is the configuration class to store the configuration of a [`Kosmos2Model`]. It is used to instantiate a
  190. KOSMOS-2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
  191. with the defaults will yield a similar configuration to that of the KOSMOS-2
  192. [microsoft/kosmos-2-patch14-224](https://huggingface.co/microsoft/kosmos-2-patch14-224) architecture.
  193. Args:
  194. text_config (`dict`, *optional*):
  195. Dictionary of configuration options used to initialize [`Kosmos2TextConfig`].
  196. vision_config (`dict`, *optional*):
  197. Dictionary of configuration options used to initialize [`Kosmos2VisionConfig`].
  198. latent_query_num (`int`, *optional*, defaults to 64):
  199. The number of latent query tokens that represent the image features used in the text decoder component.
  200. kwargs (*optional*):
  201. Dictionary of keyword arguments.
  202. Example:
  203. ```python
  204. >>> from transformers import Kosmos2Config, Kosmos2Model
  205. >>> # Initializing a Kosmos-2 kosmos-2-patch14-224 style configuration
  206. >>> configuration = Kosmos2Config()
  207. >>> # Initializing a model (with random weights) from the kosmos-2-patch14-224 style configuration
  208. >>> model = Kosmos2Model(configuration)
  209. >>> # Accessing the model configuration
  210. >>> configuration = model.config
  211. ```"""
  212. model_type = "kosmos-2"
  213. sub_configs = {"text_config": Kosmos2TextConfig, "vision_config": Kosmos2VisionConfig}
  214. def __init__(
  215. self,
  216. text_config=None,
  217. vision_config=None,
  218. latent_query_num=64,
  219. **kwargs,
  220. ):
  221. super().__init__(**kwargs)
  222. if text_config is None:
  223. text_config = {}
  224. logger.info("`text_config` is `None`. Initializing the `Kosmos2TextConfig` with default values.")
  225. if vision_config is None:
  226. vision_config = {}
  227. logger.info("`vision_config` is `None`. Initializing the `Kosmos2VisionConfig` with default values.")
  228. self.text_config = Kosmos2TextConfig(**text_config)
  229. self.vision_config = Kosmos2VisionConfig(**vision_config)
  230. self.latent_query_num = latent_query_num
  231. __all__ = ["Kosmos2Config"]