configuration_udop.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # coding=utf-8
  2. # Copyright 2024 HuggingFace Inc.
  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. """UDOP model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class UdopConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`UdopForConditionalGeneration`]. It is used to
  22. instantiate a UDOP 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 UDOP
  24. [microsoft/udop-large](https://huggingface.co/microsoft/udop-large) 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. Arguments:
  28. vocab_size (`int`, *optional*, defaults to 33201):
  29. Vocabulary size of the UDOP model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`UdopForConditionalGeneration`].
  31. d_model (`int`, *optional*, defaults to 1024):
  32. Size of the encoder layers and the pooler layer.
  33. d_kv (`int`, *optional*, defaults to 64):
  34. Size of the key, query, value projections per attention head. The `inner_dim` of the projection layer will
  35. be defined as `num_heads * d_kv`.
  36. d_ff (`int`, *optional*, defaults to 4096):
  37. Size of the intermediate feed forward layer in each `UdopBlock`.
  38. num_layers (`int`, *optional*, defaults to 24):
  39. Number of hidden layers in the Transformer encoder and decoder.
  40. num_decoder_layers (`int`, *optional*):
  41. Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
  42. num_heads (`int`, *optional*, defaults to 16):
  43. Number of attention heads for each attention layer in the Transformer encoder and decoder.
  44. relative_attention_num_buckets (`int`, *optional*, defaults to 32):
  45. The number of buckets to use for each attention layer.
  46. relative_attention_max_distance (`int`, *optional*, defaults to 128):
  47. The maximum distance of the longer sequences for the bucket separation.
  48. relative_bias_args (`list[dict]`, *optional*, defaults to `[{'type': '1d'}, {'type': 'horizontal'}, {'type': 'vertical'}]`):
  49. A list of dictionaries containing the arguments for the relative bias layers.
  50. dropout_rate (`float`, *optional*, defaults to 0.1):
  51. The ratio for all dropout layers.
  52. layer_norm_epsilon (`float`, *optional*, defaults to 1e-06):
  53. The epsilon used by the layer normalization layers.
  54. initializer_factor (`float`, *optional*, defaults to 1.0):
  55. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  56. testing).
  57. feed_forward_proj (`string`, *optional*, defaults to `"relu"`):
  58. Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. Udopv1.1 uses the
  59. `"gated-gelu"` feed forward projection. Original Udop uses `"relu"`.
  60. is_encoder_decoder (`bool`, *optional*, defaults to `True`):
  61. Whether the model should behave as an encoder/decoder or not.
  62. use_cache (`bool`, *optional*, defaults to `True`):
  63. Whether or not the model should return the last key/values attentions (not used by all models).
  64. pad_token_id (`int`, *optional*, defaults to 0):
  65. The id of the padding token in the vocabulary.
  66. eos_token_id (`int`, *optional*, defaults to 1):
  67. The id of the end-of-sequence token in the vocabulary.
  68. max_2d_position_embeddings (`int`, *optional*, defaults to 1024):
  69. The maximum absolute position embeddings for relative position encoding.
  70. image_size (`int`, *optional*, defaults to 224):
  71. The size of the input images.
  72. patch_size (`int`, *optional*, defaults to 16):
  73. The patch size used by the vision encoder.
  74. num_channels (`int`, *optional*, defaults to 3):
  75. The number of channels in the input images.
  76. """
  77. model_type = "udop"
  78. keys_to_ignore_at_inference = ["past_key_values"]
  79. attribute_map = {"hidden_size": "d_model", "num_attention_heads": "num_heads", "num_hidden_layers": "num_layers"}
  80. def __init__(
  81. self,
  82. vocab_size=33201,
  83. d_model=1024,
  84. d_kv=64,
  85. d_ff=4096,
  86. num_layers=24,
  87. num_decoder_layers=None,
  88. num_heads=16,
  89. relative_attention_num_buckets=32,
  90. relative_attention_max_distance=128,
  91. relative_bias_args=[{"type": "1d"}, {"type": "horizontal"}, {"type": "vertical"}],
  92. dropout_rate=0.1,
  93. layer_norm_epsilon=1e-6,
  94. initializer_factor=1.0,
  95. feed_forward_proj="relu",
  96. is_encoder_decoder=True,
  97. use_cache=True,
  98. pad_token_id=0,
  99. eos_token_id=1,
  100. max_2d_position_embeddings=1024,
  101. image_size=224,
  102. patch_size=16,
  103. num_channels=3,
  104. **kwargs,
  105. ):
  106. self.vocab_size = vocab_size
  107. self.d_model = d_model
  108. self.d_kv = d_kv
  109. self.d_ff = d_ff
  110. self.num_layers = num_layers
  111. self.num_decoder_layers = (
  112. num_decoder_layers if num_decoder_layers is not None else self.num_layers
  113. ) # default = symmetry
  114. self.num_heads = num_heads
  115. self.relative_attention_num_buckets = relative_attention_num_buckets
  116. self.relative_attention_max_distance = relative_attention_max_distance
  117. self.dropout_rate = dropout_rate
  118. self.layer_norm_epsilon = layer_norm_epsilon
  119. self.initializer_factor = initializer_factor
  120. self.feed_forward_proj = feed_forward_proj
  121. self.use_cache = use_cache
  122. # UDOP attributes
  123. self.max_2d_position_embeddings = max_2d_position_embeddings
  124. self.image_size = image_size
  125. self.patch_size = patch_size
  126. self.num_channels = num_channels
  127. if not isinstance(relative_bias_args, list):
  128. raise TypeError("`relative_bias_args` should be a list of dictionaries.")
  129. self.relative_bias_args = relative_bias_args
  130. act_info = self.feed_forward_proj.split("-")
  131. self.dense_act_fn = act_info[-1]
  132. self.is_gated_act = act_info[0] == "gated"
  133. if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
  134. raise ValueError(
  135. f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
  136. "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
  137. "'gated-gelu' or 'relu'"
  138. )
  139. super().__init__(
  140. pad_token_id=pad_token_id,
  141. eos_token_id=eos_token_id,
  142. is_encoder_decoder=is_encoder_decoder,
  143. **kwargs,
  144. )
  145. __all__ = ["UdopConfig"]