modular_smollm3.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. # Copyright 2025 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. from collections.abc import Callable
  15. import torch
  16. from huggingface_hub.dataclasses import strict
  17. from ...cache_utils import Cache
  18. from ...configuration_utils import PreTrainedConfig
  19. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  20. from ...modeling_rope_utils import RopeParameters
  21. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
  22. from ...processing_utils import Unpack
  23. from ...utils import auto_docstring, logging
  24. from ..llama.modeling_llama import (
  25. LlamaAttention,
  26. LlamaDecoderLayer,
  27. LlamaForCausalLM,
  28. LlamaForQuestionAnswering,
  29. LlamaForSequenceClassification,
  30. LlamaForTokenClassification,
  31. LlamaPreTrainedModel,
  32. apply_rotary_pos_emb,
  33. eager_attention_forward,
  34. )
  35. from ..qwen2.modeling_qwen2 import Qwen2Model, Qwen2RotaryEmbedding
  36. logger = logging.get_logger(__name__)
  37. @auto_docstring(checkpoint="HuggingFaceTB/SmolLM3-3B")
  38. @strict
  39. class SmolLM3Config(PreTrainedConfig):
  40. r"""
  41. no_rope_layers (`List[int]`, *optional*):
  42. List with at least the same length as the number of layers in the model.
  43. A `1` at an index position indicates that the corresponding layer will use RoPE,
  44. while a `0` indicates that it's a NoPE layer.
  45. no_rope_layer_interval (`int`, *optional*, defaults to 4):
  46. If `no_rope_layers` is `None`, it will be created using a NoPE layer every
  47. `no_rope_layer_interval` layers.
  48. ```python
  49. >>> from transformers import SmolLM3Model, SmolLM3Config
  50. >>> # Initializing a SmolLM3 style configuration
  51. >>> configuration = SmolLM3Config()
  52. >>> # Initializing a model from the SmolLM3 style configuration
  53. >>> model = SmolLM3Model(configuration)
  54. >>> # Accessing the model configuration
  55. >>> configuration = model.config
  56. ```"""
  57. model_type = "smollm3"
  58. keys_to_ignore_at_inference = ["past_key_values"]
  59. default_theta = 2000000.0
  60. base_model_tp_plan = {
  61. "layers.*.self_attn.q_proj": "colwise",
  62. "layers.*.self_attn.k_proj": "colwise",
  63. "layers.*.self_attn.v_proj": "colwise",
  64. "layers.*.self_attn.o_proj": "rowwise",
  65. "layers.*.mlp.gate_proj": "colwise",
  66. "layers.*.mlp.up_proj": "colwise",
  67. "layers.*.mlp.down_proj": "rowwise",
  68. }
  69. base_model_pp_plan = {
  70. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  71. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  72. "norm": (["hidden_states"], ["hidden_states"]),
  73. }
  74. vocab_size: int = 128256
  75. hidden_size: int = 2048
  76. intermediate_size: int = 11008
  77. num_hidden_layers: int = 36
  78. num_attention_heads: int = 16
  79. num_key_value_heads: int | None = 4
  80. hidden_act: str = "silu"
  81. max_position_embeddings: int = 32768
  82. initializer_range: float = 0.02
  83. rms_norm_eps: float = 1e-6
  84. use_cache: bool = True
  85. pad_token_id: int | None = 128004
  86. bos_token_id: int | None = 128000
  87. eos_token_id: int | list[int] | None = 128001
  88. rope_parameters: RopeParameters | dict | None = None
  89. use_sliding_window: bool = False
  90. sliding_window: int | None = None
  91. no_rope_layers: list[int] | None = None
  92. no_rope_layer_interval: int = 4
  93. layer_types: list[str] | None = None
  94. attention_bias: bool = False
  95. attention_dropout: float | int = 0.0
  96. mlp_bias: bool = False
  97. tie_word_embeddings: bool = True
  98. def __post_init__(self, **kwargs):
  99. if self.num_key_value_heads is None:
  100. self.num_key_value_heads = self.num_attention_heads
  101. if self.no_rope_layers is None:
  102. self.no_rope_layers = [
  103. int((layer_idx + 1) % self.no_rope_layer_interval != 0) for layer_idx in range(self.num_hidden_layers)
  104. ]
  105. if self.layer_types is None:
  106. self.layer_types = []
  107. for layer_idx in range(self.num_hidden_layers):
  108. has_rope = self.no_rope_layers[layer_idx]
  109. if self.use_sliding_window and self.sliding_window is not None and not has_rope:
  110. self.layer_types.append("sliding_attention")
  111. else:
  112. self.layer_types.append("full_attention")
  113. super().__post_init__(**kwargs)
  114. class SmolLM3RotaryEmbedding(Qwen2RotaryEmbedding):
  115. pass
  116. class SmolLM3Attention(LlamaAttention):
  117. def __init__(self, config: SmolLM3Config, layer_idx: int):
  118. super().__init__(config, layer_idx)
  119. self.use_rope = config.no_rope_layers[layer_idx]
  120. self.sliding_window = (
  121. config.sliding_window
  122. if config.use_sliding_window and config.layer_types[layer_idx] == "sliding_attention"
  123. else None
  124. )
  125. def forward(
  126. self,
  127. hidden_states: torch.Tensor,
  128. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  129. attention_mask: torch.Tensor | None,
  130. past_key_values: Cache | None = None,
  131. **kwargs: Unpack[FlashAttentionKwargs],
  132. ) -> tuple[torch.Tensor, torch.Tensor | None]:
  133. input_shape = hidden_states.shape[:-1]
  134. hidden_shape = (*input_shape, -1, self.head_dim)
  135. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  136. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  137. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  138. if self.use_rope:
  139. cos, sin = position_embeddings
  140. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  141. if past_key_values is not None:
  142. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  143. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  144. self.config._attn_implementation, eager_attention_forward
  145. )
  146. attn_output, attn_weights = attention_interface(
  147. self,
  148. query_states,
  149. key_states,
  150. value_states,
  151. attention_mask,
  152. dropout=0.0 if not self.training else self.attention_dropout,
  153. scaling=self.scaling,
  154. sliding_window=self.sliding_window,
  155. **kwargs,
  156. )
  157. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  158. attn_output = self.o_proj(attn_output)
  159. return attn_output, attn_weights
  160. class SmolLM3DecoderLayer(LlamaDecoderLayer):
  161. pass
  162. class SmolLM3PreTrainedModel(LlamaPreTrainedModel):
  163. pass
  164. class SmolLM3Model(Qwen2Model):
  165. pass
  166. class SmolLM3ForCausalLM(LlamaForCausalLM):
  167. pass
  168. class SmolLM3ForSequenceClassification(LlamaForSequenceClassification):
  169. pass
  170. class SmolLM3ForTokenClassification(LlamaForTokenClassification):
  171. pass
  172. class SmolLM3ForQuestionAnswering(LlamaForQuestionAnswering):
  173. pass
  174. __all__ = [
  175. "SmolLM3Config",
  176. "SmolLM3PreTrainedModel",
  177. "SmolLM3Model",
  178. "SmolLM3ForCausalLM",
  179. "SmolLM3ForSequenceClassification",
  180. "SmolLM3ForTokenClassification",
  181. "SmolLM3ForQuestionAnswering",
  182. ]