configuration_cohere.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # coding=utf-8
  2. # Copyright 2024 Cohere team. All rights reserved.
  3. #
  4. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  5. # and OPT implementations in this library. It has been modified from its
  6. # original forms to accommodate minor architectural differences compared
  7. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License");
  10. # you may not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS,
  17. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. """Cohere model configuration"""
  21. from ...configuration_utils import PretrainedConfig
  22. from ...modeling_rope_utils import rope_config_validation
  23. from ...utils import logging
  24. logger = logging.get_logger(__name__)
  25. class CohereConfig(PretrainedConfig):
  26. r"""
  27. This is the configuration class to store the configuration of a [`CohereModel`]. It is used to instantiate an Cohere
  28. model according to the specified arguments, defining the model architecture.
  29. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  30. documentation from [`PretrainedConfig`] for more information. Instantiating a configuration
  31. 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.
  32. Args:
  33. vocab_size (`int`, *optional*, defaults to 256000):
  34. Vocabulary size of the Cohere model. Defines the number of different tokens that can be represented by the
  35. `inputs_ids` passed when calling [`CohereModel`]
  36. hidden_size (`int`, *optional*, defaults to 8192):
  37. Dimension of the hidden representations.
  38. intermediate_size (`int`, *optional*, defaults to 22528):
  39. Dimension of the MLP representations.
  40. logit_scale (`float`, *optional*, defaults to 0.0625):
  41. The scaling factor for the output logits.
  42. num_hidden_layers (`int`, *optional*, defaults to 40):
  43. Number of hidden layers in the Transformer decoder.
  44. num_attention_heads (`int`, *optional*, defaults to 64):
  45. Number of attention heads for each attention layer in the Transformer decoder.
  46. num_key_value_heads (`int`, *optional*):
  47. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  48. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  49. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  50. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  51. by meanpooling all the original heads within that group. For more details checkout [this
  52. paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
  53. `num_attention_heads`.
  54. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  55. The non-linear activation function (function or string) in the decoder.
  56. max_position_embeddings (`int`, *optional*, defaults to 8192):
  57. The maximum sequence length that this model might ever be used with.
  58. initializer_range (`float`, *optional*, defaults to 0.02):
  59. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  60. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  61. The epsilon used by the layer normalization.
  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). Only
  64. relevant if `config.is_decoder=True`.
  65. pad_token_id (`int`, *optional*, defaults to 0):
  66. Padding token id.
  67. bos_token_id (`int`, *optional*, defaults to 5):
  68. Beginning of stream token id.
  69. eos_token_id (`int`, *optional*, defaults to 255001):
  70. End of stream token id.
  71. tie_word_embeddings (`bool`, *optional*, defaults to `True`):
  72. Whether to tie weight embeddings
  73. rope_theta (`float`, *optional*, defaults to 10000.0):
  74. The base period of the RoPE embeddings.
  75. rope_scaling (`Dict`, *optional*):
  76. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  77. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  78. accordingly.
  79. Expected contents:
  80. `rope_type` (`str`):
  81. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  82. 'llama3'], with 'default' being the original RoPE implementation.
  83. `factor` (`float`, *optional*):
  84. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  85. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  86. original maximum pre-trained length.
  87. `original_max_position_embeddings` (`int`, *optional*):
  88. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  89. pretraining.
  90. `attention_factor` (`float`, *optional*):
  91. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  92. computation. If unspecified, it defaults to value recommended by the implementation, using the
  93. `factor` field to infer the suggested value.
  94. `beta_fast` (`float`, *optional*):
  95. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  96. ramp function. If unspecified, it defaults to 32.
  97. `beta_slow` (`float`, *optional*):
  98. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  99. ramp function. If unspecified, it defaults to 1.
  100. `short_factor` (`List[float]`, *optional*):
  101. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  102. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  103. size divided by the number of attention heads divided by 2
  104. `long_factor` (`List[float]`, *optional*):
  105. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  106. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  107. size divided by the number of attention heads divided by 2
  108. `low_freq_factor` (`float`, *optional*):
  109. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  110. `high_freq_factor` (`float`, *optional*):
  111. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  112. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
  113. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  114. attention_dropout (`float`, *optional*, defaults to 0.0):
  115. The dropout ratio for the attention probabilities.
  116. use_qk_norm (`bool`, *optional*, defaults to `False`):
  117. Whether to use query-key normalization in the attention
  118. ```python
  119. >>> from transformers import CohereModel, CohereConfig
  120. >>> # Initializing a Cohere model configuration
  121. >>> configuration = CohereConfig()
  122. >>> # Initializing a model from the Cohere configuration
  123. >>> model = CohereModel(configuration) # doctest: +SKIP
  124. >>> # Accessing the model configuration
  125. >>> configuration = model.config # doctest: +SKIP
  126. ```"""
  127. model_type = "cohere"
  128. keys_to_ignore_at_inference = ["past_key_values"]
  129. def __init__(
  130. self,
  131. vocab_size=256000,
  132. hidden_size=8192,
  133. intermediate_size=22528,
  134. logit_scale=0.0625,
  135. num_hidden_layers=40,
  136. num_attention_heads=64,
  137. num_key_value_heads=None,
  138. hidden_act="silu",
  139. max_position_embeddings=8192,
  140. initializer_range=0.02,
  141. layer_norm_eps=1e-5,
  142. use_cache=True,
  143. pad_token_id=0,
  144. bos_token_id=5,
  145. eos_token_id=255001,
  146. tie_word_embeddings=True,
  147. rope_theta=10000.0,
  148. rope_scaling=None,
  149. attention_bias=False,
  150. attention_dropout=0.0,
  151. use_qk_norm=False,
  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.logit_scale = logit_scale
  158. self.intermediate_size = intermediate_size
  159. self.num_hidden_layers = num_hidden_layers
  160. self.num_attention_heads = num_attention_heads
  161. # for backward compatibility
  162. if num_key_value_heads is None:
  163. num_key_value_heads = num_attention_heads
  164. self.num_key_value_heads = num_key_value_heads
  165. self.hidden_act = hidden_act
  166. self.initializer_range = initializer_range
  167. self.layer_norm_eps = layer_norm_eps
  168. self.use_cache = use_cache
  169. self.rope_theta = rope_theta
  170. self.rope_scaling = rope_scaling
  171. self.attention_bias = attention_bias
  172. self.attention_dropout = attention_dropout
  173. self.use_qk_norm = use_qk_norm
  174. # Validate the correctness of rotary position embeddings parameters
  175. rope_config_validation(self)
  176. super().__init__(
  177. pad_token_id=pad_token_id,
  178. bos_token_id=bos_token_id,
  179. eos_token_id=eos_token_id,
  180. tie_word_embeddings=tie_word_embeddings,
  181. **kwargs,
  182. )