modular_arcee.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # coding=utf-8
  2. # Copyright 2025 Arcee AI 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. """PyTorch Arcee model."""
  16. from transformers.utils import auto_docstring, logging
  17. from ..llama.configuration_llama import LlamaConfig
  18. from ..llama.modeling_llama import (
  19. LlamaForCausalLM,
  20. LlamaForQuestionAnswering,
  21. LlamaForSequenceClassification,
  22. LlamaForTokenClassification,
  23. )
  24. from ..nemotron.modeling_nemotron import NemotronMLP
  25. logger = logging.get_logger(__name__)
  26. class ArceeConfig(LlamaConfig):
  27. r"""
  28. This is the configuration class to store the configuration of a [`ArceeModel`]. It is used to instantiate an Arcee
  29. model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
  30. defaults will yield a similar configuration to that of the AFM-4.5B-Base.
  31. Pre-trained weights are available at
  32. [arcee-ai/AFM-4.5B](https://huggingface.co/arcee-ai/AFM-4.5B)
  33. and were used to build the examples below.
  34. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  35. documentation from [`PretrainedConfig`] for more information.
  36. Args:
  37. vocab_size (`int`, *optional*, defaults to 32000):
  38. Vocabulary size of the Arcee model. Defines the number of different tokens that can be represented by the
  39. `inputs_ids` passed when calling [`ArceeModel`]
  40. hidden_size (`int`, *optional*, defaults to 2560):
  41. Dimension of the hidden representations.
  42. intermediate_size (`int`, *optional*, defaults to 18432):
  43. Dimension of the MLP representations.
  44. num_hidden_layers (`int`, *optional*, defaults to 32):
  45. Number of hidden layers in the Transformer decoder.
  46. num_attention_heads (`int`, *optional*, defaults to 32):
  47. Number of attention heads for each attention layer in the Transformer decoder.
  48. num_key_value_heads (`int`, *optional*):
  49. This is the number of key_value heads that should be used to implement Grouped Query Attention. If
  50. `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
  51. `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used. When
  52. converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
  53. by meanpooling all the original heads within that group. For more details checkout [this
  54. paper](https://huggingface.co/papers/2305.13245). If it is not specified, will default to
  55. `num_attention_heads`.
  56. hidden_act (`str` or `function`, *optional*, defaults to `"relu2"`):
  57. The non-linear activation function (function or string) in the decoder.
  58. max_position_embeddings (`int`, *optional*, defaults to 4096):
  59. The maximum sequence length that this model might ever be used with. AFM-4.5B-Base supports up to 16384 tokens.
  60. initializer_range (`float`, *optional*, defaults to 0.02):
  61. The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
  62. rms_norm_eps (`float`, *optional*, defaults to 1e-05):
  63. The epsilon used by the rms normalization layers.
  64. use_cache (`bool`, *optional*, defaults to `True`):
  65. Whether or not the model should return the last key/values attentions (not used by all models). Only
  66. relevant if `config.is_decoder=True`.
  67. pad_token_id (`int`, *optional*):
  68. Padding token id.
  69. bos_token_id (`int`, *optional*, defaults to 128000):
  70. Beginning of stream token id.
  71. eos_token_id (`int`, *optional*, defaults to 128001):
  72. End of stream token id.
  73. tie_word_embeddings (`bool`, *optional*, defaults to `False`):
  74. Whether to tie weight embeddings
  75. rope_theta (`float`, *optional*, defaults to 10000.0):
  76. The base period of the RoPE embeddings.
  77. rope_scaling (`Dict`, *optional*):
  78. Dictionary containing the scaling configuration for the RoPE embeddings. NOTE: if you apply new rope type
  79. and you expect the model to work on longer `max_position_embeddings`, we recommend you to update this value
  80. accordingly.
  81. Expected contents:
  82. `rope_type` (`str`):
  83. The sub-variant of RoPE to use. Can be one of ['default', 'yarn'], with 'default' being the original RoPE implementation.
  84. `factor` (`float`, *optional*):
  85. Used with all rope types except 'default'. The scaling factor to apply to the RoPE embeddings. In
  86. most scaling types, a `factor` of x will enable the model to handle sequences of length x *
  87. original maximum pre-trained length.
  88. `original_max_position_embeddings` (`int`, *optional*):
  89. Used with 'yarn'. The original max position embeddings used during pretraining.
  90. `attention_factor` (`float`, *optional*):
  91. Used with 'yarn'. The scaling factor to be applied on the attention computation. If unspecified,
  92. it defaults to value recommended by the implementation, using the `factor` field to infer the suggested value.
  93. `beta_fast` (`float`, *optional*):
  94. Only used with 'yarn'. Parameter to set the boundary for extrapolation (only) in the linear
  95. ramp function. If unspecified, it defaults to 32.
  96. `beta_slow` (`float`, *optional*):
  97. Only used with 'yarn'. Parameter to set the boundary for interpolation (only) in the linear
  98. ramp function. If unspecified, it defaults to 1.
  99. attention_bias (`bool`, *optional*, defaults to `False`):
  100. Whether to use a bias in the query, key, value and output projection layers during self-attention.
  101. attention_dropout (`float`, *optional*, defaults to 0.0):
  102. The dropout ratio for the attention probabilities.
  103. mlp_bias (`bool`, *optional*, defaults to `False`):
  104. Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
  105. head_dim (`int`, *optional*):
  106. The attention head dimension. If None, it will default to hidden_size // num_attention_heads
  107. ```python
  108. >>> from transformers import ArceeModel, ArceeConfig
  109. >>> # Initializing an Arcee AFM-4.5B-Base style configuration
  110. >>> configuration = ArceeConfig()
  111. >>> # Initializing a model from the AFM-4.5B-Base style configuration
  112. >>> model = ArceeModel(configuration)
  113. >>> # Accessing the model configuration
  114. >>> configuration = model.config
  115. ```"""
  116. model_type = "arcee"
  117. base_model_tp_plan = {
  118. "layers.*.self_attn.q_proj": "colwise",
  119. "layers.*.self_attn.k_proj": "colwise",
  120. "layers.*.self_attn.v_proj": "colwise",
  121. "layers.*.self_attn.o_proj": "rowwise",
  122. "layers.*.mlp.up_proj": "colwise",
  123. "layers.*.mlp.down_proj": "rowwise",
  124. }
  125. def __init__(
  126. self,
  127. vocab_size=32000,
  128. hidden_size=2560,
  129. intermediate_size=18432,
  130. num_hidden_layers=32,
  131. num_attention_heads=32,
  132. num_key_value_heads=None,
  133. hidden_act="relu2",
  134. max_position_embeddings=4096,
  135. initializer_range=0.02,
  136. rms_norm_eps=1e-5,
  137. use_cache=True,
  138. pad_token_id=None,
  139. bos_token_id=128000,
  140. eos_token_id=128001,
  141. tie_word_embeddings=False,
  142. rope_theta=10000.0,
  143. rope_scaling=None,
  144. attention_bias=False,
  145. attention_dropout=0.0,
  146. mlp_bias=False,
  147. head_dim=None,
  148. **kwargs,
  149. ):
  150. super().__init__(
  151. vocab_size=vocab_size,
  152. hidden_size=hidden_size,
  153. intermediate_size=intermediate_size,
  154. num_hidden_layers=num_hidden_layers,
  155. num_attention_heads=num_attention_heads,
  156. num_key_value_heads=num_key_value_heads,
  157. hidden_act=hidden_act,
  158. max_position_embeddings=max_position_embeddings,
  159. initializer_range=initializer_range,
  160. rms_norm_eps=rms_norm_eps,
  161. use_cache=use_cache,
  162. pad_token_id=pad_token_id,
  163. bos_token_id=bos_token_id,
  164. eos_token_id=eos_token_id,
  165. tie_word_embeddings=tie_word_embeddings,
  166. rope_theta=rope_theta,
  167. rope_scaling=rope_scaling,
  168. attention_bias=attention_bias,
  169. attention_dropout=attention_dropout,
  170. mlp_bias=mlp_bias,
  171. head_dim=head_dim,
  172. **kwargs,
  173. )
  174. del self.pretraining_tp
  175. class ArceeMLP(NemotronMLP):
  176. pass
  177. @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
  178. class ArceeForCausalLM(LlamaForCausalLM):
  179. pass
  180. @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
  181. class ArceeForSequenceClassification(LlamaForSequenceClassification):
  182. pass
  183. @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
  184. class ArceeForQuestionAnswering(LlamaForQuestionAnswering):
  185. pass
  186. @auto_docstring(checkpoint="arcee-ai/AFM-4.5B")
  187. class ArceeForTokenClassification(LlamaForTokenClassification):
  188. pass
  189. __all__ = [
  190. "ArceeConfig",
  191. "ArceeForCausalLM",
  192. "ArceeForQuestionAnswering",
  193. "ArceeForSequenceClassification",
  194. "ArceeForTokenClassification",
  195. "ArceeModel", # noqa: F822
  196. "ArceePreTrainedModel", # noqa: F822
  197. ]