modular_apertus.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Copyright 2025 the HuggingFace Inc. team and the Swiss AI Initiative. All rights reserved.
  2. #
  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 collections.abc import Callable
  16. import torch
  17. from huggingface_hub.dataclasses import strict
  18. from torch import nn
  19. from ...activations import ACT2CLS
  20. from ...cache_utils import Cache
  21. from ...configuration_utils import PreTrainedConfig
  22. from ...modeling_rope_utils import RopeParameters
  23. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS
  24. from ...processing_utils import Unpack
  25. from ...utils import TransformersKwargs, auto_docstring, logging
  26. from ..llama.modeling_llama import (
  27. LlamaAttention,
  28. LlamaDecoderLayer,
  29. LlamaForCausalLM,
  30. LlamaForTokenClassification,
  31. LlamaModel,
  32. LlamaPreTrainedModel,
  33. LlamaRMSNorm,
  34. LlamaRotaryEmbedding,
  35. apply_rotary_pos_emb,
  36. eager_attention_forward,
  37. )
  38. from ..nemotron.modeling_nemotron import NemotronMLP
  39. logger = logging.get_logger(__name__)
  40. @auto_docstring(checkpoint="swiss-ai/Apertus-8B-Instruct-2509")
  41. @strict
  42. class ApertusConfig(PreTrainedConfig):
  43. r"""
  44. ```python
  45. >>> from transformers import ApertusModel, ApertusConfig
  46. >>> # Initializing a Apertus-8B style configuration
  47. >>> configuration = ApertusConfig()
  48. >>> # Initializing a model from the Apertus-8B style configuration
  49. >>> model = ApertusModel(configuration)
  50. >>> # Accessing the model configuration
  51. >>> configuration = model.config
  52. ```"""
  53. model_type = "apertus"
  54. keys_to_ignore_at_inference = ["past_key_values"]
  55. default_theta = 12000000.0
  56. base_model_tp_plan = {
  57. "layers.*.self_attn.q_proj": "colwise",
  58. "layers.*.self_attn.k_proj": "colwise",
  59. "layers.*.self_attn.v_proj": "colwise",
  60. "layers.*.self_attn.q_norm": "replicated_with_grad_allreduce",
  61. "layers.*.self_attn.k_norm": "replicated_with_grad_allreduce",
  62. "layers.*.self_attn.o_proj": "rowwise",
  63. "layers.*.mlp.up_proj": "colwise",
  64. "layers.*.mlp.down_proj": "rowwise",
  65. }
  66. base_model_pp_plan = {
  67. "embed_tokens": (["input_ids"], ["inputs_embeds"]),
  68. "layers": (["hidden_states", "attention_mask"], ["hidden_states"]),
  69. "norm": (["hidden_states"], ["hidden_states"]),
  70. }
  71. vocab_size: int = 131072
  72. hidden_size: int = 4096
  73. intermediate_size: int = 14336
  74. num_hidden_layers: int = 32
  75. num_attention_heads: int = 32
  76. num_key_value_heads: int | None = None
  77. hidden_act: str = "xielu"
  78. max_position_embeddings: int = 65536
  79. initializer_range: float = 0.02
  80. rms_norm_eps: float = 1e-5
  81. use_cache: bool = True
  82. pad_token_id: int | None = 3
  83. bos_token_id: int | None = 1
  84. eos_token_id: int | list[int] | None = 2
  85. tie_word_embeddings: bool = False
  86. rope_parameters: RopeParameters | dict | None = None
  87. attention_bias: bool = False
  88. attention_dropout: float | int = 0.0
  89. def __post_init__(self, **kwargs):
  90. if self.num_key_value_heads is None:
  91. self.num_key_value_heads = self.num_attention_heads
  92. if self.rope_parameters is None:
  93. self.rope_parameters = {
  94. "rope_type": "llama3",
  95. "rope_theta": 12000000.0,
  96. "factor": 8.0,
  97. "original_max_position_embeddings": 8192,
  98. "low_freq_factor": 1.0,
  99. "high_freq_factor": 4.0,
  100. }
  101. super().__post_init__(**kwargs)
  102. class ApertusMLP(NemotronMLP):
  103. def __init__(self, config):
  104. super().__init__(config)
  105. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
  106. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
  107. if config.hidden_act == "xielu":
  108. self.act_fn = ACT2CLS["xielu"](dtype=config.dtype)
  109. class ApertusRMSNorm(LlamaRMSNorm):
  110. pass
  111. class ApertusRotaryEmbedding(LlamaRotaryEmbedding):
  112. pass
  113. class ApertusAttention(LlamaAttention):
  114. def __init__(self, config: ApertusConfig, layer_idx: int | None = None):
  115. super().__init__(config, layer_idx)
  116. self.q_norm = ApertusRMSNorm(self.head_dim, config.rms_norm_eps)
  117. self.k_norm = ApertusRMSNorm(self.head_dim, config.rms_norm_eps)
  118. def forward(
  119. self,
  120. hidden_states: torch.Tensor,
  121. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  122. attention_mask: torch.Tensor | None,
  123. past_key_values: Cache | None = None,
  124. **kwargs: Unpack[TransformersKwargs],
  125. ) -> tuple[torch.Tensor, torch.Tensor]:
  126. input_shape = hidden_states.shape[:-1]
  127. hidden_shape = (*input_shape, -1, self.head_dim)
  128. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  129. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  130. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  131. query_states = self.q_norm(query_states)
  132. key_states = self.k_norm(key_states)
  133. cos, sin = position_embeddings
  134. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  135. if past_key_values is not None:
  136. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx)
  137. attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
  138. self.config._attn_implementation, eager_attention_forward
  139. )
  140. attn_output, attn_weights = attention_interface(
  141. self,
  142. query_states,
  143. key_states,
  144. value_states,
  145. attention_mask,
  146. dropout=0.0 if not self.training else self.attention_dropout,
  147. scaling=self.scaling,
  148. **kwargs,
  149. )
  150. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  151. attn_output = self.o_proj(attn_output)
  152. return attn_output, attn_weights
  153. class ApertusDecoderLayer(LlamaDecoderLayer):
  154. def __init__(self, config: ApertusConfig, layer_idx: int):
  155. super().__init__(config, layer_idx)
  156. self.attention_layernorm = ApertusRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  157. self.feedforward_layernorm = ApertusRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  158. del self.input_layernorm
  159. del self.post_attention_layernorm
  160. def forward(
  161. self,
  162. hidden_states: torch.Tensor,
  163. attention_mask: torch.Tensor | None = None,
  164. position_ids: torch.LongTensor | None = None,
  165. past_key_values: Cache | None = None,
  166. use_cache: bool | None = False,
  167. position_embeddings: tuple[torch.Tensor, torch.Tensor] | None = None,
  168. **kwargs: Unpack[TransformersKwargs],
  169. ) -> torch.Tensor:
  170. residual = hidden_states
  171. hidden_states = self.attention_layernorm(hidden_states)
  172. hidden_states, _ = self.self_attn(
  173. hidden_states=hidden_states,
  174. attention_mask=attention_mask,
  175. position_ids=position_ids,
  176. past_key_values=past_key_values,
  177. use_cache=use_cache,
  178. position_embeddings=position_embeddings,
  179. **kwargs,
  180. )
  181. hidden_states = residual + hidden_states
  182. # Fully Connected
  183. residual = hidden_states
  184. hidden_states = self.feedforward_layernorm(hidden_states)
  185. hidden_states = self.mlp(hidden_states)
  186. hidden_states = residual + hidden_states
  187. return hidden_states
  188. class ApertusPreTrainedModel(LlamaPreTrainedModel):
  189. pass
  190. class ApertusModel(LlamaModel):
  191. pass
  192. class ApertusForCausalLM(LlamaForCausalLM):
  193. def forward(self, **super_kwargs):
  194. r"""
  195. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  196. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  197. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  198. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  199. Example:
  200. ```python
  201. >>> from transformers import AutoTokenizer, ApertusForCausalLM
  202. >>> model = ApertusForCausalLM.from_pretrained("swiss-ai/Apertus-8B-Instruct-2509")
  203. >>> tokenizer = AutoTokenizer.from_pretrained("swiss-ai/Apertus-8B-Instruct-2509")
  204. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  205. >>> inputs = tokenizer(prompt, return_tensors="pt")
  206. >>> # Generate
  207. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  208. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  209. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  210. ```"""
  211. return super().forward(**super_kwargs)
  212. class ApertusForTokenClassification(LlamaForTokenClassification):
  213. pass
  214. __all__ = [
  215. "ApertusConfig",
  216. "ApertusModel",
  217. "ApertusForCausalLM",
  218. "ApertusForTokenClassification",
  219. "ApertusPreTrainedModel",
  220. ]