configuration_starcoder2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. # coding=utf-8
  2. # Copyright 2024 BigCode and the HuggingFace Inc. team. 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. """Starcoder2 model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...modeling_rope_utils import rope_config_validation
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class Starcoder2Config(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`Starcoder2Model`]. It is used to instantiate a
  23. Starcoder2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
  24. with the defaults will yield a similar configuration to that of the [bigcode/starcoder2-7b](https://huggingface.co/bigcode/starcoder2-7b) model.
  25. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  26. documentation from [`PretrainedConfig`] for more information.
  27. Args:
  28. vocab_size (`int`, *optional*, defaults to 49152):
  29. Vocabulary size of the Starcoder2 model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`Starcoder2Model`]
  31. hidden_size (`int`, *optional*, defaults to 3072):
  32. Dimension of the hidden representations.
  33. intermediate_size (`int`, *optional*, defaults to 12288):
  34. Dimension of the MLP representations.
  35. num_hidden_layers (`int`, *optional*, defaults to 30):
  36. Number of hidden layers in the Transformer encoder.
  37. num_attention_heads (`int`, *optional*, defaults to 24):
  38. Number of attention heads for each attention layer in the Transformer encoder.
  39. num_key_value_heads (`int`, *optional*, defaults to 2):
  40. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  41. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  42. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  43. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  44. by meanpooling all the original heads within that group. For more details, check out [this
  45. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `8`.
  46. hidden_act (`str` or `function`, *optional*, defaults to `"gelu_pytorch_tanh"`):
  47. The non-linear activation function (function or string) in the decoder.
  48. max_position_embeddings (`int`, *optional*, defaults to 4096):
  49. The maximum sequence length that this model might ever be used with. Starcoder2's sliding window attention
  50. allows sequence of up to 4096*32 tokens.
  51. initializer_range (`float`, *optional*, defaults to 0.02):
  52. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  53. norm_epsilon (`float`, *optional*, defaults to 1e-05):
  54. Epsilon value for the layer norm
  55. use_cache (`bool`, *optional*, defaults to `True`):
  56. Whether or not the model should return the last key/values attentions (not used by all models). Only
  57. relevant if `config.is_decoder=True`.
  58. bos_token_id (`int`, *optional*, defaults to 50256):
  59. The id of the "beginning-of-sequence" token.
  60. eos_token_id (`int`, *optional*, defaults to 50256):
  61. The id of the "end-of-sequence" token.
  62. rope_theta (`float`, *optional*, defaults to 10000.0):
  63. The base period of the RoPE embeddings.
  64. rope_scaling (`Dict`, *optional*):
  65. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  66. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  67. accordingly.
  68. Expected contents:
  69. `rope_type` (`str`):
  70. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  71. 'llama3'], with 'default' being the original RoPE implementation.
  72. `factor` (`float`, *optional*):
  73. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  74. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  75. original maximum pre-trained length.
  76. `original_max_position_embeddings` (`int`, *optional*):
  77. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  78. pretraining.
  79. `attention_factor` (`float`, *optional*):
  80. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  81. computation. If unspecified, it defaults to value recommended by the implementation, using the
  82. `factor` field to infer the suggested value.
  83. `beta_fast` (`float`, *optional*):
  84. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  85. ramp function. If unspecified, it defaults to 32.
  86. `beta_slow` (`float`, *optional*):
  87. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  88. ramp function. If unspecified, it defaults to 1.
  89. `short_factor` (`list[float]`, *optional*):
  90. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  91. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  92. size divided by the number of attention heads divided by 2
  93. `long_factor` (`list[float]`, *optional*):
  94. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  95. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  96. size divided by the number of attention heads divided by 2
  97. `low_freq_factor` (`float`, *optional*):
  98. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  99. `high_freq_factor` (`float`, *optional*):
  100. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  101. sliding_window (`int`, *optional*):
  102. Sliding window attention window size. If not specified, will default to `None` (no sliding window).
  103. attention_dropout (`float`, *optional*, defaults to 0.0):
  104. The dropout ratio for the attention probabilities.
  105. residual_dropout (`float`, *optional*, defaults to 0.0):
  106. Residual connection dropout value.
  107. embedding_dropout (`float`, *optional*, defaults to 0.0):
  108. Embedding dropout.
  109. use_bias (`bool`, *optional*, defaults to `True`):
  110. Whether to use bias term on linear layers of the model.
  111. ```python
  112. >>> from transformers import Starcoder2Model, Starcoder2Config
  113. >>> # Initializing a Starcoder2 7B style configuration
  114. >>> configuration = Starcoder2Config()
  115. >>> # Initializing a model from the Starcoder2 7B style configuration
  116. >>> model = Starcoder2Model(configuration)
  117. >>> # Accessing the model configuration
  118. >>> configuration = model.config
  119. ```"""
  120. model_type = "starcoder2"
  121. keys_to_ignore_at_inference = ["past_key_values"]
  122. # Default tensor parallel plan for base model `Starcoder2`
  123. base_model_tp_plan = {
  124. "layers.*.self_attn.q_proj": "colwise",
  125. "layers.*.self_attn.k_proj": "colwise",
  126. "layers.*.self_attn.v_proj": "colwise",
  127. "layers.*.self_attn.o_proj": "rowwise",
  128. "layers.*.mlp.c_fc": "colwise",
  129. "layers.*.mlp.c_proj": "rowwise",
  130. }
  131. base_model_pp_plan = {
  132. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  133. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  134. "norm": (["hidden_states"], ["hidden_states"]),
  135. }
  136. def __init__(
  137. self,
  138. vocab_size=49152,
  139. hidden_size=3072,
  140. intermediate_size=12288,
  141. num_hidden_layers=30,
  142. num_attention_heads=24,
  143. num_key_value_heads=2,
  144. hidden_act="gelu_pytorch_tanh",
  145. max_position_embeddings=4096,
  146. initializer_range=0.018042,
  147. norm_epsilon=1e-5,
  148. use_cache=True,
  149. bos_token_id=50256,
  150. eos_token_id=50256,
  151. rope_theta=10000.0,
  152. rope_scaling=None,
  153. sliding_window=None,
  154. attention_dropout=0.0,
  155. residual_dropout=0.0,
  156. embedding_dropout=0.0,
  157. use_bias=True,
  158. **kwargs,
  159. ):
  160. self.vocab_size = vocab_size
  161. self.max_position_embeddings = max_position_embeddings
  162. self.hidden_size = hidden_size
  163. self.intermediate_size = intermediate_size
  164. self.num_hidden_layers = num_hidden_layers
  165. self.num_attention_heads = num_attention_heads
  166. self.sliding_window = sliding_window
  167. self.use_bias = use_bias
  168. self.num_key_value_heads = num_key_value_heads
  169. self.hidden_act = hidden_act
  170. self.initializer_range = initializer_range
  171. self.norm_epsilon = norm_epsilon
  172. self.use_cache = use_cache
  173. self.rope_theta = rope_theta
  174. self.rope_scaling = rope_scaling
  175. self.attention_dropout = attention_dropout
  176. self.residual_dropout = residual_dropout
  177. self.embedding_dropout = embedding_dropout
  178. # Validate the correctness of rotary position embeddings parameters
  179. # BC: if there is a 'type' field, move it to 'rope_type'.
  180. if self.rope_scaling is not None and "type" in self.rope_scaling:
  181. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  182. rope_config_validation(self)
  183. super().__init__(
  184. bos_token_id=bos_token_id,
  185. eos_token_id=eos_token_id,
  186. **kwargs,
  187. )
  188. __all__ = ["Starcoder2Config"]