configuration_mt5.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # coding=utf-8
  2. # Copyright 2020, 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. """mT5 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 MT5Config(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`MT5Model`] or a [`TFMT5Model`]. It is used to
  24. instantiate a mT5 model according to the specified arguments, defining the model architecture. Instantiating a
  25. configuration with the defaults will yield a similar configuration to that of the mT5
  26. [google/mt5-small](https://huggingface.co/google/mt5-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 T5 model. Defines the number of different tokens that can be represented by the
  32. `inputs_ids` passed when calling [`T5Model`] or [`TFT5Model`].
  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. In the conventional context, it is typically expected that `d_kv` has to be equal to `d_model // num_heads`.
  37. But in the architecture of mt5-small, `d_kv` is not equal to `d_model //num_heads`. The `inner_dim` of the projection layer will be defined as `num_heads * d_kv`.
  38. d_ff (`int`, *optional*, defaults to 1024):
  39. Size of the intermediate feed forward layer in each `T5Block`.
  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 = "mt5"
  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=False,
  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. # for backwards compatibility
  124. if feed_forward_proj == "gated-gelu":
  125. self.dense_act_fn = "gelu_new"
  126. super().__init__(
  127. is_encoder_decoder=is_encoder_decoder,
  128. tokenizer_class=tokenizer_class,
  129. tie_word_embeddings=tie_word_embeddings,
  130. pad_token_id=pad_token_id,
  131. eos_token_id=eos_token_id,
  132. decoder_start_token_id=decoder_start_token_id,
  133. **kwargs,
  134. )
  135. class MT5OnnxConfig(OnnxSeq2SeqConfigWithPast):
  136. @property
  137. # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.inputs
  138. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  139. common_inputs = {
  140. "input_ids": {0: "batch", 1: "encoder_sequence"},
  141. "attention_mask": {0: "batch", 1: "encoder_sequence"},
  142. }
  143. if self.use_past:
  144. common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
  145. common_inputs["decoder_input_ids"] = {0: "batch"}
  146. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
  147. else:
  148. common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
  149. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
  150. if self.use_past:
  151. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  152. return common_inputs
  153. @property
  154. # Copied from transformers.models.t5.configuration_t5.T5OnnxConfig.default_onnx_opset
  155. def default_onnx_opset(self) -> int:
  156. return 13
  157. @property
  158. def atol_for_validation(self) -> float:
  159. return 5e-4
  160. __all__ = ["MT5Config", "MT5OnnxConfig"]