configuration_phi3.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # Copyright 2024 Microsoft and the HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Phi-3 model configuration"""
  15. from huggingface_hub.dataclasses import strict
  16. from ...configuration_utils import PreTrainedConfig
  17. from ...modeling_rope_utils import RopeParameters
  18. from ...utils import auto_docstring
  19. @auto_docstring(checkpoint="microsoft/Phi-3-mini-4k-instruct")
  20. @strict
  21. class Phi3Config(PreTrainedConfig):
  22. r"""
  23. original_max_position_embeddings (`int`, *optional*, defaults to 4096):
  24. The maximum sequence length that this model was trained with. This is used to determine the size of the
  25. original RoPE embeddings when using long scaling.
  26. Example:
  27. ```python
  28. >>> from transformers import Phi3Model, Phi3Config
  29. >>> # Initializing a Phi-3 style configuration
  30. >>> configuration = Phi3Config.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
  31. >>> # Initializing a model from the configuration
  32. >>> model = Phi3Model(configuration)
  33. >>> # Accessing the model configuration
  34. >>> configuration = model.config
  35. ```"""
  36. model_type = "phi3"
  37. keys_to_ignore_at_inference = ["past_key_values"]
  38. base_model_tp_plan = {
  39. "layers.*.self_attn.qkv_proj": "colwise_gather_output", # we need to replicate here due to the slicing of qkv
  40. "layers.*.self_attn.o_proj": "rowwise_split_input", # input is replicated due to the slicing of qkv
  41. "layers.*.mlp.gate_up_proj": "colwise_gather_output", # we need to replicate here due to the `chunk` operation
  42. "layers.*.mlp.down_proj": "rowwise_split_input", # input is replicated due to the `chunk` operation
  43. }
  44. base_model_pp_plan = {
  45. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  46. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  47. "norm": (["hidden_states"], ["hidden_states"]),
  48. }
  49. vocab_size: int = 32064
  50. hidden_size: int = 3072
  51. intermediate_size: int = 8192
  52. num_hidden_layers: int = 32
  53. num_attention_heads: int = 32
  54. num_key_value_heads: int | None = None
  55. resid_pdrop: float | int = 0.0
  56. embd_pdrop: float | int = 0.0
  57. attention_dropout: float | int = 0.0
  58. hidden_act: str = "silu"
  59. max_position_embeddings: int = 4096
  60. original_max_position_embeddings: int = 4096
  61. initializer_range: float = 0.02
  62. rms_norm_eps: float = 1e-5
  63. use_cache: bool = True
  64. tie_word_embeddings: bool = False
  65. rope_parameters: RopeParameters | dict | None = None
  66. bos_token_id: int | None = 1
  67. eos_token_id: int | list[int] | None = 32000
  68. pad_token_id: int | None = 32000
  69. sliding_window: int | None = None
  70. def __post_init__(self, **kwargs):
  71. if self.num_key_value_heads is None:
  72. self.num_key_value_heads = self.num_attention_heads
  73. super().__post_init__(**kwargs)
  74. def convert_rope_params_to_dict(
  75. self, default_theta: int | float = 10_000.0, ignore_keys: set | None = None, **kwargs
  76. ):
  77. rope_scaling = kwargs.pop("rope_scaling", None)
  78. self.rope_parameters = rope_scaling or self.rope_parameters
  79. self.rope_parameters = self.rope_parameters if self.rope_parameters is not None else {}
  80. # Standardize and validate the correctness of rotary position embeddings parameters
  81. self.rope_parameters.setdefault("rope_theta", kwargs.pop("rope_theta", default_theta))
  82. self.rope_parameters.setdefault("partial_rotary_factor", kwargs.get("partial_rotary_factor", 1.0))
  83. self.standardize_rope_params()
  84. # For backward compatibility if previous version used "su" or "yarn"
  85. rope_parameters_type = self.rope_parameters.get("rope_type", None)
  86. if rope_parameters_type is not None and rope_parameters_type in ["su", "yarn"]:
  87. self.rope_parameters["rope_type"] = "longrope"
  88. return kwargs
  89. def validate_rope(self):
  90. """
  91. Validate the `rope_parameters` configuration.
  92. """
  93. super().validate_rope()
  94. # Run Phi3 specific validation
  95. if not isinstance(self.rope_parameters, dict):
  96. raise ValueError(f"`rope_parameters` must be a dictionary but got {self.rope_parameters}")
  97. rope_parameters_type = self.rope_parameters.get("rope_type", None)
  98. rope_parameters_short_factor = self.rope_parameters.get("short_factor", None)
  99. rope_parameters_long_factor = self.rope_parameters.get("long_factor", None)
  100. rotary_ndims = int(
  101. self.hidden_size // self.num_attention_heads * self.rope_parameters["partial_rotary_factor"]
  102. )
  103. if rope_parameters_type not in ["default", "longrope"]:
  104. raise ValueError(f"`rope_parameters`'s type field must be one of ['longrope'], got {rope_parameters_type}")
  105. if rope_parameters_short_factor is not None:
  106. if not (
  107. isinstance(rope_parameters_short_factor, list)
  108. and all(isinstance(x, (int, float)) for x in rope_parameters_short_factor)
  109. ):
  110. raise ValueError(
  111. f"`rope_parameters`'s short_factor field must be a list of numbers, got {rope_parameters_short_factor}"
  112. )
  113. if not len(rope_parameters_short_factor) == rotary_ndims // 2:
  114. raise ValueError(
  115. f"`rope_parameters`'s short_factor field must have length {rotary_ndims // 2}, got {len(rope_parameters_short_factor)}"
  116. )
  117. if rope_parameters_long_factor is not None:
  118. if not (
  119. isinstance(rope_parameters_long_factor, list)
  120. and all(isinstance(x, (int, float)) for x in rope_parameters_long_factor)
  121. ):
  122. raise ValueError(
  123. f"`rope_parameters`'s long_factor field must be a list of numbers, got {rope_parameters_long_factor}"
  124. )
  125. if not len(rope_parameters_long_factor) == rotary_ndims // 2:
  126. raise ValueError(
  127. f"`rope_parameters`'s long_factor field must have length {rotary_ndims // 2}, got {len(rope_parameters_long_factor)}"
  128. )
  129. __all__ = ["Phi3Config"]