configuration_phimoe.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. """PyTorch Phi-MoE model."""
  16. from ...configuration_utils import PretrainedConfig
  17. from ...modeling_rope_utils import rope_config_validation
  18. from ...utils import logging
  19. logger = logging.get_logger(__name__)
  20. class PhimoeConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`PhimoeModel`]. It is used to instantiate a Phi-moe
  23. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  24. defaults will yield a similar configuration to that of the
  25. [microsoft/Phi-3.5-MoE-instruct](https://huggingface.co/microsoft/Phi-3.5-MoE-instruct).
  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 32064):
  30. Vocabulary size of the Phimoe model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`PhimoeModel`]
  32. hidden_size (`int`, *optional*, defaults to 4096):
  33. Dimension of the hidden representations.
  34. intermediate_size (`int`, *optional*, defaults to 6400):
  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. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  48. The non-linear activation function (function or string) in the decoder.
  49. max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
  50. The maximum sequence length that this model might ever be used with. Mixtral's sliding window attention
  51. allows sequence of up to 4096*32 tokens.
  52. initializer_range (`float`, *optional*, defaults to 0.02):
  53. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  54. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  55. The epsilon used by the rms normalization layers.
  56. use_cache (`bool`, *optional*, defaults to `True`):
  57. Whether or not the model should return the last key/values attentions (not used by all models). Only
  58. relevant if `config.is_decoder=True`.
  59. pad_token_id (`int`, *optional*):
  60. The id of the padding token.
  61. bos_token_id (`int`, *optional*, defaults to 1):
  62. The id of the "beginning-of-sequence" token.
  63. eos_token_id (`int`, *optional*, defaults to 2):
  64. The id of the "end-of-sequence" token.
  65. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  66. Whether the model's input and output word embeddings should be tied.
  67. rope_theta (`float`, *optional*, defaults to 1000000.0):
  68. The base period of the RoPE embeddings.
  69. rope_scaling (`dict`, *optional*):
  70. The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must
  71. contain the following keys: `type`, `short_factor`, `long_factor`, `short_mscale`, `long_mscale` and
  72. `original_max_position_embeddings`. The `type` must be `longrope`, the `short_mscale` and `long_scale` must
  73. be numbers, the `short_factor` and `long_factor` must be lists of numbers with the same length as half of
  74. the attention head size and the `original_max_position_embeddings` must be an integer.
  75. sliding_window (`int`, *optional*):
  76. Sliding window attention window size. If not specified, will default to `262144`.
  77. attention_dropout (`float`, *optional*, defaults to 0.0):
  78. The dropout ratio for the attention probabilities.
  79. num_experts_per_tok (`int`, *optional*, defaults to 2):
  80. The number of experts to root per-token, can be also interpreted as the `top-p` routing
  81. parameter
  82. num_local_experts (`int`, *optional*, defaults to 16):
  83. Number of experts per Sparse MLP layer.
  84. output_router_logits (`bool`, *optional*, defaults to `False`):
  85. Whether or not the router logits should be returned by the model. Enabling this will also
  86. allow the model to output the auxiliary loss. See [here]() for more details
  87. router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
  88. The aux loss factor for the total loss.
  89. router_jitter_noise (`float`, *optional*, defaults to 0.01):
  90. Amount of noise to add to the router.
  91. input_jitter_noise (`float`, *optional*, defaults to 0.0): Input jitter noise
  92. attention_bias (`bool`, *optional*, defaults to `False`): Attention bias
  93. lm_head_bias (`bool`, *optional*, defaults to `False`): LM head bias
  94. Example:
  95. ```python
  96. >>> from transformers import PhimoeModel, PhimoeConfig
  97. >>> # Initializing a Phi-3 style configuration
  98. >>> configuration = PhimoeConfig.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
  99. >>> # Initializing a model from the configuration
  100. >>> model = PhimoeModel(configuration)
  101. >>> # Accessing the model configuration
  102. >>> configuration = model.config
  103. ```"""
  104. model_type = "phimoe"
  105. keys_to_ignore_at_inference = ["past_key_values"]
  106. def __init__(
  107. self,
  108. vocab_size=32064,
  109. hidden_size=4096,
  110. intermediate_size=6400,
  111. num_hidden_layers=32,
  112. num_attention_heads=32,
  113. num_key_value_heads=8,
  114. hidden_act="silu",
  115. max_position_embeddings=4096 * 32,
  116. initializer_range=0.02,
  117. rms_norm_eps=1e-5,
  118. use_cache=True,
  119. pad_token_id=None,
  120. bos_token_id=1,
  121. eos_token_id=2,
  122. tie_word_embeddings=False,
  123. rope_theta=1e6,
  124. rope_scaling=None,
  125. sliding_window=None,
  126. attention_dropout=0.0,
  127. num_experts_per_tok=2,
  128. num_local_experts=16,
  129. output_router_logits=False,
  130. router_aux_loss_coef=0.001,
  131. router_jitter_noise=0.01,
  132. input_jitter_noise=0.0,
  133. attention_bias=False,
  134. lm_head_bias=False,
  135. **kwargs,
  136. ):
  137. self.vocab_size = vocab_size
  138. self.max_position_embeddings = max_position_embeddings
  139. self.hidden_size = hidden_size
  140. self.intermediate_size = intermediate_size
  141. self.num_hidden_layers = num_hidden_layers
  142. self.num_attention_heads = num_attention_heads
  143. self.sliding_window = sliding_window
  144. self.attention_bias = attention_bias
  145. self.lm_head_bias = lm_head_bias
  146. # for backward compatibility
  147. if num_key_value_heads is None:
  148. num_key_value_heads = num_attention_heads
  149. self.num_key_value_heads = num_key_value_heads
  150. self.hidden_act = hidden_act
  151. self.initializer_range = initializer_range
  152. self.rms_norm_eps = rms_norm_eps
  153. self.use_cache = use_cache
  154. self.rope_theta = rope_theta
  155. self.attention_dropout = attention_dropout
  156. self.num_experts_per_tok = num_experts_per_tok
  157. self.num_local_experts = num_local_experts
  158. self.output_router_logits = output_router_logits
  159. self.router_aux_loss_coef = router_aux_loss_coef
  160. self.router_jitter_noise = router_jitter_noise
  161. self.input_jitter_noise = input_jitter_noise
  162. self.rope_scaling = rope_scaling
  163. if isinstance(self.rope_scaling, dict):
  164. if "rope_type" not in self.rope_scaling:
  165. self.rope_scaling["rope_type"] = self.rope_scaling.get("type", None)
  166. if "original_max_position_embeddings" in self.rope_scaling:
  167. self.original_max_position_embeddings = self.rope_scaling["original_max_position_embeddings"]
  168. rope_scaling_short_mscale = self.rope_scaling.get("short_mscale", None)
  169. rope_scaling_long_mscale = self.rope_scaling.get("long_mscale", None)
  170. if not isinstance(rope_scaling_short_mscale, (int, float)):
  171. raise TypeError(
  172. f"`rope_scaling`'s short_mscale field must be a number, got {rope_scaling_short_mscale}"
  173. )
  174. if not isinstance(rope_scaling_long_mscale, (int, float)):
  175. raise TypeError(f"`rope_scaling`'s long_mscale field must be a number, got {rope_scaling_long_mscale}")
  176. rope_config_validation(self)
  177. super().__init__(
  178. pad_token_id=pad_token_id,
  179. bos_token_id=bos_token_id,
  180. eos_token_id=eos_token_id,
  181. tie_word_embeddings=tie_word_embeddings,
  182. **kwargs,
  183. )
  184. __all__ = ["PhimoeConfig"]