configuration_gpt2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. # coding=utf-8
  2. # Copyright 2018 The OpenAI Team Authors and HuggingFace Inc. team.
  3. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """OpenAI GPT-2 configuration"""
  17. from collections import OrderedDict
  18. from collections.abc import Mapping
  19. from typing import Any, Optional
  20. from ... import PreTrainedTokenizer, TensorType, is_torch_available
  21. from ...configuration_utils import PretrainedConfig
  22. from ...onnx import OnnxConfigWithPast, PatchingSpec
  23. from ...utils import logging
  24. logger = logging.get_logger(__name__)
  25. class GPT2Config(PretrainedConfig):
  26. """
  27. This is the configuration class to store the configuration of a [`GPT2Model`] or a [`TFGPT2Model`]. It is used to
  28. instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a
  29. configuration with the defaults will yield a similar configuration to that of the GPT-2
  30. [openai-community/gpt2](https://huggingface.co/openai-community/gpt2) architecture.
  31. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  32. documentation from [`PretrainedConfig`] for more information.
  33. Args:
  34. vocab_size (`int`, *optional*, defaults to 50257):
  35. Vocabulary size of the GPT-2 model. Defines the number of different tokens that can be represented by the
  36. `inputs_ids` passed when calling [`GPT2Model`] or [`TFGPT2Model`].
  37. n_positions (`int`, *optional*, defaults to 1024):
  38. The maximum sequence length that this model might ever be used with. Typically set this to something large
  39. just in case (e.g., 512 or 1024 or 2048).
  40. n_embd (`int`, *optional*, defaults to 768):
  41. Dimensionality of the embeddings and hidden states.
  42. n_layer (`int`, *optional*, defaults to 12):
  43. Number of hidden layers in the Transformer encoder.
  44. n_head (`int`, *optional*, defaults to 12):
  45. Number of attention heads for each attention layer in the Transformer encoder.
  46. n_inner (`int`, *optional*):
  47. Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
  48. activation_function (`str`, *optional*, defaults to `"gelu_new"`):
  49. Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
  50. resid_pdrop (`float`, *optional*, defaults to 0.1):
  51. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  52. embd_pdrop (`float`, *optional*, defaults to 0.1):
  53. The dropout ratio for the embeddings.
  54. attn_pdrop (`float`, *optional*, defaults to 0.1):
  55. The dropout ratio for the attention.
  56. layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
  57. The epsilon to use in the layer normalization layers.
  58. initializer_range (`float`, *optional*, defaults to 0.02):
  59. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  60. summary_type (`string`, *optional*, defaults to `"cls_index"`):
  61. Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
  62. [`TFGPT2DoubleHeadsModel`].
  63. Has to be one of the following options:
  64. - `"last"`: Take the last token hidden state (like XLNet).
  65. - `"first"`: Take the first token hidden state (like BERT).
  66. - `"mean"`: Take the mean of all tokens hidden states.
  67. - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
  68. - `"attn"`: Not implemented now, use multi-head attention.
  69. summary_use_proj (`bool`, *optional*, defaults to `True`):
  70. Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
  71. [`TFGPT2DoubleHeadsModel`].
  72. Whether or not to add a projection after the vector extraction.
  73. summary_activation (`str`, *optional*):
  74. Argument used when doing sequence summary. Used in for the multiple choice head in
  75. [`GPT2DoubleHeadsModel`].
  76. Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
  77. summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
  78. Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
  79. [`TFGPT2DoubleHeadsModel`].
  80. Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
  81. summary_first_dropout (`float`, *optional*, defaults to 0.1):
  82. Argument used when doing sequence summary, used in the models [`GPT2DoubleHeadsModel`] and
  83. [`TFGPT2DoubleHeadsModel`].
  84. The dropout ratio to be used after the projection and activation.
  85. scale_attn_weights (`bool`, *optional*, defaults to `True`):
  86. Scale attention weights by dividing by sqrt(hidden_size)..
  87. use_cache (`bool`, *optional*, defaults to `True`):
  88. Whether or not the model should return the last key/values attentions (not used by all models).
  89. bos_token_id (`int`, *optional*, defaults to 50256):
  90. Id of the beginning of sentence token in the vocabulary.
  91. eos_token_id (`int`, *optional*, defaults to 50256):
  92. Id of the end of sentence token in the vocabulary.
  93. scale_attn_by_inverse_layer_idx (`bool`, *optional*, defaults to `False`):
  94. Whether to additionally scale attention weights by `1 / layer_idx + 1`.
  95. reorder_and_upcast_attn (`bool`, *optional*, defaults to `False`):
  96. Whether to scale keys (K) prior to computing attention (dot-product) and upcast attention
  97. dot-product/softmax to float() when training with mixed precision.
  98. Example:
  99. ```python
  100. >>> from transformers import GPT2Config, GPT2Model
  101. >>> # Initializing a GPT2 configuration
  102. >>> configuration = GPT2Config()
  103. >>> # Initializing a model (with random weights) from the configuration
  104. >>> model = GPT2Model(configuration)
  105. >>> # Accessing the model configuration
  106. >>> configuration = model.config
  107. ```"""
  108. model_type = "gpt2"
  109. keys_to_ignore_at_inference = ["past_key_values"]
  110. attribute_map = {
  111. "hidden_size": "n_embd",
  112. "max_position_embeddings": "n_positions",
  113. "num_attention_heads": "n_head",
  114. "num_hidden_layers": "n_layer",
  115. }
  116. def __init__(
  117. self,
  118. vocab_size=50257,
  119. n_positions=1024,
  120. n_embd=768,
  121. n_layer=12,
  122. n_head=12,
  123. n_inner=None,
  124. activation_function="gelu_new",
  125. resid_pdrop=0.1,
  126. embd_pdrop=0.1,
  127. attn_pdrop=0.1,
  128. layer_norm_epsilon=1e-5,
  129. initializer_range=0.02,
  130. summary_type="cls_index",
  131. summary_use_proj=True,
  132. summary_activation=None,
  133. summary_proj_to_labels=True,
  134. summary_first_dropout=0.1,
  135. scale_attn_weights=True,
  136. use_cache=True,
  137. bos_token_id=50256,
  138. eos_token_id=50256,
  139. scale_attn_by_inverse_layer_idx=False,
  140. reorder_and_upcast_attn=False,
  141. **kwargs,
  142. ):
  143. self.vocab_size = vocab_size
  144. self.n_positions = n_positions
  145. self.n_embd = n_embd
  146. self.n_layer = n_layer
  147. self.n_head = n_head
  148. self.n_inner = n_inner
  149. self.activation_function = activation_function
  150. self.resid_pdrop = resid_pdrop
  151. self.embd_pdrop = embd_pdrop
  152. self.attn_pdrop = attn_pdrop
  153. self.layer_norm_epsilon = layer_norm_epsilon
  154. self.initializer_range = initializer_range
  155. self.summary_type = summary_type
  156. self.summary_use_proj = summary_use_proj
  157. self.summary_activation = summary_activation
  158. self.summary_first_dropout = summary_first_dropout
  159. self.summary_proj_to_labels = summary_proj_to_labels
  160. self.scale_attn_weights = scale_attn_weights
  161. self.use_cache = use_cache
  162. self.scale_attn_by_inverse_layer_idx = scale_attn_by_inverse_layer_idx
  163. self.reorder_and_upcast_attn = reorder_and_upcast_attn
  164. self.bos_token_id = bos_token_id
  165. self.eos_token_id = eos_token_id
  166. super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
  167. class GPT2OnnxConfig(OnnxConfigWithPast):
  168. def __init__(
  169. self,
  170. config: PretrainedConfig,
  171. task: str = "default",
  172. patching_specs: Optional[list[PatchingSpec]] = None,
  173. use_past: bool = False,
  174. ):
  175. super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
  176. if not getattr(self._config, "pad_token_id", None):
  177. # TODO: how to do that better?
  178. self._config.pad_token_id = 0
  179. @property
  180. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  181. common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
  182. if self.use_past:
  183. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  184. common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
  185. else:
  186. common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
  187. return common_inputs
  188. @property
  189. def num_layers(self) -> int:
  190. return self._config.n_layer
  191. @property
  192. def num_attention_heads(self) -> int:
  193. return self._config.n_head
  194. def generate_dummy_inputs(
  195. self,
  196. tokenizer: PreTrainedTokenizer,
  197. batch_size: int = -1,
  198. seq_length: int = -1,
  199. is_pair: bool = False,
  200. framework: Optional[TensorType] = None,
  201. ) -> Mapping[str, Any]:
  202. common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
  203. tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
  204. )
  205. # We need to order the input in the way they appears in the forward()
  206. ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
  207. # Need to add the past_keys
  208. if self.use_past:
  209. if not is_torch_available():
  210. raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
  211. else:
  212. import torch
  213. batch, seqlen = common_inputs["input_ids"].shape
  214. # Not using the same length for past_key_values
  215. past_key_values_length = seqlen + 2
  216. past_shape = (
  217. batch,
  218. self.num_attention_heads,
  219. past_key_values_length,
  220. self._config.hidden_size // self.num_attention_heads,
  221. )
  222. ordered_inputs["past_key_values"] = [
  223. (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
  224. ]
  225. ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
  226. if self.use_past:
  227. mask_dtype = ordered_inputs["attention_mask"].dtype
  228. ordered_inputs["attention_mask"] = torch.cat(
  229. [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
  230. )
  231. return ordered_inputs
  232. @property
  233. def default_onnx_opset(self) -> int:
  234. return 13
  235. __all__ = ["GPT2Config", "GPT2OnnxConfig"]