configuration_phi3.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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, check out [this
  45. paper](https://huggingface.co/papers/2305.13245). 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. partial_rotary_factor (`float`, *optional*, defaults to 1.0):
  77. Percentage of the query and keys which will have rotary embedding. Must be between 0.0 and 1.0.
  78. bos_token_id (`int`, *optional*, defaults to 1):
  79. The id of the "beginning-of-sequence" token.
  80. eos_token_id (`int`, *optional*, defaults to 32000):
  81. The id of the "end-of-sequence" token.
  82. pad_token_id (`int`, *optional*, defaults to 32000):
  83. The id of the padding token.
  84. sliding_window (`int`, *optional*):
  85. Sliding window attention window size. If `None`, no sliding window is applied.
  86. Example:
  87. ```python
  88. >>> from transformers import Phi3Model, Phi3Config
  89. >>> # Initializing a Phi-3 style configuration
  90. >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
  91. >>> # Initializing a model from the configuration
  92. >>> model = Phi3Model(configuration)
  93. >>> # Accessing the model configuration
  94. >>> configuration = model.config
  95. ```"""
  96. model_type = "phi3"
  97. keys_to_ignore_at_inference = ["past_key_values"]
  98. base_model_tp_plan = {
  99. "layers.*.self_attn.qkv_proj": "colwise_rep", # we need to replicate here due to the slicing of qkv
  100. "layers.*.self_attn.o_proj": "rowwise_rep", # we need to replicate here due to the slicing of qkv
  101. "layers.*.mlp.gate_up_proj": "colwise_rep", # we need to replicate here due to the `chunk` operation
  102. "layers.*.mlp.down_proj": "rowwise_rep", # we need to replicate here due to the `chunk` operation
  103. }
  104. base_model_pp_plan = {
  105. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  106. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  107. "norm": (["hidden_states"], ["hidden_states"]),
  108. }
  109. def __init__(
  110. self,
  111. vocab_size=32064,
  112. hidden_size=3072,
  113. intermediate_size=8192,
  114. num_hidden_layers=32,
  115. num_attention_heads=32,
  116. num_key_value_heads=None,
  117. resid_pdrop=0.0,
  118. embd_pdrop=0.0,
  119. attention_dropout=0.0,
  120. hidden_act="silu",
  121. max_position_embeddings=4096,
  122. original_max_position_embeddings=4096,
  123. initializer_range=0.02,
  124. rms_norm_eps=1e-5,
  125. use_cache=True,
  126. tie_word_embeddings=False,
  127. rope_theta=10000.0,
  128. rope_scaling=None,
  129. partial_rotary_factor=1.0,
  130. bos_token_id=1,
  131. eos_token_id=32000,
  132. pad_token_id=32000,
  133. sliding_window=None,
  134. **kwargs,
  135. ):
  136. self.vocab_size = vocab_size
  137. self.hidden_size = hidden_size
  138. self.intermediate_size = intermediate_size
  139. self.num_hidden_layers = num_hidden_layers
  140. self.num_attention_heads = num_attention_heads
  141. if num_key_value_heads is None:
  142. num_key_value_heads = num_attention_heads
  143. self.num_key_value_heads = num_key_value_heads
  144. self.resid_pdrop = resid_pdrop
  145. self.embd_pdrop = embd_pdrop
  146. self.attention_dropout = attention_dropout
  147. self.hidden_act = hidden_act
  148. self.max_position_embeddings = max_position_embeddings
  149. self.original_max_position_embeddings = original_max_position_embeddings
  150. self.initializer_range = initializer_range
  151. self.rms_norm_eps = rms_norm_eps
  152. self.use_cache = use_cache
  153. self.rope_theta = rope_theta
  154. self.rope_scaling = rope_scaling
  155. self.partial_rotary_factor = partial_rotary_factor
  156. self._rope_scaling_adjustment()
  157. self._rope_scaling_validation()
  158. self.sliding_window = sliding_window
  159. super().__init__(
  160. bos_token_id=bos_token_id,
  161. eos_token_id=eos_token_id,
  162. pad_token_id=pad_token_id,
  163. tie_word_embeddings=tie_word_embeddings,
  164. **kwargs,
  165. )
  166. def _rope_scaling_adjustment(self):
  167. """
  168. Adjust the `type` of the `rope_scaling` configuration for backward compatibility.
  169. """
  170. if self.rope_scaling is None:
  171. return
  172. rope_scaling_type = self.rope_scaling.get("type", None)
  173. # For backward compatibility if previous version used "su" or "yarn"
  174. if rope_scaling_type is not None and rope_scaling_type in ["su", "yarn"]:
  175. self.rope_scaling["type"] = "longrope"
  176. def _rope_scaling_validation(self):
  177. """
  178. Validate the `rope_scaling` configuration.
  179. """
  180. if self.rope_scaling is None:
  181. return
  182. if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 3:
  183. raise ValueError(
  184. "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor` and `long_factor`, "
  185. f"got {self.rope_scaling}"
  186. )
  187. rope_scaling_type = self.rope_scaling.get("type", None)
  188. rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)
  189. rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)
  190. if rope_scaling_type is None or rope_scaling_type != "longrope":
  191. raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")
  192. if not (
  193. isinstance(rope_scaling_short_factor, list)
  194. and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)
  195. ):
  196. raise ValueError(
  197. f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"
  198. )
  199. rotary_ndims = int(self.hidden_size // self.num_attention_heads * self.partial_rotary_factor)
  200. if not len(rope_scaling_short_factor) == rotary_ndims // 2:
  201. raise ValueError(
  202. f"`rope_scaling`'s short_factor field must have length {rotary_ndims // 2}, got {len(rope_scaling_short_factor)}"
  203. )
  204. if not (
  205. isinstance(rope_scaling_long_factor, list)
  206. and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)
  207. ):
  208. raise ValueError(
  209. f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"
  210. )
  211. if not len(rope_scaling_long_factor) == rotary_ndims // 2:
  212. raise ValueError(
  213. f"`rope_scaling`'s long_factor field must have length {rotary_ndims // 2}, got {len(rope_scaling_long_factor)}"
  214. )
  215. __all__ = ["Phi3Config"]