configuration_mistral.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. # coding=utf-8
  2. # Copyright 2023 Mistral 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. """Mistral model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class MistralConfig(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an
  22. Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration
  23. with the defaults will yield a similar configuration to that of the Mistral-7B-v0.1 or Mistral-7B-Instruct-v0.1.
  24. [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1)
  25. [mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1)
  26. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  27. documentation from [`PretrainedConfig`] for more information.
  28. Args:
  29. vocab_size (`int`, *optional*, defaults to 32000):
  30. Vocabulary size of the Mistral model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`MistralModel`]
  32. hidden_size (`int`, *optional*, defaults to 4096):
  33. Dimension of the hidden representations.
  34. intermediate_size (`int`, *optional*, defaults to 14336):
  35. Dimension of the MLP representations.
  36. num_hidden_layers (`int`, *optional*, defaults to 32):
  37. Number of hidden layers in the Transformer encoder.
  38. num_attention_heads (`int`, *optional*, defaults to 32):
  39. Number of attention heads for each attention layer in the Transformer encoder.
  40. num_key_value_heads (`int`, *optional*, defaults to 8):
  41. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  42. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  43. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  44. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  45. by meanpooling all the original heads within that group. For more details, check out [this
  46. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to `8`.
  47. head_dim (`int`, *optional*, defaults to `hidden_size // num_attention_heads`):
  48. The attention head dimension.
  49. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  50. The non-linear activation function (function or string) in the decoder.
  51. max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
  52. The maximum sequence length that this model might ever be used with. Mistral's sliding window attention
  53. allows sequence of up to 4096*32 tokens.
  54. initializer_range (`float`, *optional*, defaults to 0.02):
  55. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  56. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  57. The epsilon used by the rms normalization layers.
  58. use_cache (`bool`, *optional*, defaults to `True`):
  59. Whether or not the model should return the last key/values attentions (not used by all models). Only
  60. relevant if `config.is_decoder=True`.
  61. pad_token_id (`int`, *optional*):
  62. The id of the padding token.
  63. bos_token_id (`int`, *optional*, defaults to 1):
  64. The id of the "beginning-of-sequence" token.
  65. eos_token_id (`int`, *optional*, defaults to 2):
  66. The id of the "end-of-sequence" token.
  67. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  68. Whether the model's input and output word embeddings should be tied.
  69. rope_theta (`float`, *optional*, defaults to 10000.0):
  70. The base period of the RoPE embeddings.
  71. sliding_window (`int`, *optional*, defaults to 4096):
  72. Sliding window attention window size. If not specified, will default to `4096`.
  73. attention_dropout (`float`, *optional*, defaults to 0.0):
  74. The dropout ratio for the attention probabilities.
  75. ```python
  76. >>> from transformers import MistralModel, MistralConfig
  77. >>> # Initializing a Mistral 7B style configuration
  78. >>> configuration = MistralConfig()
  79. >>> # Initializing a model from the Mistral 7B style configuration
  80. >>> model = MistralModel(configuration)
  81. >>> # Accessing the model configuration
  82. >>> configuration = model.config
  83. ```"""
  84. model_type = "mistral"
  85. keys_to_ignore_at_inference = ["past_key_values"]
  86. # Default tensor parallel plan for base model `MistralModel`
  87. base_model_tp_plan = {
  88. "layers.*.self_attn.q_proj": "colwise",
  89. "layers.*.self_attn.k_proj": "colwise",
  90. "layers.*.self_attn.v_proj": "colwise",
  91. "layers.*.self_attn.o_proj": "rowwise",
  92. "layers.*.mlp.gate_proj": "colwise",
  93. "layers.*.mlp.up_proj": "colwise",
  94. "layers.*.mlp.down_proj": "rowwise",
  95. }
  96. base_model_pp_plan = {
  97. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  98. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  99. "norm": (["hidden_states"], ["hidden_states"]),
  100. }
  101. def __init__(
  102. self,
  103. vocab_size=32000,
  104. hidden_size=4096,
  105. intermediate_size=14336,
  106. num_hidden_layers=32,
  107. num_attention_heads=32,
  108. num_key_value_heads=8,
  109. head_dim=None,
  110. hidden_act="silu",
  111. max_position_embeddings=4096 * 32,
  112. initializer_range=0.02,
  113. rms_norm_eps=1e-6,
  114. use_cache=True,
  115. pad_token_id=None,
  116. bos_token_id=1,
  117. eos_token_id=2,
  118. tie_word_embeddings=False,
  119. rope_theta=10000.0,
  120. sliding_window=4096,
  121. attention_dropout=0.0,
  122. **kwargs,
  123. ):
  124. self.vocab_size = vocab_size
  125. self.max_position_embeddings = max_position_embeddings
  126. self.hidden_size = hidden_size
  127. self.intermediate_size = intermediate_size
  128. self.num_hidden_layers = num_hidden_layers
  129. self.num_attention_heads = num_attention_heads
  130. self.sliding_window = sliding_window
  131. self.head_dim = head_dim
  132. # for backward compatibility
  133. if num_key_value_heads is None:
  134. num_key_value_heads = num_attention_heads
  135. self.num_key_value_heads = num_key_value_heads
  136. self.hidden_act = hidden_act
  137. self.initializer_range = initializer_range
  138. self.rms_norm_eps = rms_norm_eps
  139. self.use_cache = use_cache
  140. self.rope_theta = rope_theta
  141. self.attention_dropout = attention_dropout
  142. if "layer_types" in kwargs:
  143. logger.warning_once(
  144. "Detected Mistral model with layer_types. Consider using AutoModel or Ministral classes instead to enable alternating attention compatibility."
  145. )
  146. super().__init__(
  147. pad_token_id=pad_token_id,
  148. bos_token_id=bos_token_id,
  149. eos_token_id=eos_token_id,
  150. tie_word_embeddings=tie_word_embeddings,
  151. **kwargs,
  152. )
  153. __all__ = ["MistralConfig"]