configuration_phi.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # coding=utf-8
  2. # Copyright 2023 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 model configuration"""
  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 PhiConfig(PretrainedConfig):
  21. r"""
  22. This is the configuration class to store the configuration of a [`PhiModel`]. It is used to instantiate an Phi
  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 Phi
  25. [microsoft/phi-1](https://huggingface.co/microsoft/phi-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 51200):
  30. Vocabulary size of the Phi model. Defines the number of different tokens that can be represented by the
  31. `inputs_ids` passed when calling [`PhiModel`].
  32. hidden_size (`int`, *optional*, defaults to 2048):
  33. Dimension of the hidden representations.
  34. intermediate_size (`int`, *optional*, defaults to 8192):
  35. Dimension of the MLP representations.
  36. num_hidden_layers (`int`, *optional*, defaults to 24):
  37. Number of hidden layers in the Transformer decoder.
  38. num_attention_heads (`int`, *optional*, defaults to 32):
  39. Number of attention heads for each attention layer in the Transformer decoder.
  40. num_key_value_heads (`int`, *optional*):
  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 checkout [this
  46. paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
  47. `num_attention_heads`.
  48. resid_pdrop (`float`, *optional*, defaults to 0.0):
  49. Dropout probability for mlp outputs.
  50. embd_pdrop (`int`, *optional*, defaults to 0.0):
  51. The dropout ratio for the embeddings.
  52. attention_dropout (`float`, *optional*, defaults to 0.0):
  53. The dropout ratio after computing the attention scores.
  54. hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
  55. The non-linear activation function (function or string) in the decoder.
  56. max_position_embeddings (`int`, *optional*, defaults to 2048):
  57. The maximum sequence length that this model might ever be used with. Phi-1 and Phi-1.5 supports up to 2048
  58. tokens.
  59. initializer_range (`float`, *optional*, defaults to 0.02):
  60. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  61. layer_norm_eps (`float`, *optional*, defaults to 1e-05):
  62. The epsilon used by the rms normalization layers.
  63. use_cache (`bool`, *optional*, defaults to `True`):
  64. Whether or not the model should return the last key/values attentions (not used by all models). Only
  65. relevant if `config.is_decoder=True`. Whether to tie weight embeddings or not.
  66. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  67. Whether to tie weight embeddings
  68. rope_theta (`float`, *optional*, defaults to 10000.0):
  69. The base period of the RoPE embeddings.
  70. rope_scaling (`Dict`, *optional*):
  71. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  72. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  73. accordingly.
  74. Expected contents:
  75. `rope_type` (`str`):
  76. The sub-variant of RoPE to use. Can be one of ['default', 'linear', 'dynamic', 'yarn', 'longrope',
  77. 'llama3'], with 'default' being the original RoPE implementation.
  78. `factor` (`float`, *optional*):
  79. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  80. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  81. original maximum pre-trained length.
  82. `original_max_position_embeddings` (`int`, *optional*):
  83. Used with 'dynamic', 'longrope' and 'llama3'. The original max position embeddings used during
  84. pretraining.
  85. `attention_factor` (`float`, *optional*):
  86. Used with 'yarn' and 'longrope'. The scaling factor to be applied on the attention
  87. computation. If unspecified, it defaults to value recommended by the implementation, using the
  88. `factor` field to infer the suggested value.
  89. `beta_fast` (`float`, *optional*):
  90. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  91. ramp function. If unspecified, it defaults to 32.
  92. `beta_slow` (`float`, *optional*):
  93. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  94. ramp function. If unspecified, it defaults to 1.
  95. `short_factor` (`List[float]`, *optional*):
  96. Only used with 'longrope'. The scaling factor to be applied to short contexts (<
  97. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  98. size divided by the number of attention heads divided by 2
  99. `long_factor` (`List[float]`, *optional*):
  100. Only used with 'longrope'. The scaling factor to be applied to long contexts (<
  101. `original_max_position_embeddings`). Must be a list of numbers with the same length as the hidden
  102. size divided by the number of attention heads divided by 2
  103. `low_freq_factor` (`float`, *optional*):
  104. Only used with 'llama3'. Scaling factor applied to low frequency components of the RoPE
  105. `high_freq_factor` (`float`, *optional*):
  106. Only used with 'llama3'. Scaling factor applied to high frequency components of the RoPE
  107. partial_rotary_factor (`float`, *optional*, defaults to 0.5):
  108. Percentage of the query and keys which will have rotary embedding.
  109. qk_layernorm (`bool`, *optional*, defaults to `False`):
  110. Whether or not to normalize the Queries and Keys after projecting the hidden states.
  111. bos_token_id (`int`, *optional*, defaults to 1):
  112. Denotes beginning of sequences token id.
  113. eos_token_id (`int`, *optional*, defaults to 2):
  114. Denotes end of sequences token id.
  115. Example:
  116. ```python
  117. >>> from transformers import PhiModel, PhiConfig
  118. >>> # Initializing a Phi-1 style configuration
  119. >>> configuration = PhiConfig.from_pretrained("microsoft/phi-1")
  120. >>> # Initializing a model from the configuration
  121. >>> model = PhiModel(configuration)
  122. >>> # Accessing the model configuration
  123. >>> configuration = model.config
  124. ```"""
  125. model_type = "phi"
  126. keys_to_ignore_at_inference = ["past_key_values"]
  127. def __init__(
  128. self,
  129. vocab_size=51200,
  130. hidden_size=2048,
  131. intermediate_size=8192,
  132. num_hidden_layers=24,
  133. num_attention_heads=32,
  134. num_key_value_heads=None,
  135. resid_pdrop=0.0,
  136. embd_pdrop=0.0,
  137. attention_dropout=0.0,
  138. hidden_act="gelu_new",
  139. max_position_embeddings=2048,
  140. initializer_range=0.02,
  141. layer_norm_eps=1e-5,
  142. use_cache=True,
  143. tie_word_embeddings=False,
  144. rope_theta=10000.0,
  145. rope_scaling=None,
  146. partial_rotary_factor=0.5,
  147. qk_layernorm=False,
  148. bos_token_id=1,
  149. eos_token_id=2,
  150. **kwargs,
  151. ):
  152. self.vocab_size = vocab_size
  153. self.hidden_size = hidden_size
  154. self.intermediate_size = intermediate_size
  155. self.num_hidden_layers = num_hidden_layers
  156. self.num_attention_heads = num_attention_heads
  157. if num_key_value_heads is None:
  158. num_key_value_heads = num_attention_heads
  159. self.num_key_value_heads = num_key_value_heads
  160. self.resid_pdrop = resid_pdrop
  161. self.embd_pdrop = embd_pdrop
  162. self.attention_dropout = attention_dropout
  163. self.hidden_act = hidden_act
  164. self.max_position_embeddings = max_position_embeddings
  165. self.initializer_range = initializer_range
  166. self.layer_norm_eps = layer_norm_eps
  167. self.use_cache = use_cache
  168. self.rope_theta = rope_theta
  169. self.rope_scaling = rope_scaling
  170. self.partial_rotary_factor = partial_rotary_factor
  171. self.qk_layernorm = qk_layernorm
  172. # Validate the correctness of rotary position embeddings parameters
  173. # BC: if there is a 'type' field, move it to 'rope_type'.
  174. if self.rope_scaling is not None and "type" in self.rope_scaling:
  175. self.rope_scaling["rope_type"] = self.rope_scaling["type"]
  176. rope_config_validation(self)
  177. super().__init__(
  178. bos_token_id=bos_token_id,
  179. eos_token_id=eos_token_id,
  180. tie_word_embeddings=tie_word_embeddings,
  181. **kwargs,
  182. )