configuration_t5.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. """T5 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 T5Config(PretrainedConfig):
  22. r"""
  23. This is the configuration class to store the configuration of a [`T5Model`] or a [`TFT5Model`]. It is used to
  24. instantiate a T5 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 T5
  26. [google-t5/t5-small](https://huggingface.co/google-t5/t5-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 32128):
  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. The `inner_dim` of the projection layer will
  37. be defined as `num_heads * d_kv`.
  38. d_ff (`int`, *optional*, defaults to 2048):
  39. Size of the intermediate feed forward layer in each `T5Block`.
  40. num_layers (`int`, *optional*, defaults to 6):
  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 8):
  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 `"relu"`):
  60. Type of feed forward layer to be used. Should be one of `"relu"` or `"gated-gelu"`. T5v1.1 uses the
  61. `"gated-gelu"` feed forward projection. Original T5 uses `"relu"`.
  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. """
  65. model_type = "t5"
  66. keys_to_ignore_at_inference = ["past_key_values"]
  67. attribute_map = {
  68. "hidden_size": "d_model",
  69. "num_attention_heads": "num_heads",
  70. "num_hidden_layers": "num_layers",
  71. "head_dim": "d_kv",
  72. }
  73. def __init__(
  74. self,
  75. vocab_size=32128,
  76. d_model=512,
  77. d_kv=64,
  78. d_ff=2048,
  79. num_layers=6,
  80. num_decoder_layers=None,
  81. num_heads=8,
  82. relative_attention_num_buckets=32,
  83. relative_attention_max_distance=128,
  84. dropout_rate=0.1,
  85. layer_norm_epsilon=1e-6,
  86. initializer_factor=1.0,
  87. feed_forward_proj="relu",
  88. is_encoder_decoder=True,
  89. use_cache=True,
  90. pad_token_id=0,
  91. eos_token_id=1,
  92. classifier_dropout=0.0,
  93. **kwargs,
  94. ):
  95. self.vocab_size = vocab_size
  96. self.d_model = d_model
  97. self.d_kv = d_kv
  98. self.d_ff = d_ff
  99. self.num_layers = num_layers
  100. self.num_decoder_layers = (
  101. num_decoder_layers if num_decoder_layers is not None else self.num_layers
  102. ) # default = symmetry
  103. self.num_heads = num_heads
  104. self.relative_attention_num_buckets = relative_attention_num_buckets
  105. self.relative_attention_max_distance = relative_attention_max_distance
  106. self.dropout_rate = dropout_rate
  107. self.classifier_dropout = classifier_dropout
  108. self.layer_norm_epsilon = layer_norm_epsilon
  109. self.initializer_factor = initializer_factor
  110. self.feed_forward_proj = feed_forward_proj
  111. self.use_cache = use_cache
  112. act_info = self.feed_forward_proj.split("-")
  113. self.dense_act_fn = act_info[-1]
  114. self.is_gated_act = act_info[0] == "gated"
  115. if len(act_info) > 1 and act_info[0] != "gated" or len(act_info) > 2:
  116. raise ValueError(
  117. f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer. "
  118. "Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. "
  119. "'gated-gelu' or 'relu'"
  120. )
  121. # for backwards compatibility
  122. if feed_forward_proj == "gated-gelu":
  123. self.dense_act_fn = "gelu_new"
  124. super().__init__(
  125. pad_token_id=pad_token_id,
  126. eos_token_id=eos_token_id,
  127. is_encoder_decoder=is_encoder_decoder,
  128. **kwargs,
  129. )
  130. class T5OnnxConfig(OnnxSeq2SeqConfigWithPast):
  131. @property
  132. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  133. common_inputs = {
  134. "input_ids": {0: "batch", 1: "encoder_sequence"},
  135. "attention_mask": {0: "batch", 1: "encoder_sequence"},
  136. }
  137. if self.use_past:
  138. common_inputs["attention_mask"][1] = "past_encoder_sequence + sequence"
  139. common_inputs["decoder_input_ids"] = {0: "batch"}
  140. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
  141. else:
  142. common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
  143. common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
  144. if self.use_past:
  145. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  146. return common_inputs
  147. @property
  148. def default_onnx_opset(self) -> int:
  149. return 13
  150. __all__ = ["T5Config", "T5OnnxConfig"]