configuration_umt5.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. # coding=utf-8
  2. # Copyright 2023, The T5 Authors and 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. """UMT5 model configuration"""
  16. from collections.abc import Mapping
  17. from ...configuration_utils import PretrainedConfig
  18. from ...onnx import OnnxSeq2SeqConfigWithPast
  19. from ...utils import logging
  20. logger = logging.get_logger(__name__)
  21. class UMT5Config(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`UMT5Model`]. It is used to instantiate a UMT5
  24. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  25. defaults will yield a similar configuration to that of the UMT5
  26. [google/umt5-small](https://huggingface.co/google/umt5-small) architecture.
  27. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  28. documentation from [`PretrainedConfig`] for more information.
  29. Arguments:
  30. vocab_size (`int`, *optional*, defaults to 250112):
  31. Vocabulary size of the UMT5 model. Defines the number of different tokens that can be represented by the
  32. `inputs_ids` passed when calling [`UMT5Model`] or [`TFUMT5Model`].
  33. d_model (`int`, *optional*, defaults to 512):
  34. Size of the encoder layers and the pooler layer.
  35. d_kv (`int`, *optional*, defaults to 64):
  36. Size of the key, query, value projections per attention head. `d_kv` has to be equal to `d_model //
  37. num_heads`.
  38. d_ff (`int`, *optional*, defaults to 1024):
  39. Size of the intermediate feed forward layer in each `UMT5Block`.
  40. num_layers (`int`, *optional*, defaults to 8):
  41. Number of hidden layers in the Transformer encoder.
  42. num_decoder_layers (`int`, *optional*):
  43. Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
  44. num_heads (`int`, *optional*, defaults to 6):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. relative_attention_num_buckets (`int`, *optional*, defaults to 32):
  47. The number of buckets to use for each attention layer.
  48. relative_attention_max_distance (`int`, *optional*, defaults to 128):
  49. The maximum distance of the longer sequences for the bucket separation.
  50. dropout_rate (`float`, *optional*, defaults to 0.1):
  51. The ratio for all dropout layers.
  52. classifier_dropout (`float`, *optional*, defaults to 0.0):
  53. The dropout ratio for classifier.
  54. layer_norm_eps (`float`, *optional*, defaults to 1e-6):
  55. The epsilon used by the layer normalization layers.
  56. initializer_factor (`float`, *optional*, defaults to 1):
  57. A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
  58. testing).
  59. feed_forward_proj (`string`, *optional*, defaults to `"gated-gelu"`):
  60. Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`.
  61. use_cache (`bool`, *optional*, defaults to `True`):
  62. Whether or not the model should return the last key/values attentions (not used by all models).
  63. """
  64. model_type = "umt5"
  65. keys_to_ignore_at_inference = ["past_key_values"]
  66. attribute_map = {
  67. "hidden_size": "d_model",
  68. "num_attention_heads": "num_heads",
  69. "num_hidden_layers": "num_layers",
  70. "head_dim": "d_kv",
  71. }
  72. def __init__(
  73. self,
  74. vocab_size=250112,
  75. d_model=512,
  76. d_kv=64,
  77. d_ff=1024,
  78. num_layers=8,
  79. num_decoder_layers=None,
  80. num_heads=6,
  81. relative_attention_num_buckets=32,
  82. relative_attention_max_distance=128,
  83. dropout_rate=0.1,
  84. layer_norm_epsilon=1e-6,
  85. initializer_factor=1.0,
  86. feed_forward_proj="gated-gelu",
  87. is_encoder_decoder=True,
  88. use_cache=True,
  89. tokenizer_class="T5Tokenizer",
  90. tie_word_embeddings=True,
  91. pad_token_id=0,
  92. eos_token_id=1,
  93. decoder_start_token_id=0,
  94. classifier_dropout=0.0,
  95. **kwargs,
  96. ):
  97. self.vocab_size = vocab_size
  98. self.d_model = d_model
  99. self.d_kv = d_kv
  100. self.d_ff = d_ff
  101. self.num_layers = num_layers
  102. self.num_decoder_layers = (
  103. num_decoder_layers if num_decoder_layers is not None else self.num_layers
  104. ) # default = symmetry
  105. self.num_heads = num_heads
  106. self.relative_attention_num_buckets = relative_attention_num_buckets
  107. self.relative_attention_max_distance = relative_attention_max_distance
  108. self.dropout_rate = dropout_rate
  109. self.classifier_dropout = classifier_dropout
  110. self.layer_norm_epsilon = layer_norm_epsilon
  111. self.initializer_factor = initializer_factor
  112. self.feed_forward_proj = feed_forward_proj
  113. self.use_cache = use_cache
  114. act_info = self.feed_forward_proj.split("-")
  115. self.dense_act_fn = act_info[-1]
  116. self.is_gated_act = act_info[0] == "gated"
  117. if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
  118. raise ValueError(
  119. f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. "
  120. "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
  121. "'gated-gelu' or 'relu'"
  122. )
  123. if feed_forward_proj == "gated-gelu":
  124. self.dense_act_fn = "gelu_new"
  125. super().__init__(
  126. is_encoder_decoder=is_encoder_decoder,
  127. tokenizer_class=tokenizer_class,
  128. tie_word_embeddings=tie_word_embeddings,
  129. pad_token_id=pad_token_id,
  130. eos_token_id=eos_token_id,
  131. decoder_start_token_id=decoder_start_token_id,
  132. **kwargs,
  133. )
  134. class UMT5OnnxConfig(OnnxSeq2SeqConfigWithPast):
  135. @property
  136. # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
  137. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  138. common_inputs = {
  139. "input_ids": {0: "batch", 1: "encoder_sequence"},
  140. "attention_mask": {0: "batch", 1: "encoder_sequence"},
  141. }
  142. if self.use_past:
  143. common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
  144. common_inputs["decoder_input_ids"] = {0: "batch"}
  145. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
  146. else:
  147. common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
  148. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
  149. if self.use_past:
  150. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  151. return common_inputs
  152. @property
  153. # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
  154. def default_onnx_opset(self) -> int:
  155. return 13
  156. @property
  157. def atol_for_validation(self) -> float:
  158. return 5e-4
  159. __all__ = ["UMT5Config", "UMT5OnnxConfig"]