FriendliAI/Phi-tiny-MoE-instruct
018
1# coding=utf-82# 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 at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# 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 and14# limitations under the License.15 16""" PyTorch Phi-MoE model."""17 18 19from transformers.configuration_utils import PretrainedConfig20from transformers.utils import logging21 22 23logger = logging.get_logger(__name__)24 25 26class PhiMoEConfig(PretrainedConfig):27 r"""28 This is the configuration class to store the configuration of a [`PhiMoEModel`]. It is used to instantiate a Phi-MoE29 model according to the specified arguments, defining the model architecture. Instantiating a configuration with the30 defaults will yield a similar configuration to that of the31 [microsoft/Phi-3.5-MoE-instruct](https://huggingface.co/microsoft/Phi-3.5-MoE-instruct).32 33 Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the34 documentation from [`PretrainedConfig`] for more information.35 36 37 Args:38 vocab_size (`int`, *optional*, defaults to 32064):39 Vocabulary size of the PhiMoE model. Defines the number of different tokens that can be represented by the40 `inputs_ids` passed when calling [`PhiMoEModel`]41 hidden_size (`int`, *optional*, defaults to 4096):42 Dimension of the hidden representations.43 intermediate_size (`int`, *optional*, defaults to 6400):44 Dimension of the MLP representations.45 num_hidden_layers (`int`, *optional*, defaults to 32):46 Number of hidden layers in the Transformer encoder.47 num_attention_heads (`int`, *optional*, defaults to 32):48 Number of attention heads for each attention layer in the Transformer encoder.49 num_key_value_heads (`int`, *optional*, defaults to 8):50 This is the number of key_value heads that should be used to implement Grouped Query Attention. If51 `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if52 `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When53 converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed54 by meanpooling all the original heads within that group. For more details checkout [this55 paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.56 hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):57 The non-linear activation function (function or string) in the decoder.58 max_position_embeddings (`int`, *optional*, defaults to `4096*32`):59 The maximum sequence length that this model might ever be used with. Mixtral's sliding window attention60 allows sequence of up to 4096*32 tokens.61 initializer_range (`float`, *optional*, defaults to 0.02):62 The standard deviation of the truncated_normal_initializer for initializing all weight matrices.63 rms_norm_eps (`float`, *optional*, defaults to 1e-05):64 The epsilon used by the rms normalization layers.65 use_cache (`bool`, *optional*, defaults to `True`):66 Whether or not the model should return the last key/values attentions (not used by all models). Only67 relevant if `config.is_decoder=True`.68 pad_token_id (`int`, *optional*):69 The id of the padding token.70 bos_token_id (`int`, *optional*, defaults to 1):71 The id of the "beginning-of-sequence" token.72 eos_token_id (`int`, *optional*, defaults to 2):73 The id of the "end-of-sequence" token.74 tie_word_embeddings (`bool`, *optional*, defaults to `False`):75 Whether the model's input and output word embeddings should be tied.76 rope_theta (`float`, *optional*, defaults to 10000.0):77 The base period of the RoPE embeddings.78 rope_scaling (`dict`, *optional*):79 The scaling strategy for the RoPE embeddings. If `None`, no scaling is applied. If a dictionary, it must80 contain the following keys: `type`, `short_factor`, `long_factor`, `short_mscale`, `long_mscale` and81 `original_max_position_embeddings`. The `type` must be `longrope`, the `short_mscale` and `long_scale` must82 be numbers, the `short_factor` and `long_factor` must be lists of numbers with the same length as half of83 the attention head size and the `original_max_position_embeddings` must be an integer.84 sliding_window (`int`, *optional*):85 Sliding window attention window size. If not specified, will default to `262144`.86 attention_dropout (`float`, *optional*, defaults to 0.0):87 The dropout ratio for the attention probabilities.88 num_experts_per_tok (`int`, *optional*, defaults to 2):89 The number of experts to root per-token, can be also interpreted as the `top-p` routing90 parameter91 num_local_experts (`int`, *optional*, defaults to 16):92 Number of experts per Sparse MLP layer.93 output_router_logits (`bool`, *optional*, defaults to `False`):94 Whether or not the router logits should be returned by the model. Enabeling this will also95 allow the model to output the auxiliary loss. See [here]() for more details96 router_aux_loss_coef (`float`, *optional*, defaults to 0.0):97 The aux loss factor for the total loss.98 router_jitter_noise (`float`, *optional*, defaults to 0.01):99 Amount of noise to add to the router.100 101 ```python102 >>> from transformers import PhiMoEModel, PhiMoEConfig103 104 >>> # Initializing a Phi-3 style configuration105 >>> configuration = PhiMoEConfig.from_pretrained("microsoft/Phi-3.5-MoE-instruct")106 107 >>> # Initializing a model from the configuration108 >>> model = PhiMoEModel(configuration)109 110 >>> # Accessing the model configuration111 >>> configuration = model.config112 ```"""113 114 model_type = "phimoe"115 keys_to_ignore_at_inference = ["past_key_values"]116 117 def __init__(118 self,119 vocab_size=32064,120 hidden_size=4096,121 intermediate_size=6400,122 num_hidden_layers=32,123 num_attention_heads=32,124 num_key_value_heads=8,125 head_dim=None, # added to control head dimension126 hidden_act="silu",127 max_position_embeddings=4096 * 32,128 initializer_range=0.02,129 rms_norm_eps=1e-5,130 use_cache=True,131 pad_token_id=None,132 bos_token_id=1,133 eos_token_id=2,134 tie_word_embeddings=False,135 rope_theta=1e6,136 rope_scaling=None,137 sliding_window=None,138 attention_dropout=0.0,139 num_experts_per_tok=2,140 num_local_experts=16,141 output_router_logits=False,142 router_aux_loss_coef=0.001,143 router_jitter_noise=0.01,144 input_jitter_noise=0.0,145 attention_bias = False,146 lm_head_bias = False,147 **kwargs,148 ):149 self.vocab_size = vocab_size150 self.max_position_embeddings = max_position_embeddings151 self.hidden_size = hidden_size152 self.intermediate_size = intermediate_size153 self.num_hidden_layers = num_hidden_layers154 self.num_attention_heads = num_attention_heads155 self.sliding_window = sliding_window156 self.attention_bias = attention_bias157 self.lm_head_bias = lm_head_bias158 # for backward compatibility159 if num_key_value_heads is None:160 num_key_value_heads = num_attention_heads161 if head_dim is None:162 head_dim = hidden_size // num_attention_heads163 164 self.head_dim = head_dim165 self.num_key_value_heads = num_key_value_heads166 self.hidden_act = hidden_act167 self.initializer_range = initializer_range168 self.rms_norm_eps = rms_norm_eps169 self.use_cache = use_cache170 self.rope_theta = rope_theta171 self.attention_dropout = attention_dropout172 173 self.num_experts_per_tok = num_experts_per_tok174 self.num_local_experts = num_local_experts175 self.output_router_logits = output_router_logits176 self.router_aux_loss_coef = router_aux_loss_coef177 self.router_jitter_noise = router_jitter_noise178 self.input_jitter_noise = input_jitter_noise179 180 self.rope_scaling = rope_scaling181 self._rope_scaling_validation()182 183 super().__init__(184 pad_token_id=pad_token_id,185 bos_token_id=bos_token_id,186 eos_token_id=eos_token_id,187 tie_word_embeddings=tie_word_embeddings,188 **kwargs,189 )190 191 def _rope_scaling_validation(self):192 """193 Validate the `rope_scaling` configuration.194 """195 if self.rope_scaling is None:196 return197 198 if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 6:199 raise ValueError(200 "`rope_scaling` must be a dictionary with three fields, `type`, `short_factor`, `long_factor`, "201 f"`short_mscale`, `long_mscale` and `original_max_position_embeddings`, got {self.rope_scaling}"202 )203 rope_scaling_type = self.rope_scaling.get("type", None)204 rope_scaling_short_factor = self.rope_scaling.get("short_factor", None)205 rope_scaling_long_factor = self.rope_scaling.get("long_factor", None)206 rope_scaling_short_mscale = self.rope_scaling.get("short_mscale", None)207 rope_scaling_long_mscale = self.rope_scaling.get("long_mscale", None)208 original_max_position_embeddings = self.rope_scaling.get("original_max_position_embeddings", None)209 if rope_scaling_type is None or rope_scaling_type not in ["longrope"]:210 raise ValueError(f"`rope_scaling`'s type field must be one of ['longrope'], got {rope_scaling_type}")211 if not (212 isinstance(rope_scaling_short_factor, list)213 and all(isinstance(x, (int, float)) for x in rope_scaling_short_factor)214 ):215 raise ValueError(216 f"`rope_scaling`'s short_factor field must be a list of numbers, got {rope_scaling_short_factor}"217 )218 if not len(rope_scaling_short_factor) == self.hidden_size // self.num_attention_heads // 2:219 raise ValueError(220 f"`rope_scaling`'s short_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_short_factor)}"221 )222 if not (223 isinstance(rope_scaling_long_factor, list)224 and all(isinstance(x, (int, float)) for x in rope_scaling_long_factor)225 ):226 raise ValueError(227 f"`rope_scaling`'s long_factor field must be a list of numbers, got {rope_scaling_long_factor}"228 )229 if not len(rope_scaling_long_factor) == self.hidden_size // self.num_attention_heads // 2:230 raise ValueError(231 f"`rope_scaling`'s long_factor field must have length {self.hidden_size // self.num_attention_heads // 2}, got {len(rope_scaling_long_factor)}"232 )233 if not isinstance(rope_scaling_short_mscale, (int, float)):234 raise ValueError(235 f"`rope_scaling`'s short_mscale field must be a number, got {rope_scaling_short_mscale}"236 )237 if not isinstance(rope_scaling_long_mscale, (int, float)):238 raise ValueError(239 f"`rope_scaling`'s long_mscale field must be a number, got {rope_scaling_long_mscale}"240 )241 if not isinstance(original_max_position_embeddings, int):242 raise ValueError(243 f"`rope_scaling`'s original_max_position_embeddings field must be an integer, got {original_max_position_embeddings}"244 )