configuration_dots1.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. # coding=utf-8
  2. # Copyright 2025 The rednote-hilab team 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. from ...configuration_utils import PretrainedConfig, layer_type_validation
  16. from ...utils import logging
  17. logger = logging.get_logger(__name__)
  18. class Dots1Config(PretrainedConfig):
  19. r"""
  20. This is the configuration class to store the configuration of a [`Dots1Model`]. It is used to instantiate a
  21. `dots.llm1` model according to the specified arguments, defining the model architecture. Instantiating a
  22. configuration with the defaults will yield a similar configuration to that of
  23. [rednote-hilab/dots.llm1.base](https://huggingface.co/rednote-hilab/dots.llm1.base).
  24. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  25. documentation from [`PretrainedConfig`] for more information.
  26. Args:
  27. vocab_size (`int`, *optional*, defaults to 152064):
  28. Vocabulary size of the model. Defines the number of different tokens that can be represented by the
  29. `input_ids` passed when calling [`Dots1Model`].
  30. hidden_size (`int`, *optional*, defaults to 4608):
  31. Dimension of the hidden representations.
  32. intermediate_size (`int`, *optional*, defaults to 10944):
  33. Dimension of the MLP representations.
  34. moe_intermediate_size (`int`, *optional*, defaults to 1408):
  35. Dimension of the MoE representations.
  36. num_hidden_layers (`int`, *optional*, defaults to 62):
  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*, defaults to 32):
  41. Number of key/value heads for Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, Multi
  42. Head Attention (MHA) is used. If `num_key_value_heads=1`, Multi Query Attention (MQA) is used. Otherwise,
  43. Grouped Query Attention (GQA) is used. If not specified, defaults to `num_attention_heads`.
  44. n_shared_experts (`int`, *optional*, default=None):
  45. Number of shared experts. None means dense model.
  46. n_routed_experts (`int`, *optional*, default=None):
  47. Number of routed experts. None means dense model.
  48. n_group (`int`, *optional*, defaults to 1):
  49. Number of groups for routed experts.
  50. topk_group (`int`, *optional*, defaults to 1):
  51. Number of selected groups for each token (selected experts only within `topk_group` groups).
  52. num_experts_per_tok (`int`, *optional*, default=None):
  53. Number of selected experts. None means dense model.
  54. first_k_dense_replace (`int`, *optional*, defaults to 0):
  55. Number of dense layers at the beginning of the model before the first MoE layer.
  56. norm_topk_prob (`bool`, *optional*, defaults to `False`):
  57. Whether to normalize the weights of the routed experts.
  58. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
  59. The non-linear activation function (function or string).
  60. max_position_embeddings (`int`, *optional*, defaults to 2048):
  61. Maximum sequence length the model might ever be used with.
  62. initializer_range (`float`, *optional*, defaults to 0.02):
  63. Standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  64. rms_norm_eps (`float`, *optional*, defaults to 1e-06):
  65. Epsilon used by the RMS normalization layers.
  66. use_cache (`bool`, *optional*, defaults to `True`):
  67. Whether or not the model should return the last key/values attentions. Only relevant if `config.is_decoder=True`.
  68. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  69. Whether to tie the input and output word embeddings.
  70. rope_theta (`float`, *optional*, defaults to 10000.0):
  71. The base period of the RoPE embeddings.
  72. rope_scaling (`dict`, *optional*):
  73. Dictionary for scaling RoPE embeddings. Supports `{"type": strategy name, "factor": scaling factor}`.
  74. attention_bias (`bool`, *optional*, defaults to `False`):
  75. Whether to use a bias in the self-attention projections.
  76. attention_dropout (`float`, *optional*, defaults to 0.0):
  77. Dropout ratio for the attention probabilities.
  78. routed_scaling_factor (`float`, *optional*, defaults to 1.0):
  79. Scaling factor for routed experts.
  80. sliding_window (`int`, *optional*, defaults to 4096):
  81. Size of the sliding window for attention. If not specified, defaults to `4096`.
  82. max_window_layers (`int`, *optional*, defaults to 62):
  83. The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
  84. additional layer afterwards will use SWA (Sliding Window Attention).
  85. layer_types (`list`, *optional*):
  86. Attention pattern for each layer.
  87. Examples:
  88. ```python
  89. >>> from transformers import Dots1Model, Dots1Config
  90. >>> # Initializing a Dots1 style configuration
  91. >>> configuration = Dots1Config()
  92. >>> # Accessing the model configuration
  93. >>> configuration = model.config
  94. ```
  95. """
  96. model_type = "dots1"
  97. keys_to_ignore_at_inference = ["past_key_values"]
  98. base_model_tp_plan = { # TODO: only replicate attention layers when > first_k_dense_replace
  99. "layers.*.self_attn.q_proj": "colwise",
  100. "layers.*.self_attn.k_proj": "colwise",
  101. "layers.*.self_attn.v_proj": "colwise",
  102. "layers.*.self_attn.o_proj": "rowwise",
  103. "layers.*.mlp.experts.*.gate_proj": "local_colwise",
  104. "layers.*.mlp.experts.*.up_proj": "local_colwise",
  105. "layers.*.mlp.experts.*.down_proj": "local_rowwise",
  106. "layers.*.mlp.experts.*": "local", # each expert is wrapped in a module list
  107. "layers.*.mlp.shared_experts.gate_proj": "local_colwise",
  108. "layers.*.mlp.shared_experts.up_proj": "local_colwise",
  109. "layers.*.mlp.shared_experts.down_proj": "local_rowwise",
  110. "layers.*.mlp.shared_experts": "local",
  111. "layers.*.mlp.gate_proj": "local_colwise",
  112. "layers.*.mlp.up_proj": "local_colwise",
  113. "layers.*.mlp.down_proj": "local_rowwise",
  114. "layers.*.mlp": "gather", # This is the only moment where results are gathered
  115. }
  116. base_model_pp_plan = {
  117. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  118. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  119. "norm": (["hidden_states"], ["hidden_states"]),
  120. }
  121. def __init__(
  122. self,
  123. vocab_size=152064,
  124. hidden_size=4608,
  125. intermediate_size=10944,
  126. moe_intermediate_size=1408,
  127. num_hidden_layers=62,
  128. num_attention_heads=32,
  129. num_key_value_heads=32,
  130. n_shared_experts=None,
  131. n_routed_experts=None,
  132. n_group=1,
  133. topk_group=1,
  134. num_experts_per_tok=None,
  135. first_k_dense_replace=0,
  136. norm_topk_prob=False,
  137. hidden_act="silu",
  138. max_position_embeddings=2048,
  139. initializer_range=0.02,
  140. rms_norm_eps=1e-6,
  141. use_cache=True,
  142. tie_word_embeddings=False,
  143. rope_theta=10000.0,
  144. rope_scaling=None,
  145. attention_bias=False,
  146. attention_dropout=0.0,
  147. routed_scaling_factor=1.0,
  148. sliding_window=4096,
  149. max_window_layers=62,
  150. layer_types=None,
  151. **kwargs,
  152. ):
  153. self.vocab_size = vocab_size
  154. self.max_position_embeddings = max_position_embeddings
  155. self.hidden_size = hidden_size
  156. self.intermediate_size = intermediate_size
  157. self.moe_intermediate_size = moe_intermediate_size
  158. self.num_hidden_layers = num_hidden_layers
  159. self.num_attention_heads = num_attention_heads
  160. self.n_shared_experts = n_shared_experts
  161. self.n_routed_experts = n_routed_experts
  162. self.num_experts_per_tok = num_experts_per_tok
  163. self.first_k_dense_replace = first_k_dense_replace
  164. self.norm_topk_prob = norm_topk_prob
  165. if num_key_value_heads is None:
  166. num_key_value_heads = num_attention_heads
  167. self.n_group = n_group
  168. self.topk_group = topk_group
  169. self.num_key_value_heads = num_key_value_heads
  170. self.hidden_act = hidden_act
  171. self.initializer_range = initializer_range
  172. self.rms_norm_eps = rms_norm_eps
  173. self.use_cache = use_cache
  174. self.rope_theta = rope_theta
  175. self.rope_scaling = rope_scaling
  176. self.attention_bias = attention_bias
  177. self.attention_dropout = attention_dropout
  178. self.routed_scaling_factor = routed_scaling_factor
  179. self.sliding_window = sliding_window
  180. self.max_window_layers = max_window_layers
  181. self.layer_types = layer_types
  182. if self.layer_types is None:
  183. self.layer_types = [
  184. "sliding_attention"
  185. if self.sliding_window is not None and i >= self.max_window_layers
  186. else "full_attention"
  187. for i in range(self.num_hidden_layers)
  188. ]
  189. layer_type_validation(self.layer_types, self.num_hidden_layers)
  190. super().__init__(
  191. tie_word_embeddings=tie_word_embeddings,
  192. **kwargs,
  193. )
  194. __all__ = ["Dots1Config"]