configuration.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. # Copyright (c) Alibaba, Inc. and its affiliates.
  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 typing import Mapping
  17. from transformers.configuration_utils import PretrainedConfig
  18. from transformers.onnx import OnnxSeq2SeqConfigWithPast
  19. from modelscope.utils.logger import get_logger
  20. logger = get_logger()
  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. [t5-small](https://huggingface.co/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. `d_kv` has to be equal to `d_model //
  37. num_heads`.
  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. layer_norm_eps (`float`, *optional*, defaults to 1e-6):
  53. The epsilon used by the layer normalization layers.
  54. initializer_factor (`float`, *optional*, defaults to 1):
  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"`. T5v1.1 uses the
  59. `"gated-gelu"` feed forward projection. Original T5 uses `"relu"`.
  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. """
  63. model_type = 't5'
  64. keys_to_ignore_at_inference = ['past_key_values']
  65. attribute_map = {
  66. 'hidden_size': 'd_model',
  67. 'num_attention_heads': 'num_heads',
  68. 'num_hidden_layers': 'num_layers'
  69. }
  70. def __init__(self,
  71. vocab_size=32128,
  72. d_model=512,
  73. d_kv=64,
  74. d_ff=2048,
  75. num_layers=6,
  76. num_decoder_layers=None,
  77. num_heads=8,
  78. relative_attention_num_buckets=32,
  79. relative_attention_max_distance=128,
  80. dropout_rate=0.1,
  81. layer_norm_epsilon=1e-6,
  82. initializer_factor=1.0,
  83. feed_forward_proj='relu',
  84. is_encoder_decoder=True,
  85. use_cache=True,
  86. pad_token_id=0,
  87. eos_token_id=1,
  88. **kwargs):
  89. self.vocab_size = vocab_size
  90. self.d_model = d_model
  91. self.d_kv = d_kv
  92. self.d_ff = d_ff
  93. self.num_layers = num_layers
  94. self.num_decoder_layers = (num_decoder_layers if num_decoder_layers
  95. is not None else self.num_layers
  96. ) # default = symmetry
  97. self.num_heads = num_heads
  98. self.relative_attention_num_buckets = relative_attention_num_buckets
  99. self.relative_attention_max_distance = relative_attention_max_distance
  100. self.dropout_rate = dropout_rate
  101. self.layer_norm_epsilon = layer_norm_epsilon
  102. self.initializer_factor = initializer_factor
  103. self.feed_forward_proj = feed_forward_proj
  104. self.use_cache = use_cache
  105. act_info = self.feed_forward_proj.split('-')
  106. self.dense_act_fn = act_info[-1]
  107. self.is_gated_act = act_info[0] == 'gated'
  108. if len(act_info) > 1 and act_info[0] != 'gated' or len(act_info) > 2:
  109. raise ValueError(
  110. f'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'
  111. 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '
  112. "'gated-gelu' or 'relu'")
  113. # for backwards compatibility
  114. if feed_forward_proj == 'gated-gelu':
  115. self.dense_act_fn = 'gelu_new'
  116. super().__init__(
  117. pad_token_id=pad_token_id,
  118. eos_token_id=eos_token_id,
  119. is_encoder_decoder=is_encoder_decoder,
  120. **kwargs,
  121. )
  122. class T5OnnxConfig(OnnxSeq2SeqConfigWithPast):
  123. @property
  124. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  125. common_inputs = {
  126. 'input_ids': {
  127. 0: 'batch',
  128. 1: 'encoder_sequence'
  129. },
  130. 'attention_mask': {
  131. 0: 'batch',
  132. 1: 'encoder_sequence'
  133. },
  134. }
  135. if self.use_past:
  136. common_inputs['attention_mask'][
  137. 1] = 'past_encoder_sequence + sequence'
  138. common_inputs['decoder_input_ids'] = {0: 'batch'}
  139. common_inputs['decoder_attention_mask'] = {
  140. 0: 'batch',
  141. 1: 'past_decoder_sequence + sequence'
  142. }
  143. else:
  144. common_inputs['decoder_input_ids'] = {
  145. 0: 'batch',
  146. 1: 'decoder_sequence'
  147. }
  148. common_inputs['decoder_attention_mask'] = {
  149. 0: 'batch',
  150. 1: 'decoder_sequence'
  151. }
  152. if self.use_past:
  153. self.fill_with_past_key_values_(common_inputs, direction='inputs')
  154. return common_inputs
  155. @property
  156. def default_onnx_opset(self) -> int:
  157. return 13