configuration.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. # Copyright 2021-2022 The Alibaba DAMO NLP Team Authors.
  2. # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
  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. import torch
  16. from transformers.configuration_utils import PretrainedConfig
  17. from transformers.utils import logging
  18. logger = logging.get_logger()
  19. class GPT3Config(PretrainedConfig):
  20. r"""
  21. Configuration classes for GPT-3 model.
  22. Class attributes:
  23. - **model_type** (`str`) -- An identifier for the model type, serialized into the JSON file, can be used to recreate
  24. the correct object in [`~transformers.AutoConfig`].
  25. Args:
  26. vocab_size (`int`, *optional*, defaults to 25600):
  27. Vocabulary size of the GPT model. Defines the number of different
  28. tokens that can be represented by the `inputs_ids` passed when
  29. calling [`GPT3Model`].
  30. hidden_size (`int`, *optional*, defaults to 768):
  31. Dimensionality of the decoder layers and the pooler layer.
  32. ffn_hidden_size (`int`, *optional*, defaults to None):
  33. Dimensionality of the ffn layer, None defaults to four times the hidden_size.
  34. num_hidden_layers (`int`, *optional*, defaults to 12):
  35. Number of hidden layers in the Transformer decoder.
  36. num_attention_heads (`int`, *optional*, defaults to 12):
  37. Number of attention heads for each attention layer in the
  38. Transformer decoder.
  39. intermediate_size (`int`, *optional*, defaults to 3072):
  40. Dimensionality of the "intermediate" (often named feed-forward)
  41. layer in the Transformer decoder.
  42. hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
  43. The non-linear activation function (function or string) in the
  44. decoder and pooler. If string, `"gelu"`, `"relu"`, `"silu"` and
  45. `"gelu_new"` are supported.
  46. hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
  47. The dropout probability for all fully connected layers in the
  48. embeddings, decoder, and pooler.
  49. attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
  50. The dropout ratio for the attention probabilities.
  51. max_position_embeddings (`int`, *optional*, defaults to 512):
  52. The maximum sequence length that this model might ever be used with.
  53. Typically set this to something large just in case (e.g., 512 or
  54. 1024 or 2048).
  55. type_vocab_size (`int`, *optional*, defaults to 2):
  56. The vocabulary size of the `token_type_ids` passed when calling
  57. [`GPT3Model`].
  58. layernorm_epsilon (`float`, *optional*, defaults to 1e-12):
  59. The epsilon used by the layer normalization layers.
  60. bias_gelu_fusion (`bool`, *optional*, defaults to True):
  61. Whether to use gelu activation function when mixing bias.
  62. fp32_residual_connection (`bool`, *optional*, defaults to False):
  63. Whether to use fp32 for residual connection
  64. between layers to improve accuracy.
  65. sequence_parallel (`bool`, *optional*, defaults to False):
  66. Whether to use sequence parallel during training.
  67. bf16 (`bool`, *optional*, defaults to `False`):
  68. Whether to use bf16 16-bit (mixed) precision training instead of 32-bit training.
  69. Requires Ampere or higher NVIDIA architecture or using CPU (no_cuda).
  70. This is an experimental API and it may change.
  71. fp16 (`bool`, *optional*, defaults to `False`):
  72. Whether to use fp16 16-bit (mixed) precision training instead of 32-bit training.
  73. apply_query_key_layer_scaling (`bool`, *optional*, defaults to `True`):
  74. Whether to scale query and key layer parameters during training.
  75. init_method_std (`float`, *optional*, defaults to `0.02`):
  76. The standard deviation of the normal distribution for initialization process.
  77. eod_id (`int`, *optional*, defaults to `1`):
  78. The end of text label for tokenizer, also indicates the end of the generation.
  79. tokens_to_generate (`int`, *optional*, defaults to 100):
  80. Number of tokens to generate.
  81. top_k (`int`, *optional*, defaults to 0):
  82. Number of highest probability vocabulary tokens to keep for
  83. top-k-filtering that will be used by default in
  84. the `generate` method of the model.
  85. top_p (`float`, *optional*, defaults to 0.9):
  86. Value that will be used by default in the `generate` method of the model
  87. for `top_p`. If set to float < 1,
  88. only the most probable tokens with probabilities that add up to `top_p`
  89. or higher are kept for generation.
  90. temperature (`float`, *optional*, defaults to 1.0):
  91. The value used to module the next token probabilities that will be used
  92. by default in the `generate` method of the model. Must be strictly positive.
  93. """
  94. model_type = 'gpt3'
  95. def __init__(
  96. self,
  97. vocab_size=25600,
  98. hidden_size=768,
  99. ffn_hidden_size=None,
  100. num_hidden_layers=12,
  101. num_attention_heads=12,
  102. intermediate_size=3072,
  103. hidden_act='gelu',
  104. hidden_dropout_prob=0.1,
  105. attention_probs_dropout_prob=0.1,
  106. max_position_embeddings=2048,
  107. type_vocab_size=2,
  108. layernorm_epsilon=1e-12,
  109. bias_gelu_fusion=True,
  110. fp32_residual_connection=False,
  111. sequence_parallel=False,
  112. fp16=False,
  113. bf16=False,
  114. apply_query_key_layer_scaling=True,
  115. attention_softmax_in_fp32=False,
  116. kv_channels=None,
  117. masked_softmax_fusion=True,
  118. attention_dropout=0.1,
  119. bias_dropout_fusion=True,
  120. apply_residual_connection_post_layernorm=False,
  121. hidden_dropout=0.1,
  122. init_method_std=0.02,
  123. # generate
  124. eod_id=1,
  125. tokens_to_generate=100,
  126. top_k=0,
  127. top_p=0.9,
  128. temperature=1.0,
  129. **kwargs):
  130. super().__init__(layer_norm_eps=layernorm_epsilon, **kwargs)
  131. self.vocab_size = vocab_size
  132. self.hidden_size = hidden_size
  133. self.ffn_hidden_size = 4 * hidden_size \
  134. if ffn_hidden_size is None else ffn_hidden_size
  135. self.num_hidden_layers = num_hidden_layers
  136. self.num_attention_heads = num_attention_heads
  137. self.hidden_act = hidden_act
  138. self.intermediate_size = intermediate_size
  139. self.hidden_dropout_prob = hidden_dropout_prob
  140. self.attention_probs_dropout_prob = attention_probs_dropout_prob
  141. self.max_position_embeddings = max_position_embeddings
  142. self.type_vocab_size = type_vocab_size
  143. self.layernorm_epsilon = layernorm_epsilon
  144. self.bias_gelu_fusion = bias_gelu_fusion
  145. self.fp32_residual_connection = fp32_residual_connection
  146. self.sequence_parallel = sequence_parallel
  147. self.fp16 = fp16
  148. self.bf16 = bf16
  149. assert not (fp16 and bf16)
  150. self.apply_query_key_layer_scaling = apply_query_key_layer_scaling
  151. self.attention_softmax_in_fp32 = attention_softmax_in_fp32
  152. if kv_channels is None:
  153. assert hidden_size % num_attention_heads == 0
  154. self.kv_channels = hidden_size // num_attention_heads
  155. self.masked_softmax_fusion = masked_softmax_fusion
  156. self.attention_dropout = attention_dropout
  157. self.bias_dropout_fusion = bias_dropout_fusion
  158. self.apply_residual_connection_post_layernorm = \
  159. apply_residual_connection_post_layernorm
  160. self.hidden_dropout = hidden_dropout
  161. self.init_method_std = init_method_std
  162. self.eod_id = eod_id
  163. self.tokens_to_generate = tokens_to_generate
  164. self.top_k = top_k
  165. self.top_p = top_p
  166. self.temperature = temperature
  167. TORCH_MAJOR = int(torch.__version__.split('.')[0])
  168. TORCH_MINOR = int(torch.__version__.split('.')[1])
  169. self.no_persist_layer_norm = \
  170. TORCH_MAJOR < 1 or (TORCH_MAJOR == 1 and TORCH_MINOR < 11)
  171. @property
  172. def params_dtype(self):
  173. if self.fp16:
  174. return torch.half
  175. elif self.bf16:
  176. return torch.bfloat16
  177. else:
  178. return torch.float