modeling_ministral.py 22 KB

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