configuration_stablelm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. # coding=utf-8
  2. # Copyright 2024 Stability AI 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. """StableLM 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 StableLmConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`~StableLmModel`].
  23. It is used to instantiate an StableLM model according to the specified arguments, defining the model
  24. architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
  25. the StableLM [stabilityai/stablelm-3b-4e1t](https://huggingface.co/stabilityai/stablelm-3b-4e1t) architecture.
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used
  27. to control the model outputs. Read the documentation from [`PretrainedConfig`]
  28. for more information.
  29. Args:
  30. vocab_size (`int`, *optional*, defaults to 50304):
  31. Vocabulary size of the StableLM model. Defines the number of different tokens that
  32. can be represented by the `inputs_ids` passed when calling [`StableLmModel`].
  33. intermediate_size (`int`, *optional*, defaults to 6912):
  34. Dimension of the MLP representations.
  35. hidden_size (`int`, *optional*, defaults to 2560):
  36. Number of hidden layers in the Transformer decoder.
  37. num_hidden_layers (`int`, *optional*, defaults to 32):
  38. Number of hidden layers in the Transformer decoder.
  39. num_attention_heads (`int`, *optional*, defaults to 32):
  40. Number of attention heads for each attention layer in the Transformer encoder.
  41. num_key_value_heads (`int`, *optional*, defaults to 32):
  42. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  43. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  44. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  45. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  46. by meanpooling all the original heads within that group. For more details, check out [this
  47. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  48. `num_attention_heads`.
  49. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  50. The non-linear activation function (function or string).
  51. max_position_embeddings (`int`, *optional*, defaults to 4096):
  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 1024 or 2048).
  54. initializer_range (`float`, *optional*, defaults to 0.02):
  55. The standard deviation of the truncated_normal_initializer for initializing
  56. all weight matrices.
  57. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  58. The epsilon used by the normalization layers.
  59. use_cache (`bool`, *optional*, defaults to `True`):
  60. Whether or not the model should return the last key/values attentions
  61. (not used by all models). Only relevant if `config.is_decoder=True`.
  62. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  63. Whether the model's input and output word embeddings should be tied.
  64. rope_theta (`float`, *optional*, defaults to `10000.0`):
  65. The base period of the RoPE embeddings.
  66. rope_scaling (`Dict`, *optional*):
  67. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  68. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  69. accordingly.
  70. Expected contents:
  71. `rope_type` (`str`):
  72. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  73. 'llama3'], with 'default' being the original RoPE implementation.
  74. `factor` (`float`, *optional*):
  75. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  76. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  77. original maximum pre-trained length.
  78. `original_max_position_embeddings` (`int`, *optional*):
  79. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  80. pretraining.
  81. `attention_factor` (`float`, *optional*):
  82. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  83. computation. If unspecified, it defaults to value recommended by the implementation, using the
  84. `factor` field to infer the suggested value.
  85. `beta_fast` (`float`, *optional*):
  86. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  87. ramp function. If unspecified, it defaults to 32.
  88. `beta_slow` (`float`, *optional*):
  89. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  90. ramp function. If unspecified, it defaults to 1.
  91. `short_factor` (`list[float]`, *optional*):
  92. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  93. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  94. size divided by the number of attention heads divided by 2
  95. `long_factor` (`list[float]`, *optional*):
  96. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  97. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  98. size divided by the number of attention heads divided by 2
  99. `low_freq_factor` (`float`, *optional*):
  100. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  101. `high_freq_factor` (`float`, *optional*):
  102. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  103. use_qkv_bias (`bool`, *optional*, defaults to `False`):
  104. Whether or not the model should use bias for qkv layers.
  105. qk_layernorm (`bool`, *optional*, defaults to `False`):
  106. Whether or not to normalize, per head, the Queries and Keys after projecting the hidden states.
  107. use_parallel_residual (`bool`, *optional*, defaults to `False`):
  108. Whether to use a "parallel" formulation in each Transformer layer, which can provide a slight training
  109. speedup at large scales.
  110. hidden_dropout (`float`, *optional*, defaults to 0.0):
  111. The dropout ratio after applying the MLP to the hidden states.
  112. attention_dropout (`float`, *optional*, defaults to 0.0):
  113. The dropout ratio for the attention probabilities.
  114. partial_rotary_factor (`float`, *optional*, defaults to 0.25):
  115. Percentage of the query and keys which will have rotary embedding.
  116. bos_token_id (int, *optional*, defaults to 0):
  117. The id of the `BOS` token in the vocabulary.
  118. eos_token_id (int, *optional*, defaults to 0):
  119. The id of the `EOS` token in the vocabulary.
  120. Example:
  121. ```python
  122. >>> from transformers import StableLmModel, StableLmConfig
  123. >>> # Initializing a StableLM stablelm-3b style configuration
  124. >>> configuration = StableLmConfig()
  125. ```"""
  126. model_type = "stablelm"
  127. keys_to_ignore_at_inference = ["past_key_values"]
  128. def __init__(
  129. self,
  130. vocab_size=50304,
  131. intermediate_size=6912,
  132. hidden_size=2560,
  133. num_hidden_layers=32,
  134. num_attention_heads=32,
  135. num_key_value_heads=32,
  136. hidden_act="silu",
  137. max_position_embeddings=4096,
  138. initializer_range=0.02,
  139. layer_norm_eps=1.0e-5,
  140. use_cache=True,
  141. tie_word_embeddings=False,
  142. rope_theta=10_000,
  143. rope_scaling=None,
  144. use_qkv_bias=False,
  145. qk_layernorm=False,
  146. use_parallel_residual=False,
  147. hidden_dropout=0.0,
  148. attention_dropout=0.0,
  149. partial_rotary_factor=0.25,
  150. bos_token_id=0,
  151. eos_token_id=0,
  152. **kwargs,
  153. ):
  154. self.vocab_size = vocab_size
  155. self.max_position_embeddings = max_position_embeddings
  156. self.hidden_size = hidden_size
  157. self.intermediate_size = intermediate_size
  158. self.num_hidden_layers = num_hidden_layers
  159. self.num_attention_heads = num_attention_heads
  160. self.num_key_value_heads = num_key_value_heads
  161. self.hidden_act = hidden_act
  162. self.initializer_range = initializer_range
  163. self.layer_norm_eps = layer_norm_eps
  164. self.use_cache = use_cache
  165. self.rope_theta = rope_theta
  166. self.rope_scaling = rope_scaling
  167. self.use_qkv_bias = use_qkv_bias
  168. self.qk_layernorm = qk_layernorm
  169. self.use_parallel_residual = use_parallel_residual
  170. self.hidden_dropout = hidden_dropout
  171. self.attention_dropout = attention_dropout
  172. self.partial_rotary_factor = partial_rotary_factor
  173. # Validate the correctness of rotary position embeddings parameters
  174. # BC: if there is a 'type' field, move it to 'rope_type'.
  175. if self.rope_scaling is not None and "type" in self.rope_scaling:
  176. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  177. rope_config_validation(self)
  178. super().__init__(
  179. bos_token_id=bos_token_id,
  180. eos_token_id=eos_token_id,
  181. tie_word_embeddings=tie_word_embeddings,
  182. **kwargs,
  183. )
  184. __all__ = ["StableLmConfig"]