configuration_diffllama.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # coding=utf-8
  2. # Copyright 2024 weak-kajuma and the HuggingFace Inc. team. All rights reserved.
  3. #
  4. # This code is based on Llama implementations in this library and Microsoft's
  5. # Differential Transformer implementations.
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """DiffLlama model configuration"""
  18. from ...configuration_utils import PretrainedConfig
  19. from ...modeling_rope_utils import rope_config_validation
  20. class DiffLlamaConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`DiffLlamaModel`]. It is used to instantiate an DiffLlama
  23. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults
  24. will yield a similar configuration to that of the [kajuma/DiffLlama-0.3B-handcut](https://huggingface.co/kajuma/DiffLlama-0.3B-handcut).
  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 32000):
  29. Vocabulary size of the DiffLlama model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`DiffLlamaModel`]
  31. hidden_size (`int`, *optional*, defaults to 2048):
  32. Dimension of the hidden representations.
  33. intermediate_size (`int`, *optional*, defaults to 8192):
  34. Dimension of the MLP representations.
  35. num_hidden_layers (`int`, *optional*, defaults to 16):
  36. Number of hidden layers in the Transformer decoder.
  37. num_attention_heads (`int`, *optional*, defaults to 32):
  38. Number of attention heads for each attention layer in the Transformer decoder.
  39. num_key_value_heads (`int`, *optional*):
  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
  46. `num_attention_heads`.
  47. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  48. The non-linear activation function (function or string) in the decoder.
  49. max_position_embeddings (`int`, *optional*, defaults to 2048):
  50. The maximum sequence length that this model might ever be used with.
  51. initializer_range (`float`, *optional*, defaults to 0.02):
  52. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  53. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  54. The epsilon used by the rms normalization layers.
  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. pad_token_id (`int`, *optional*):
  59. Padding token id.
  60. bos_token_id (`int`, *optional*, defaults to 1):
  61. Beginning of stream token id.
  62. eos_token_id (`int`, *optional*, defaults to 2):
  63. End of stream token id.
  64. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  65. Whether to tie weight embeddings
  66. rope_theta (`float`, *optional*, defaults to 10000.0):
  67. The base period of the RoPE embeddings.
  68. rope_scaling (`Dict`, *optional*):
  69. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  70. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  71. accordingly.
  72. Expected contents:
  73. `rope_type` (`str`):
  74. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  75. 'diffllama3'], with 'default' being the original RoPE implementation.
  76. `factor` (`float`, *optional*):
  77. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  78. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  79. original maximum pre-trained length.
  80. `original_max_position_embeddings` (`int`, *optional*):
  81. Used with 'dynamic', 'longrope' and 'diffllama3'. The original max position embeddings used during
  82. pretraining.
  83. `attention_factor` (`float`, *optional*):
  84. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  85. computation. If unspecified, it defaults to value recommended by the implementation, using the
  86. `factor` field to infer the suggested value.
  87. `beta_fast` (`float`, *optional*):
  88. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  89. ramp function. If unspecified, it defaults to 32.
  90. `beta_slow` (`float`, *optional*):
  91. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  92. ramp function. If unspecified, it defaults to 1.
  93. `short_factor` (`list[float]`, *optional*):
  94. Only used with 'longrope'. The scaling factor to be applied to short 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. `long_factor` (`list[float]`, *optional*):
  98. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  99. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  100. size divided by the number of attention heads divided by 2
  101. `low_freq_factor` (`float`, *optional*):
  102. Only used with 'diffllama3'. Scaling factor applied to low frequency components of the RoPE
  103. `high_freq_factor` (`float`, *optional*):
  104. Only used with 'diffllama3'. Scaling factor applied to high frequency components of the RoPE
  105. attention_bias (`bool`, *optional*, defaults to `False`):
  106. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  107. attention_dropout (`float`, *optional*, defaults to 0.0):
  108. The dropout ratio for the attention probabilities.
  109. lambda_std_dev (`float`, *optional*, defaults to 0.1):
  110. The standard deviation for initialization of parameter lambda in attention layer.
  111. head_dim (`int`, *optional*):
  112. The attention head dimension. If None, it will default to hidden_size // num_heads
  113. ```python
  114. >>> from transformers import DiffLlamaModel, DiffLlamaConfig
  115. >>> # Initializing a DiffLlama diffllama-7b style configuration
  116. >>> configuration = DiffLlamaConfig()
  117. >>> # Initializing a model from the diffllama-7b style configuration
  118. >>> model = DiffLlamaModel(configuration)
  119. >>> # Accessing the model configuration
  120. >>> configuration = model.config
  121. ```"""
  122. model_type = "diffllama"
  123. keys_to_ignore_at_inference = ["past_key_values"]
  124. def __init__(
  125. self,
  126. vocab_size=32000,
  127. hidden_size=2048,
  128. intermediate_size=8192,
  129. num_hidden_layers=16,
  130. num_attention_heads=32,
  131. num_key_value_heads=None,
  132. hidden_act="silu",
  133. max_position_embeddings=2048,
  134. initializer_range=0.02,
  135. rms_norm_eps=1e-5,
  136. use_cache=True,
  137. pad_token_id=None,
  138. bos_token_id=1,
  139. eos_token_id=2,
  140. tie_word_embeddings=False,
  141. rope_theta=10000.0,
  142. rope_scaling=None,
  143. attention_bias=False,
  144. attention_dropout=0.0,
  145. lambda_std_dev=0.1,
  146. head_dim=None,
  147. **kwargs,
  148. ):
  149. self.vocab_size = vocab_size
  150. self.max_position_embeddings = max_position_embeddings
  151. self.hidden_size = hidden_size
  152. self.intermediate_size = intermediate_size
  153. self.num_hidden_layers = num_hidden_layers
  154. self.num_attention_heads = num_attention_heads
  155. # for backward compatibility
  156. if num_key_value_heads is None:
  157. num_key_value_heads = num_attention_heads
  158. self.num_key_value_heads = num_key_value_heads
  159. self.hidden_act = hidden_act
  160. self.initializer_range = initializer_range
  161. self.rms_norm_eps = rms_norm_eps
  162. self.use_cache = use_cache
  163. self.rope_theta = rope_theta
  164. self.rope_scaling = rope_scaling
  165. self.attention_bias = attention_bias
  166. self.attention_dropout = attention_dropout
  167. self.lambda_std_dev = lambda_std_dev
  168. self.head_dim = head_dim if head_dim is not None else self.hidden_size // self.num_attention_heads
  169. # Validate the correctness of rotary position embeddings parameters
  170. # BC: if there is a 'type' field, copy it it to 'rope_type'.
  171. if self.rope_scaling is not None and "type" in self.rope_scaling:
  172. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  173. rope_config_validation(self)
  174. super().__init__(
  175. pad_token_id=pad_token_id,
  176. bos_token_id=bos_token_id,
  177. eos_token_id=eos_token_id,
  178. tie_word_embeddings=tie_word_embeddings,
  179. **kwargs,
  180. )
  181. __all__ = ["DiffLlamaConfig"]