configuration_phi3.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. # coding=utf-8
  2. # Copyright 2024 Microsoft 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. """Phi-3 model configuration"""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...utils import logging
  18. logger = logging.get_logger(__name__)
  19. class Phi3Config(PretrainedConfig):
  20. r"""
  21. This is the configuration class to store the configuration of a [`Phi3Model`]. It is used to instantiate a Phi-3
  22. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  23. defaults will yield a similar configuration to that of the
  24. [microsoft/Phi-3-mini-4k-instruct](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct).
  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 32064):
  29. Vocabulary size of the Phi-3 model. Defines the number of different tokens that can be represented by the
  30. `inputs_ids` passed when calling [`Phi3Model`].
  31. hidden_size (`int`, *optional*, defaults to 3072):
  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 32):
  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 checkout [this
  45. paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
  46. `num_attention_heads`.
  47. resid_pdrop (`float`, *optional*, defaults to 0.0):
  48. Dropout probability for mlp outputs.
  49. embd_pdrop (`int`, *optional*, defaults to 0.0):
  50. The dropout ratio for the embeddings.
  51. attention_dropout (`float`, *optional*, defaults to 0.0):
  52. The dropout ratio after computing the attention scores.
  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 4096):
  56. The maximum sequence length that this model might ever be used with.
  57. original_max_position_embeddings (`int`, *optional*, defaults to 4096):
  58. The maximum sequence length that this model was trained with. This is used to determine the size of the
  59. original RoPE embeddings when using long scaling.
  60. initializer_range (`float`, *optional*, defaults to 0.02):
  61. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  62. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  63. The epsilon value used for the RMSNorm.
  64. use_cache (`bool`, *optional*, defaults to `True`):
  65. Whether or not the model should return the last key/values attentions (not used by all models). Only
  66. relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
  67. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  68. Whether to tie weight embeddings
  69. rope_theta (`float`, *optional*, defaults to 10000.0):
  70. The base period of the RoPE embeddings.
  71. rope_scaling (`dict`, *optional*):
  72. The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
  73. contain the following keys: `type`, `short_factor` and `long_factor`. The `type` must be `longrope` and
  74. the `short_factor` and `long_factor` must be lists of numbers with the same length as the hidden size
  75. divided by the number of attention heads divided by 2.
  76. bos_token_id (`int`, *optional*, defaults to 1):
  77. The id of the "beginning-of-sequence" token.
  78. eos_token_id (`int`, *optional*, defaults to 32000):
  79. The id of the "end-of-sequence" token.
  80. pad_token_id (`int`, *optional*, defaults to 32000):
  81. The id of the padding token.
  82. sliding_window (`int`, *optional*):
  83. Sliding window attention window size. If `None`, no sliding window is applied.
  84. Example:
  85. ```python
  86. >>> from transformers import Phi3Model, Phi3Config
  87. >>> # Initializing a Phi-3 style configuration
  88. >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
  89. >>> # Initializing a model from the configuration
  90. >>> model = Phi3Model(configuration)
  91. >>> # Accessing the model configuration
  92. >>> configuration = model.config
  93. ```"""
  94. model_type = "phi3"
  95. keys_to_ignore_at_inference = ["past_key_values"]
  96. def __init__(
  97. self,
  98. vocab_size=32064,
  99. hidden_size=3072,
  100. intermediate_size=8192,
  101. num_hidden_layers=32,
  102. num_attention_heads=32,
  103. num_key_value_heads=None,
  104. resid_pdrop=0.0,
  105. embd_pdrop=0.0,
  106. attention_dropout=0.0,
  107. hidden_act="silu",
  108. max_position_embeddings=4096,
  109. original_max_position_embeddings=4096,
  110. initializer_range=0.02,
  111. rms_norm_eps=1e-5,
  112. use_cache=True,
  113. tie_word_embeddings=False,
  114. rope_theta=10000.0,
  115. rope_scaling=None,
  116. bos_token_id=1,
  117. eos_token_id=32000,
  118. pad_token_id=32000,
  119. sliding_window=None,
  120. **kwargs,
  121. ):
  122. self.vocab_size = vocab_size
  123. self.hidden_size = hidden_size
  124. self.intermediate_size = intermediate_size
  125. self.num_hidden_layers = num_hidden_layers
  126. self.num_attention_heads = num_attention_heads
  127. if num_key_value_heads is None:
  128. num_key_value_heads = num_attention_heads
  129. self.num_key_value_heads = num_key_value_heads
  130. self.resid_pdrop = resid_pdrop
  131. self.embd_pdrop = embd_pdrop
  132. self.attention_dropout = attention_dropout
  133. self.hidden_act = hidden_act
  134. self.max_position_embeddings = max_position_embeddings
  135. self.original_max_position_embeddings = original_max_position_embeddings
  136. self.initializer_range = initializer_range
  137. self.rms_norm_eps = rms_norm_eps
  138. self.use_cache = use_cache
  139. self.rope_theta = rope_theta
  140. self.rope_scaling = rope_scaling
  141. self._rope_scaling_adjustment()
  142. self._rope_scaling_validation()
  143. self.sliding_window = sliding_window
  144. super().__init__(
  145. bos_token_id=bos_token_id,
  146. eos_token_id=eos_token_id,
  147. pad_token_id=pad_token_id,
  148. tie_word_embeddings=tie_word_embeddings,
  149. **kwargs,
  150. )
  151. def _rope_scaling_adjustment(self):
  152. """
  153. Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
  154. """
  155. if self.rope_scaling is None:
  156. return
  157. rope_scaling_type = self.rope_scaling.get("type", None)
  158. # For backward compatibility if previous version used "su" or "yarn"
  159. if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
  160. self.rope_scaling["type"] = "longrope"
  161. def _rope_scaling_validation(self):
  162. """
  163. Validate the `rope_scaling` configuration.
  164. """
  165. if self.rope_scaling is None:
  166. return
  167. if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
  168. raise ValueError(
  169. "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
  170. f"got {self.rope_scaling}"
  171. )
  172. rope_scaling_type = self.rope_scaling.get("type", None)
  173. rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
  174. rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
  175. if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:
  176. raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
  177. if not (
  178. isinstance(rope_scaling_short_factor, list)
  179. and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
  180. ):
  181. raise ValueError(
  182. f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
  183. )
  184. if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:
  185. raise ValueError(
  186. f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"
  187. )
  188. if not (
  189. isinstance(rope_scaling_long_factor, list)
  190. and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
  191. ):
  192. raise ValueError(
  193. f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
  194. )
  195. if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:
  196. raise ValueError(
  197. f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"
  198. )