modeling_smollm3.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  2. # This file was automatically generated from src/transformers/models/smollm3/modular_smollm3.py.
  3. # Do NOT edit this file manually as any edits will be overwritten by the generation of
  4. # the file from the modular. If any change should be done, please apply the change to the
  5. # modular_smollm3.py file directly. One of our CI enforces this.
  6. # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
  7. # coding=utf-8
  8. # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
  9. #
  10. # Licensed under the Apache License, Version 2.0 (the "License");
  11. # you may not use this file except in compliance with the License.
  12. # You may obtain a copy of the License at
  13. #
  14. # http://www.apache.org/licenses/LICENSE-2.0
  15. #
  16. # Unless required by applicable law or agreed to in writing, software
  17. # distributed under the License is distributed on an "AS IS" BASIS,
  18. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. # See the License for the specific language governing permissions and
  20. # limitations under the License.
  21. from typing import Callable, Optional, Union
  22. import torch
  23. from torch import nn
  24. from ...activations import ACT2FN
  25. from ...cache_utils import Cache, DynamicCache
  26. from ...generation import GenerationMixin
  27. from ...integrations import use_kernel_forward_from_hub
  28. from ...masking_utils import create_causal_mask, create_sliding_window_causal_mask
  29. from ...modeling_flash_attention_utils import FlashAttentionKwargs
  30. from ...modeling_layers import (
  31. GenericForQuestionAnswering,
  32. GenericForSequenceClassification,
  33. GenericForTokenClassification,
  34. GradientCheckpointingLayer,
  35. )
  36. from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
  37. from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
  38. from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
  39. from ...processing_utils import Unpack
  40. from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
  41. from ...utils.deprecation import deprecate_kwarg
  42. from ...utils.generic import check_model_inputs
  43. from .configuration_smollm3 import SmolLM3Config
  44. def rotate_half(x):
  45. """Rotates half the hidden dims of the input."""
  46. x1 = x[..., : x.shape[-1] // 2]
  47. x2 = x[..., x.shape[-1] // 2 :]
  48. return torch.cat((-x2, x1), dim=-1)
  49. def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
  50. """Applies Rotary Position Embedding to the query and key tensors.
  51. Args:
  52. q (`torch.Tensor`): The query tensor.
  53. k (`torch.Tensor`): The key tensor.
  54. cos (`torch.Tensor`): The cosine part of the rotary embedding.
  55. sin (`torch.Tensor`): The sine part of the rotary embedding.
  56. position_ids (`torch.Tensor`, *optional*):
  57. Deprecated and unused.
  58. unsqueeze_dim (`int`, *optional*, defaults to 1):
  59. The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
  60. sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
  61. that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
  62. k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
  63. cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
  64. the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
  65. Returns:
  66. `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
  67. """
  68. cos = cos.unsqueeze(unsqueeze_dim)
  69. sin = sin.unsqueeze(unsqueeze_dim)
  70. q_embed = (q * cos) + (rotate_half(q) * sin)
  71. k_embed = (k * cos) + (rotate_half(k) * sin)
  72. return q_embed, k_embed
  73. def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
  74. """
  75. This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
  76. num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
  77. """
  78. batch, num_key_value_heads, slen, head_dim = hidden_states.shape
  79. if n_rep == 1:
  80. return hidden_states
  81. hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
  82. return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
  83. def eager_attention_forward(
  84. module: nn.Module,
  85. query: torch.Tensor,
  86. key: torch.Tensor,
  87. value: torch.Tensor,
  88. attention_mask: Optional[torch.Tensor],
  89. scaling: float,
  90. dropout: float = 0.0,
  91. **kwargs: Unpack[TransformersKwargs],
  92. ):
  93. key_states = repeat_kv(key, module.num_key_value_groups)
  94. value_states = repeat_kv(value, module.num_key_value_groups)
  95. attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
  96. if attention_mask is not None:
  97. causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
  98. attn_weights = attn_weights + causal_mask
  99. attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
  100. attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
  101. attn_output = torch.matmul(attn_weights, value_states)
  102. attn_output = attn_output.transpose(1, 2).contiguous()
  103. return attn_output, attn_weights
  104. class SmolLM3Attention(nn.Module):
  105. """Multi-headed attention from 'Attention Is All You Need' paper"""
  106. def __init__(self, config: SmolLM3Config, layer_idx: int):
  107. super().__init__()
  108. self.config = config
  109. self.layer_idx = layer_idx
  110. self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
  111. self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
  112. self.scaling = self.head_dim**-0.5
  113. self.attention_dropout = config.attention_dropout
  114. self.is_causal = True
  115. self.q_proj = nn.Linear(
  116. config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
  117. )
  118. self.k_proj = nn.Linear(
  119. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  120. )
  121. self.v_proj = nn.Linear(
  122. config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
  123. )
  124. self.o_proj = nn.Linear(
  125. config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
  126. )
  127. self.use_rope = config.no_rope_layers[layer_idx]
  128. self.sliding_window = (
  129. config.sliding_window
  130. if config.use_sliding_window and config.layer_types[layer_idx] == "sliding_attention"
  131. else None
  132. )
  133. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  134. def forward(
  135. self,
  136. hidden_states: torch.Tensor,
  137. position_embeddings: tuple[torch.Tensor, torch.Tensor],
  138. attention_mask: Optional[torch.Tensor],
  139. past_key_values: Optional[Cache] = None,
  140. cache_position: Optional[torch.LongTensor] = None,
  141. **kwargs: Unpack[FlashAttentionKwargs],
  142. ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
  143. input_shape = hidden_states.shape[:-1]
  144. hidden_shape = (*input_shape, -1, self.head_dim)
  145. query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  146. key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  147. value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
  148. if self.use_rope:
  149. cos, sin = position_embeddings
  150. query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
  151. if past_key_values is not None:
  152. cache_kwargs = {"cache_position": cache_position}
  153. key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
  154. attention_interface: Callable = eager_attention_forward
  155. if self.config._attn_implementation != "eager":
  156. attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
  157. attn_output, attn_weights = attention_interface(
  158. self,
  159. query_states,
  160. key_states,
  161. value_states,
  162. attention_mask,
  163. dropout=0.0 if not self.training else self.attention_dropout,
  164. scaling=self.scaling,
  165. sliding_window=self.sliding_window,
  166. **kwargs,
  167. )
  168. attn_output = attn_output.reshape(*input_shape, -1).contiguous()
  169. attn_output = self.o_proj(attn_output)
  170. return attn_output, attn_weights
  171. @use_kernel_forward_from_hub("RMSNorm")
  172. class SmolLM3RMSNorm(nn.Module):
  173. def __init__(self, hidden_size, eps=1e-6):
  174. """
  175. SmolLM3RMSNorm is equivalent to T5LayerNorm
  176. """
  177. super().__init__()
  178. self.weight = nn.Parameter(torch.ones(hidden_size))
  179. self.variance_epsilon = eps
  180. def forward(self, hidden_states):
  181. input_dtype = hidden_states.dtype
  182. hidden_states = hidden_states.to(torch.float32)
  183. variance = hidden_states.pow(2).mean(-1, keepdim=True)
  184. hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
  185. return self.weight * hidden_states.to(input_dtype)
  186. def extra_repr(self):
  187. return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
  188. class SmolLM3MLP(nn.Module):
  189. def __init__(self, config):
  190. super().__init__()
  191. self.config = config
  192. self.hidden_size = config.hidden_size
  193. self.intermediate_size = config.intermediate_size
  194. self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  195. self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
  196. self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
  197. self.act_fn = ACT2FN[config.hidden_act]
  198. def forward(self, x):
  199. down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
  200. return down_proj
  201. class SmolLM3DecoderLayer(GradientCheckpointingLayer):
  202. def __init__(self, config: SmolLM3Config, layer_idx: int):
  203. super().__init__()
  204. self.hidden_size = config.hidden_size
  205. self.self_attn = SmolLM3Attention(config=config, layer_idx=layer_idx)
  206. self.mlp = SmolLM3MLP(config)
  207. self.input_layernorm = SmolLM3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  208. self.post_attention_layernorm = SmolLM3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  209. self.attention_type = config.layer_types[layer_idx]
  210. @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
  211. def forward(
  212. self,
  213. hidden_states: torch.Tensor,
  214. attention_mask: Optional[torch.Tensor] = None,
  215. position_ids: Optional[torch.LongTensor] = None,
  216. past_key_values: Optional[Cache] = None,
  217. use_cache: Optional[bool] = False,
  218. cache_position: Optional[torch.LongTensor] = None,
  219. position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
  220. **kwargs: Unpack[TransformersKwargs],
  221. ) -> torch.Tensor:
  222. residual = hidden_states
  223. hidden_states = self.input_layernorm(hidden_states)
  224. # Self Attention
  225. hidden_states, _ = self.self_attn(
  226. hidden_states=hidden_states,
  227. attention_mask=attention_mask,
  228. position_ids=position_ids,
  229. past_key_values=past_key_values,
  230. use_cache=use_cache,
  231. cache_position=cache_position,
  232. position_embeddings=position_embeddings,
  233. **kwargs,
  234. )
  235. hidden_states = residual + hidden_states
  236. # Fully Connected
  237. residual = hidden_states
  238. hidden_states = self.post_attention_layernorm(hidden_states)
  239. hidden_states = self.mlp(hidden_states)
  240. hidden_states = residual + hidden_states
  241. return hidden_states
  242. @auto_docstring
  243. class SmolLM3PreTrainedModel(PreTrainedModel):
  244. config: SmolLM3Config
  245. base_model_prefix = "model"
  246. supports_gradient_checkpointing = True
  247. _no_split_modules = ["SmolLM3DecoderLayer"]
  248. _skip_keys_device_placement = ["past_key_values"]
  249. _supports_flash_attn = True
  250. _supports_sdpa = True
  251. _supports_flex_attn = True
  252. _can_compile_fullgraph = True
  253. _supports_attention_backend = True
  254. _can_record_outputs = {
  255. "hidden_states": SmolLM3DecoderLayer,
  256. "attentions": SmolLM3Attention,
  257. }
  258. class SmolLM3RotaryEmbedding(nn.Module):
  259. inv_freq: torch.Tensor # fix linting for `register_buffer`
  260. def __init__(self, config: SmolLM3Config, device=None):
  261. super().__init__()
  262. # BC: "rope_type" was originally "type"
  263. if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
  264. self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
  265. else:
  266. self.rope_type = "default"
  267. self.max_seq_len_cached = config.max_position_embeddings
  268. self.original_max_seq_len = config.max_position_embeddings
  269. self.config = config
  270. self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
  271. inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
  272. self.register_buffer("inv_freq", inv_freq, persistent=False)
  273. self.original_inv_freq = self.inv_freq
  274. @torch.no_grad()
  275. @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
  276. def forward(self, x, position_ids):
  277. inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
  278. position_ids_expanded = position_ids[:, None, :].float()
  279. device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
  280. with torch.autocast(device_type=device_type, enabled=False): # Force float32
  281. freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
  282. emb = torch.cat((freqs, freqs), dim=-1)
  283. cos = emb.cos() * self.attention_scaling
  284. sin = emb.sin() * self.attention_scaling
  285. return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
  286. @auto_docstring
  287. class SmolLM3Model(SmolLM3PreTrainedModel):
  288. def __init__(self, config: SmolLM3Config):
  289. super().__init__(config)
  290. self.padding_idx = config.pad_token_id
  291. self.vocab_size = config.vocab_size
  292. self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
  293. self.layers = nn.ModuleList(
  294. [SmolLM3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
  295. )
  296. self.norm = SmolLM3RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
  297. self.rotary_emb = SmolLM3RotaryEmbedding(config=config)
  298. self.gradient_checkpointing = False
  299. self.has_sliding_layers = "sliding_attention" in self.config.layer_types
  300. # Initialize weights and apply final processing
  301. self.post_init()
  302. @check_model_inputs()
  303. @auto_docstring
  304. def forward(
  305. self,
  306. input_ids: Optional[torch.LongTensor] = None,
  307. attention_mask: Optional[torch.Tensor] = None,
  308. position_ids: Optional[torch.LongTensor] = None,
  309. past_key_values: Optional[Cache] = None,
  310. inputs_embeds: Optional[torch.FloatTensor] = None,
  311. use_cache: Optional[bool] = None,
  312. cache_position: Optional[torch.LongTensor] = None,
  313. **kwargs: Unpack[TransformersKwargs],
  314. ) -> BaseModelOutputWithPast:
  315. if (input_ids is None) ^ (inputs_embeds is not None):
  316. raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
  317. if inputs_embeds is None:
  318. inputs_embeds = self.embed_tokens(input_ids)
  319. if use_cache and past_key_values is None:
  320. past_key_values = DynamicCache(config=self.config)
  321. if cache_position is None:
  322. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
  323. cache_position = torch.arange(
  324. past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
  325. )
  326. if position_ids is None:
  327. position_ids = cache_position.unsqueeze(0)
  328. # It may already have been prepared by e.g. `generate`
  329. if not isinstance(causal_mask_mapping := attention_mask, dict):
  330. # Prepare mask arguments
  331. mask_kwargs = {
  332. "config": self.config,
  333. "input_embeds": inputs_embeds,
  334. "attention_mask": attention_mask,
  335. "cache_position": cache_position,
  336. "past_key_values": past_key_values,
  337. "position_ids": position_ids,
  338. }
  339. # Create the masks
  340. causal_mask_mapping = {
  341. "full_attention": create_causal_mask(**mask_kwargs),
  342. }
  343. # The sliding window alternating layers are not always activated depending on the config
  344. if self.has_sliding_layers:
  345. causal_mask_mapping["sliding_attention"] = create_sliding_window_causal_mask(**mask_kwargs)
  346. hidden_states = inputs_embeds
  347. # create position embeddings to be shared across the decoder layers
  348. position_embeddings = self.rotary_emb(hidden_states, position_ids)
  349. for decoder_layer in self.layers[: self.config.num_hidden_layers]:
  350. hidden_states = decoder_layer(
  351. hidden_states,
  352. attention_mask=causal_mask_mapping[decoder_layer.attention_type],
  353. position_ids=position_ids,
  354. past_key_values=past_key_values,
  355. use_cache=use_cache,
  356. cache_position=cache_position,
  357. position_embeddings=position_embeddings,
  358. **kwargs,
  359. )
  360. hidden_states = self.norm(hidden_states)
  361. return BaseModelOutputWithPast(
  362. last_hidden_state=hidden_states,
  363. past_key_values=past_key_values if use_cache else None,
  364. )
  365. @auto_docstring
  366. class SmolLM3ForCausalLM(SmolLM3PreTrainedModel, GenerationMixin):
  367. _tied_weights_keys = ["lm_head.weight"]
  368. _tp_plan = {"lm_head": "colwise_rep"}
  369. _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
  370. def __init__(self, config):
  371. super().__init__(config)
  372. self.model = SmolLM3Model(config)
  373. self.vocab_size = config.vocab_size
  374. self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  375. # Initialize weights and apply final processing
  376. self.post_init()
  377. @can_return_tuple
  378. @auto_docstring
  379. def forward(
  380. self,
  381. input_ids: Optional[torch.LongTensor] = None,
  382. attention_mask: Optional[torch.Tensor] = None,
  383. position_ids: Optional[torch.LongTensor] = None,
  384. past_key_values: Optional[Cache] = None,
  385. inputs_embeds: Optional[torch.FloatTensor] = None,
  386. labels: Optional[torch.LongTensor] = None,
  387. use_cache: Optional[bool] = None,
  388. cache_position: Optional[torch.LongTensor] = None,
  389. logits_to_keep: Union[int, torch.Tensor] = 0,
  390. **kwargs: Unpack[TransformersKwargs],
  391. ) -> CausalLMOutputWithPast:
  392. r"""
  393. Example:
  394. ```python
  395. >>> from transformers import AutoTokenizer, SmolLM3ForCausalLM
  396. >>> model = SmolLM3ForCausalLM.from_pretrained("meta-smollm3/SmolLM3-2-7b-hf")
  397. >>> tokenizer = AutoTokenizer.from_pretrained("meta-smollm3/SmolLM3-2-7b-hf")
  398. >>> prompt = "Hey, are you conscious? Can you talk to me?"
  399. >>> inputs = tokenizer(prompt, return_tensors="pt")
  400. >>> # Generate
  401. >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
  402. >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
  403. "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
  404. ```"""
  405. outputs: BaseModelOutputWithPast = self.model(
  406. input_ids=input_ids,
  407. attention_mask=attention_mask,
  408. position_ids=position_ids,
  409. past_key_values=past_key_values,
  410. inputs_embeds=inputs_embeds,
  411. use_cache=use_cache,
  412. cache_position=cache_position,
  413. **kwargs,
  414. )
  415. hidden_states = outputs.last_hidden_state
  416. # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
  417. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  418. logits = self.lm_head(hidden_states[:, slice_indices, :])
  419. loss = None
  420. if labels is not None:
  421. loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
  422. return CausalLMOutputWithPast(
  423. loss=loss,
  424. logits=logits,
  425. past_key_values=outputs.past_key_values,
  426. hidden_states=outputs.hidden_states,
  427. attentions=outputs.attentions,
  428. )
  429. class SmolLM3ForSequenceClassification(GenericForSequenceClassification, SmolLM3PreTrainedModel):
  430. pass
  431. class SmolLM3ForTokenClassification(GenericForTokenClassification, SmolLM3PreTrainedModel):
  432. pass
  433. class SmolLM3ForQuestionAnswering(GenericForQuestionAnswering, SmolLM3PreTrainedModel):
  434. base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
  435. __all__ = [
  436. "SmolLM3PreTrainedModel",
  437. "SmolLM3Model",
  438. "SmolLM3ForCausalLM",
  439. "SmolLM3ForSequenceClassification",
  440. "SmolLM3ForTokenClassification",
  441. "SmolLM3ForQuestionAnswering",
  442. ]