configuration_gptj.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # coding=utf-8
  2. # Copyright 2021 The EleutherAI and HuggingFace Teams. All rights reserved.
  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. """GPT-J model configuration"""
  16. from collections import OrderedDict
  17. from collections.abc import Mapping
  18. from typing import Any, Optional
  19. from ... import PreTrainedTokenizer, TensorType, is_torch_available
  20. from ...configuration_utils import PretrainedConfig
  21. from ...onnx import OnnxConfigWithPast, PatchingSpec
  22. from ...utils import logging
  23. logger = logging.get_logger(__name__)
  24. class GPTJConfig(PretrainedConfig):
  25. r"""
  26. This is the configuration class to store the configuration of a [`GPTJModel`]. It is used to instantiate a GPT-J
  27. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  28. defaults will yield a similar configuration to that of the GPT-J
  29. [EleutherAI/gpt-j-6B](https://huggingface.co/EleutherAI/gpt-j-6B) architecture. Configuration objects inherit from
  30. [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`]
  31. for more information.
  32. Args:
  33. vocab_size (`int`, *optional*, defaults to 50400):
  34. Vocabulary size of the GPT-J model. Defines the number of different tokens that can be represented by the
  35. `inputs_ids` passed when calling [`GPTJModel`].
  36. n_positions (`int`, *optional*, defaults to 2048):
  37. The maximum sequence length that this model might ever be used with. Typically set this to something large
  38. just in case (e.g., 512 or 1024 or 2048).
  39. n_embd (`int`, *optional*, defaults to 4096):
  40. Dimensionality of the embeddings and hidden states.
  41. n_layer (`int`, *optional*, defaults to 28):
  42. Number of hidden layers in the Transformer encoder.
  43. n_head (`int`, *optional*, defaults to 16):
  44. Number of attention heads for each attention layer in the Transformer encoder.
  45. rotary_dim (`int`, *optional*, defaults to 64):
  46. Number of dimensions in the embedding that Rotary Position Embedding is applied to.
  47. n_inner (`int`, *optional*, defaults to None):
  48. Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
  49. activation_function (`str`, *optional*, defaults to `"gelu_new"`):
  50. Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
  51. resid_pdrop (`float`, *optional*, defaults to 0.1):
  52. The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
  53. embd_pdrop (`int`, *optional*, defaults to 0.1):
  54. The dropout ratio for the embeddings.
  55. attn_pdrop (`float`, *optional*, defaults to 0.1):
  56. The dropout ratio for the attention.
  57. layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
  58. The epsilon to use in the layer normalization layers.
  59. initializer_range (`float`, *optional*, defaults to 0.02):
  60. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  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. Example:
  64. ```python
  65. >>> from transformers import GPTJModel, GPTJConfig
  66. >>> # Initializing a GPT-J 6B configuration
  67. >>> configuration = GPTJConfig()
  68. >>> # Initializing a model from the configuration
  69. >>> model = GPTJModel(configuration)
  70. >>> # Accessing the model configuration
  71. >>> configuration = model.config
  72. ```"""
  73. model_type = "gptj"
  74. attribute_map = {
  75. "max_position_embeddings": "n_positions",
  76. "hidden_size": "n_embd",
  77. "num_attention_heads": "n_head",
  78. "num_hidden_layers": "n_layer",
  79. }
  80. def __init__(
  81. self,
  82. vocab_size=50400,
  83. n_positions=2048,
  84. n_embd=4096,
  85. n_layer=28,
  86. n_head=16,
  87. rotary_dim=64,
  88. n_inner=None,
  89. activation_function="gelu_new",
  90. resid_pdrop=0.0,
  91. embd_pdrop=0.0,
  92. attn_pdrop=0.0,
  93. layer_norm_epsilon=1e-5,
  94. initializer_range=0.02,
  95. use_cache=True,
  96. bos_token_id=50256,
  97. eos_token_id=50256,
  98. tie_word_embeddings=False,
  99. **kwargs,
  100. ):
  101. self.vocab_size = vocab_size
  102. self.n_positions = n_positions
  103. self.n_embd = n_embd
  104. self.n_layer = n_layer
  105. self.n_head = n_head
  106. self.n_inner = n_inner
  107. self.rotary_dim = rotary_dim
  108. self.activation_function = activation_function
  109. self.resid_pdrop = resid_pdrop
  110. self.embd_pdrop = embd_pdrop
  111. self.attn_pdrop = attn_pdrop
  112. self.layer_norm_epsilon = layer_norm_epsilon
  113. self.initializer_range = initializer_range
  114. self.use_cache = use_cache
  115. self.bos_token_id = bos_token_id
  116. self.eos_token_id = eos_token_id
  117. super().__init__(
  118. bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
  119. )
  120. # Copied from transformers.models.gpt2.configuration_gpt2.GPT2OnnxConfig
  121. class GPTJOnnxConfig(OnnxConfigWithPast):
  122. def __init__(
  123. self,
  124. config: PretrainedConfig,
  125. task: str = "default",
  126. patching_specs: Optional[list[PatchingSpec]] = None,
  127. use_past: bool = False,
  128. ):
  129. super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
  130. if not getattr(self._config, "pad_token_id", None):
  131. # TODO: how to do that better?
  132. self._config.pad_token_id = 0
  133. @property
  134. def inputs(self) -> Mapping[str, Mapping[int, str]]:
  135. common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
  136. if self.use_past:
  137. self.fill_with_past_key_values_(common_inputs, direction="inputs")
  138. common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
  139. else:
  140. common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
  141. return common_inputs
  142. @property
  143. def num_layers(self) -> int:
  144. return self._config.n_layer
  145. @property
  146. def num_attention_heads(self) -> int:
  147. return self._config.n_head
  148. def generate_dummy_inputs(
  149. self,
  150. tokenizer: PreTrainedTokenizer,
  151. batch_size: int = -1,
  152. seq_length: int = -1,
  153. is_pair: bool = False,
  154. framework: Optional[TensorType] = None,
  155. ) -> Mapping[str, Any]:
  156. common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
  157. tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
  158. )
  159. # We need to order the input in the way they appears in the forward()
  160. ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
  161. # Need to add the past_keys
  162. if self.use_past:
  163. if not is_torch_available():
  164. raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
  165. else:
  166. import torch
  167. batch, seqlen = common_inputs["input_ids"].shape
  168. # Not using the same length for past_key_values
  169. past_key_values_length = seqlen + 2
  170. past_shape = (
  171. batch,
  172. self.num_attention_heads,
  173. past_key_values_length,
  174. self._config.hidden_size // self.num_attention_heads,
  175. )
  176. ordered_inputs["past_key_values"] = [
  177. (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
  178. ]
  179. ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
  180. if self.use_past:
  181. mask_dtype = ordered_inputs["attention_mask"].dtype
  182. ordered_inputs["attention_mask"] = torch.cat(
  183. [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
  184. )
  185. return ordered_inputs
  186. @property
  187. def default_onnx_opset(self) -> int:
  188. return 13
  189. __all__ = ["GPTJConfig", "GPTJOnnxConfig"]