configuration_cohere2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/cohere2/modular_cohere2.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_cohere2.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2024 Cohere Inc. HuggingFace Inc. team. All rights reserved.
  9. #
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License");
  12. # you may not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS,
  19. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. from ...configuration_utils import PretrainedConfig, layer_type_validation
  23. from ...modeling_rope_utils import rope_config_validation
  24. class Cohere2Config(PretrainedConfig):
  25. r"""
  26. This is the configuration class to store the configuration of a [`CohereModel`]. It is used to instantiate an Cohere
  27. model according to the specified arguments, defining the model architecture.
  28. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  29. documentation from [`PretrainedConfig`] for more information. Instantiating a configuration
  30. with the defaults will yield a similar configuration to that of the [CohereForAI/c4ai-command-r-v01](https://huggingface.co/CohereForAI/c4ai-command-r-v01) model.
  31. Args:
  32. vocab_size (`int`, *optional*, defaults to 256000):
  33. Vocabulary size of the Cohere model. Defines the number of different tokens that can be represented by the
  34. `inputs_ids` passed when calling [`CohereModel`]
  35. hidden_size (`int`, *optional*, defaults to 8192):
  36. Dimension of the hidden representations.
  37. intermediate_size (`int`, *optional*, defaults to 22528):
  38. Dimension of the MLP representations.
  39. logit_scale (`float`, *optional*, defaults to 0.0625):
  40. The scaling factor for the output logits.
  41. num_hidden_layers (`int`, *optional*, defaults to 40):
  42. Number of hidden layers in the Transformer decoder.
  43. num_attention_heads (`int`, *optional*, defaults to 64):
  44. Number of attention heads for each attention layer in the Transformer decoder.
  45. num_key_value_heads (`int`, *optional*):
  46. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  47. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  48. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  49. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  50. by meanpooling all the original heads within that group. For more details, check out [this
  51. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  52. `num_attention_heads`.
  53. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  54. The non-linear activation function (function or string) in the decoder.
  55. max_position_embeddings (`int`, *optional*, defaults to 8192):
  56. The maximum sequence length that this model might ever be used with.
  57. initializer_range (`float`, *optional*, defaults to 0.02):
  58. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  59. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  60. The epsilon used by the layer normalization.
  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). Only
  63. relevant if `config.is_decoder=True`.
  64. pad_token_id (`int`, *optional*, defaults to 0):
  65. Padding token id.
  66. bos_token_id (`int`, *optional*, defaults to 5):
  67. Beginning of stream token id.
  68. eos_token_id (`int`, *optional*, defaults to 255001):
  69. End of stream token id.
  70. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  71. Whether to tie weight embeddings
  72. rope_theta (`float`, *optional*, defaults to 10000.0):
  73. The base period of the RoPE embeddings.
  74. rope_scaling (`Dict`, *optional*):
  75. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  76. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  77. accordingly.
  78. Expected contents:
  79. `rope_type` (`str`):
  80. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  81. 'llama3'], with 'default' being the original RoPE implementation.
  82. `factor` (`float`, *optional*):
  83. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  84. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  85. original maximum pre-trained length.
  86. `original_max_position_embeddings` (`int`, *optional*):
  87. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  88. pretraining.
  89. `attention_factor` (`float`, *optional*):
  90. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  91. computation. If unspecified, it defaults to value recommended by the implementation, using the
  92. `factor` field to infer the suggested value.
  93. `beta_fast` (`float`, *optional*):
  94. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  95. ramp function. If unspecified, it defaults to 32.
  96. `beta_slow` (`float`, *optional*):
  97. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  98. ramp function. If unspecified, it defaults to 1.
  99. `short_factor` (`list[float]`, *optional*):
  100. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  101. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  102. size divided by the number of attention heads divided by 2
  103. `long_factor` (`list[float]`, *optional*):
  104. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  105. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  106. size divided by the number of attention heads divided by 2
  107. `low_freq_factor` (`float`, *optional*):
  108. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  109. `high_freq_factor` (`float`, *optional*):
  110. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  111. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
  112. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  113. attention_dropout (`float`, *optional*, defaults to 0.0):
  114. The dropout ratio for the attention probabilities.
  115. sliding_window (`int`, *optional*, defaults to 4096):
  116. Size of the sliding window attention context.
  117. layer_types (`list`, *optional*):
  118. Attention pattern for each layer.
  119. ```python
  120. >>> from transformers import Cohere2Model, Cohere2Config
  121. >>> # Initializing a Cohere Nextmodel configuration
  122. >>> configuration = Cohere2Config()
  123. >>> # Initializing a model from the Cohere2 configuration
  124. >>> model = Cohere2Model(configuration) # doctest: +SKIP
  125. >>> # Accessing the model configuration
  126. >>> configuration = model.config # doctest: +SKIP
  127. ```
  128. """
  129. model_type = "cohere2"
  130. keys_to_ignore_at_inference = ["past_key_values"]
  131. base_model_tp_plan = {
  132. "layers.*.self_attn.q_proj": "colwise",
  133. "layers.*.self_attn.k_proj": "colwise",
  134. "layers.*.self_attn.v_proj": "colwise",
  135. "layers.*.self_attn.o_proj": "rowwise",
  136. "layers.*.mlp.gate_proj": "colwise",
  137. "layers.*.mlp.up_proj": "colwise",
  138. "layers.*.mlp.down_proj": "rowwise",
  139. }
  140. base_model_pp_plan = {
  141. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  142. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  143. "norm": (["hidden_states"], ["hidden_states"]),
  144. }
  145. def __init__(
  146. self,
  147. vocab_size=256000,
  148. hidden_size=8192,
  149. intermediate_size=22528,
  150. logit_scale=0.0625,
  151. num_hidden_layers=40,
  152. num_attention_heads=64,
  153. num_key_value_heads=None,
  154. hidden_act="silu",
  155. max_position_embeddings=8192,
  156. initializer_range=0.02,
  157. layer_norm_eps=1e-5,
  158. use_cache=True,
  159. pad_token_id=0,
  160. bos_token_id=5,
  161. eos_token_id=255001,
  162. tie_word_embeddings=True,
  163. rope_theta=10000.0,
  164. rope_scaling=None,
  165. attention_bias=False,
  166. attention_dropout=0.0,
  167. sliding_window=4096,
  168. layer_types=None,
  169. **kwargs,
  170. ):
  171. self.vocab_size = vocab_size
  172. self.max_position_embeddings = max_position_embeddings
  173. self.hidden_size = hidden_size
  174. self.logit_scale = logit_scale
  175. self.intermediate_size = intermediate_size
  176. self.num_hidden_layers = num_hidden_layers
  177. self.num_attention_heads = num_attention_heads
  178. # for backward compatibility
  179. if num_key_value_heads is None:
  180. num_key_value_heads = num_attention_heads
  181. self.num_key_value_heads = num_key_value_heads
  182. self.hidden_act = hidden_act
  183. self.initializer_range = initializer_range
  184. self.layer_norm_eps = layer_norm_eps
  185. self.use_cache = use_cache
  186. self.rope_theta = rope_theta
  187. self.rope_scaling = rope_scaling
  188. self.attention_bias = attention_bias
  189. self.attention_dropout = attention_dropout
  190. self.sliding_window = sliding_window
  191. self.layer_types = layer_types
  192. # Need to specify head_dim in the config so it can be used in the attention forward functions
  193. self.head_dim = hidden_size // num_attention_heads
  194. # Validate the correctness of rotary position embeddings parameters
  195. rope_config_validation(self)
  196. super().__init__(
  197. pad_token_id=pad_token_id,
  198. bos_token_id=bos_token_id,
  199. eos_token_id=eos_token_id,
  200. tie_word_embeddings=tie_word_embeddings,
  201. **kwargs,
  202. )
  203. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  204. self._sliding_window_pattern = kwargs.get("sliding_window_pattern", 4)
  205. if self.layer_types is None:
  206. # BC -> the pattern used to be a simple int, and it's still present in configs on the Hub
  207. self._sliding_window_pattern = getattr(self, "sliding_window_pattern", 4)
  208. self.layer_types = [
  209. "sliding_attention" if bool((i + 1) % self._sliding_window_pattern) else "full_attention"
  210. for i in range(self.num_hidden_layers)
  211. ]
  212. layer_type_validation(self.layer_types, self.num_hidden_layers)
  213. __all__ = ["Cohere2Config"]