configuration_codegen.py 9.3 KB

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