1
0

arctic.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. # yapf: disable
  2. # ruff: noqa: E501
  3. # coding=utf-8
  4. # Copied from
  5. # https://huggingface.co/Snowflake/snowflake-arctic-instruct/blob/main/configuration_arctic.py
  6. """ Arctic model configuration"""
  7. from dataclasses import asdict, dataclass
  8. from typing import Any, Dict
  9. from transformers.configuration_utils import PretrainedConfig
  10. from transformers.utils import logging
  11. logger = logging.get_logger(__name__)
  12. ARCTIC_PRETRAINED_CONFIG_ARCHIVE_MAP = {
  13. "arctic": "https://huggingface.co/Snowflake/snowflake-arctic-instruct/tree/main/config.json",
  14. }
  15. @dataclass
  16. class ArcticLoraConfig:
  17. lora_r: int = 64
  18. lora_alpha: float = 16
  19. shard_base_weights: bool = False
  20. @dataclass
  21. class ArcticQuantizationConfig:
  22. q_bits: int = 8
  23. rounding: str = "nearest"
  24. mantissa_bits: int = 3
  25. group_size: int = 128
  26. class ArcticConfig(PretrainedConfig):
  27. r"""
  28. This is the configuration class to store the configuration of a [`ArcticModel`]. It is used to instantiate an
  29. Arctic model according to the specified arguments, defining the model architecture. Instantiating a configuration
  30. with the defaults will yield a similar configuration to that of the #TODO(rsamdani): add what model has the default config..
  31. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  32. documentation from [`PretrainedConfig`] for more information.
  33. Args:
  34. vocab_size (`int`, *optional*, defaults to 32000):
  35. Vocabulary size of the Arctic model. Defines the number of different tokens that can be represented by the
  36. `inputs_ids` passed when calling [`ArcticModel`]
  37. hidden_size (`int`, *optional*, defaults to 4096):
  38. Dimension of the hidden representations.
  39. intermediate_size (`int`, *optional*, defaults to 14336):
  40. Dimension of the MLP representations.
  41. num_hidden_layers (`int`, *optional*, defaults to 32):
  42. Number of hidden layers in the Transformer encoder.
  43. num_attention_heads (`int`, *optional*, defaults to 32):
  44. Number of attention heads for each attention layer in the Transformer encoder.
  45. num_key_value_heads (`int`, *optional*, defaults to 8):
  46. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  47. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  48. `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  49. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  50. by meanpooling all the original heads within that group. For more details checkout [this
  51. paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`.
  52. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  53. The non-linear activation function (function or string) in the decoder.
  54. max_position_embeddings (`int`, *optional*, defaults to `4096*32`):
  55. The maximum sequence length that this model might ever be used with. Arctic's sliding window attention
  56. allows sequence of up to 4096*32 tokens.
  57. initializer_range (`float`, *optional*, defaults to 0.02):
  58. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  59. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  60. The epsilon used by the rms normalization layers.
  61. use_cache (`bool`, *optional*, defaults to `True`):
  62. Whether or not the model should return the last key/values attentions (not used by all models). Only
  63. relevant if `config.is_decoder=True`.
  64. pad_token_id (`int`, *optional*):
  65. The id of the padding token.
  66. bos_token_id (`int`, *optional*, defaults to 1):
  67. The id of the "beginning-of-sequence" token.
  68. eos_token_id (`int`, *optional*, defaults to 2):
  69. The id of the "end-of-sequence" token.
  70. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  71. Whether the model's input and output word embeddings should be tied.
  72. rope_theta (`float`, *optional*, defaults to 1000000.0):
  73. The base period of the RoPE embeddings.
  74. sliding_window (`int`, *optional*):
  75. Sliding window attention window size. If not specified, will default to `4096`.
  76. attention_dropout (`float`, *optional*, defaults to 0.0):
  77. The dropout ratio for the attention probabilities.
  78. num_experts_per_tok (`int`, *optional*, defaults to 2):
  79. The number of experts to root per-token, can be also interpreted as the `top-p` routing
  80. parameter
  81. num_local_experts (`int`, *optional*, defaults to 8):
  82. Number of experts per Sparse MLP layer.
  83. router_aux_loss_coef (`float`, *optional*, defaults to 0.001):
  84. The aux loss factor for the total loss.
  85. ```python
  86. >>> from transformers import ArcticModel, ArcticConfig
  87. >>> # Initializing a Arctic 7B style configuration TODO(rsamdani): verify which model does the default configuration correspond to.
  88. >>> configuration = ArcticConfig()
  89. >>> # Initializing a model from the Arctic 7B style configuration
  90. >>> model = ArcticModel(configuration)
  91. >>> # Accessing the model configuration
  92. >>> configuration = model.config
  93. ```"""
  94. model_type = "arctic"
  95. keys_to_ignore_at_inference = ["past_key_values"]
  96. def __init__(
  97. self,
  98. vocab_size=32000,
  99. hidden_size=4096,
  100. intermediate_size=14336,
  101. num_hidden_layers=32,
  102. num_attention_heads=32,
  103. num_key_value_heads=None,
  104. hidden_act="silu",
  105. max_position_embeddings=4096,
  106. initializer_range=0.02,
  107. rms_norm_eps=1e-5,
  108. use_cache=True,
  109. pad_token_id=None,
  110. bos_token_id=1,
  111. eos_token_id=2,
  112. tie_word_embeddings=False,
  113. rope_theta=1e6,
  114. sliding_window=None,
  115. attention_dropout=0.0,
  116. num_experts_per_tok=1,
  117. num_local_experts=8,
  118. router_aux_loss_coef=0.001,
  119. moe_layer_frequency=2,
  120. parallel_attn_mlp_res=False,
  121. moe_train_capacity_factor=1,
  122. moe_eval_capacity_factor=1,
  123. enable_expert_tensor_parallelism=False,
  124. moe_min_capacity=0,
  125. moe_token_dropping=True,
  126. quantization=None,
  127. **kwargs,
  128. ):
  129. self.vocab_size = vocab_size
  130. self.max_position_embeddings = max_position_embeddings
  131. self.hidden_size = hidden_size
  132. self.intermediate_size = intermediate_size
  133. self.num_hidden_layers = num_hidden_layers
  134. self.num_attention_heads = num_attention_heads
  135. self.sliding_window = sliding_window
  136. # for backward compatibility
  137. if num_key_value_heads is None:
  138. num_key_value_heads = num_attention_heads
  139. self.num_key_value_heads = num_key_value_heads
  140. self.hidden_act = hidden_act
  141. self.initializer_range = initializer_range
  142. self.rms_norm_eps = rms_norm_eps
  143. self.use_cache = use_cache
  144. self.rope_theta = rope_theta
  145. self.attention_dropout = attention_dropout
  146. self.num_experts_per_tok = num_experts_per_tok
  147. self.num_local_experts = num_local_experts
  148. self.router_aux_loss_coef = router_aux_loss_coef
  149. self.moe_layer_frequency = moe_layer_frequency
  150. self.moe_train_capacity_factor = moe_train_capacity_factor
  151. self.moe_eval_capacity_factor = moe_eval_capacity_factor
  152. self.enable_expert_tensor_parallelism = enable_expert_tensor_parallelism
  153. self.moe_min_capacity = moe_min_capacity
  154. self.moe_token_dropping = moe_token_dropping
  155. self.parallel_attn_mlp_res = parallel_attn_mlp_res
  156. if isinstance(quantization, dict):
  157. self.quantization = ArcticQuantizationConfig(**quantization)
  158. else:
  159. self.quantization = quantization
  160. super().__init__(
  161. pad_token_id=pad_token_id,
  162. bos_token_id=bos_token_id,
  163. eos_token_id=eos_token_id,
  164. tie_word_embeddings=tie_word_embeddings,
  165. **kwargs,
  166. )
  167. @classmethod
  168. def from_dict(cls, config_dict: Dict[str, Any], **kwargs) -> "ArcticConfig":
  169. result = super().from_dict(config_dict, **kwargs)
  170. config = result[0] if isinstance(result, tuple) else result
  171. if isinstance(config.quantization, dict):
  172. config.quantization = ArcticQuantizationConfig(**config.quantization)
  173. return result
  174. def to_dict(self) -> Dict[str, Any]:
  175. ret = super().to_dict()
  176. if isinstance(ret["quantization"], ArcticQuantizationConfig):
  177. ret["quantization"] = asdict(ret["quantization"])
  178. return ret