hyxmmm commited on
Commit
ea5c121
·
verified ·
1 Parent(s): edb34ca

Upload modeling_mixtral.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_mixtral.py +1463 -0
modeling_mixtral.py ADDED
@@ -0,0 +1,1463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
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
+ """ PyTorch Mixtral model."""
21
+ import inspect
22
+ import math
23
+ import warnings
24
+ from typing import List, Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ import torch.utils.checkpoint
29
+ from torch import nn
30
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
31
+
32
+ from transformers.activations import ACT2FN
33
+ from transformers.cache_utils import Cache, DynamicCache
34
+ from transformers.modeling_attn_mask_utils import (
35
+ _prepare_4d_causal_attention_mask,
36
+ )
37
+ from transformers.modeling_outputs import (
38
+ MoeCausalLMOutputWithPast,
39
+ MoeModelOutputWithPast,
40
+ SequenceClassifierOutputWithPast,
41
+ )
42
+ from transformers.modeling_utils import PreTrainedModel
43
+ from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_13
44
+ from transformers.utils import (
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ is_flash_attn_2_available,
48
+ is_flash_attn_greater_or_equal_2_10,
49
+ logging,
50
+ replace_return_docstrings,
51
+ )
52
+ from transformers.utils.import_utils import is_torch_fx_available
53
+ from .configuration_mixtral import MixtralConfig
54
+
55
+
56
+ if is_flash_attn_2_available():
57
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
58
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
59
+
60
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
61
+
62
+ # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
63
+ # It means that the function will not be traced through and simply appear as a node in the graph.
64
+ if is_torch_fx_available():
65
+ if not is_torch_greater_or_equal_than_1_13:
66
+ import torch.fx
67
+
68
+ _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
69
+
70
+
71
+ logger = logging.get_logger(__name__)
72
+
73
+ _CONFIG_FOR_DOC = "MixtralConfig"
74
+
75
+
76
+ def load_balancing_loss_func(gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2) -> float:
77
+ r"""
78
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
79
+
80
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
81
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
82
+ experts is too unbalanced.
83
+
84
+ Args:
85
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
86
+ Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_experts].
87
+ num_experts (`int`, *optional*):
88
+ Number of experts
89
+
90
+ Returns:
91
+ The auxiliary loss.
92
+ """
93
+ if gate_logits is None:
94
+ return 0
95
+
96
+ if isinstance(gate_logits, tuple):
97
+ # cat along the layers?
98
+ compute_device = gate_logits[0].device
99
+ gate_logits = torch.cat([gate.to(compute_device) for gate in gate_logits], dim=0)
100
+
101
+ routing_weights, selected_experts = torch.topk(gate_logits, top_k, dim=-1)
102
+ routing_weights = routing_weights.softmax(dim=-1)
103
+
104
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
105
+ if selected_experts.dtype != torch.int64:
106
+ selected_experts = selected_experts.to(torch.int64)
107
+
108
+ if len(selected_experts.shape) == 2:
109
+ selected_experts = selected_experts.unsqueeze(2)
110
+
111
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
112
+
113
+ # For a given token, determine if it was routed to a given expert.
114
+ expert_mask = torch.max(expert_mask, axis=-2).values
115
+
116
+ # cast to float32 otherwise mean will fail
117
+ expert_mask = expert_mask.to(torch.float32)
118
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
119
+
120
+ router_prob_per_group_and_expert = torch.mean(routing_weights, axis=-1)
121
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert.unsqueeze(-1)) * (num_experts**2)
122
+
123
+
124
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
125
+ def _get_unpad_data(attention_mask):
126
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
127
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
128
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
129
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
130
+ return (
131
+ indices,
132
+ cu_seqlens,
133
+ max_seqlen_in_batch,
134
+ )
135
+
136
+
137
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mixtral
138
+ class MixtralRMSNorm(nn.Module):
139
+ def __init__(self, hidden_size, eps=1e-6):
140
+ """
141
+ MixtralRMSNorm is equivalent to T5LayerNorm
142
+ """
143
+ super().__init__()
144
+ self.weight = nn.Parameter(torch.ones(hidden_size))
145
+ self.variance_epsilon = eps
146
+
147
+ def forward(self, hidden_states):
148
+ input_dtype = hidden_states.dtype
149
+ hidden_states = hidden_states.to(torch.float32)
150
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
151
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
152
+ return self.weight * hidden_states.to(input_dtype)
153
+
154
+
155
+ # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mixtral
156
+ class MixtralRotaryEmbedding(nn.Module):
157
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
158
+ super().__init__()
159
+
160
+ self.dim = dim
161
+ self.max_position_embeddings = max_position_embeddings
162
+ self.base = base
163
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
164
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
165
+
166
+ # Build here to make `torch.jit.trace` work.
167
+ self._set_cos_sin_cache(
168
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
169
+ )
170
+
171
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
172
+ self.max_seq_len_cached = seq_len
173
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
174
+
175
+ freqs = torch.outer(t, self.inv_freq)
176
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
177
+ emb = torch.cat((freqs, freqs), dim=-1)
178
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
179
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
180
+
181
+ def forward(self, x, seq_len=None):
182
+ # x: [bs, num_attention_heads, seq_len, head_size]
183
+ if seq_len > self.max_seq_len_cached:
184
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
185
+
186
+ return (
187
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
188
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
189
+ )
190
+
191
+
192
+ # Copied from transformers.models.llama.modeling_llama.rotate_half
193
+ def rotate_half(x):
194
+ """Rotates half the hidden dims of the input."""
195
+ x1 = x[..., : x.shape[-1] // 2]
196
+ x2 = x[..., x.shape[-1] // 2 :]
197
+ return torch.cat((-x2, x1), dim=-1)
198
+
199
+
200
+ # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb
201
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
202
+ """Applies Rotary Position Embedding to the query and key tensors.
203
+
204
+ Args:
205
+ q (`torch.Tensor`): The query tensor.
206
+ k (`torch.Tensor`): The key tensor.
207
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
208
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
209
+ position_ids (`torch.Tensor`):
210
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
211
+ used to pass offsetted position ids when working with a KV-cache.
212
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
213
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
214
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
215
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
216
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
217
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
218
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
219
+ Returns:
220
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
221
+ """
222
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
223
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
224
+ q_embed = (q * cos) + (rotate_half(q) * sin)
225
+ k_embed = (k * cos) + (rotate_half(k) * sin)
226
+ return q_embed, k_embed
227
+
228
+
229
+ # Copied from transformers.models.llama.modeling_llama.repeat_kv
230
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
231
+ """
232
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
233
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
234
+ """
235
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
236
+ if n_rep == 1:
237
+ return hidden_states
238
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
239
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
240
+
241
+
242
+ # Copied from transformers.models.mistral.modeling_mistral.MistralAttention with Mistral->Mixtral
243
+ class MixtralAttention(nn.Module):
244
+ """
245
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
246
+ and "Generating Long Sequences with Sparse Transformers".
247
+ """
248
+
249
+ def __init__(self, config: MixtralConfig, layer_idx: Optional[int] = None):
250
+ super().__init__()
251
+ self.config = config
252
+ self.layer_idx = layer_idx
253
+ if layer_idx is None:
254
+ logger.warning_once(
255
+ f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
256
+ "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
257
+ "when creating this class."
258
+ )
259
+
260
+ self.hidden_size = config.hidden_size
261
+ self.num_heads = config.num_attention_heads
262
+ self.head_dim = self.hidden_size // self.num_heads
263
+ self.num_key_value_heads = config.num_key_value_heads
264
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
265
+ self.max_position_embeddings = config.max_position_embeddings
266
+ self.rope_theta = config.rope_theta
267
+ self.is_causal = True
268
+ self.attention_dropout = config.attention_dropout
269
+
270
+ if (self.head_dim * self.num_heads) != self.hidden_size:
271
+ raise ValueError(
272
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
273
+ f" and `num_heads`: {self.num_heads})."
274
+ )
275
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=True)
276
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
277
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=True)
278
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
279
+
280
+ self.rotary_emb = MixtralRotaryEmbedding(
281
+ self.head_dim,
282
+ max_position_embeddings=self.max_position_embeddings,
283
+ base=self.rope_theta,
284
+ )
285
+
286
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
287
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
288
+
289
+ def forward(
290
+ self,
291
+ hidden_states: torch.Tensor,
292
+ attention_mask: Optional[torch.Tensor] = None,
293
+ position_ids: Optional[torch.LongTensor] = None,
294
+ past_key_value: Optional[Cache] = None,
295
+ output_attentions: bool = False,
296
+ use_cache: bool = False,
297
+ **kwargs,
298
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
299
+ if "padding_mask" in kwargs:
300
+ warnings.warn(
301
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
302
+ )
303
+ bsz, q_len, _ = hidden_states.size()
304
+
305
+ query_states = self.q_proj(hidden_states)
306
+ key_states = self.k_proj(hidden_states)
307
+ value_states = self.v_proj(hidden_states)
308
+
309
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
310
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
311
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
312
+
313
+ kv_seq_len = key_states.shape[-2]
314
+ if past_key_value is not None:
315
+ if self.layer_idx is None:
316
+ raise ValueError(
317
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
318
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
319
+ "with a layer index."
320
+ )
321
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
322
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
323
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
324
+
325
+ if past_key_value is not None:
326
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
327
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
328
+
329
+ # repeat k/v heads if n_kv_heads < n_heads
330
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
331
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
332
+
333
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
334
+
335
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
336
+ raise ValueError(
337
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
338
+ f" {attn_weights.size()}"
339
+ )
340
+
341
+ if attention_mask is not None:
342
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
343
+ raise ValueError(
344
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
345
+ )
346
+
347
+ attn_weights = attn_weights + attention_mask
348
+
349
+ # upcast attention to fp32
350
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
351
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
352
+ attn_output = torch.matmul(attn_weights, value_states)
353
+
354
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
355
+ raise ValueError(
356
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
357
+ f" {attn_output.size()}"
358
+ )
359
+
360
+ attn_output = attn_output.transpose(1, 2).contiguous()
361
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
362
+
363
+ attn_output = self.o_proj(attn_output)
364
+
365
+ if not output_attentions:
366
+ attn_weights = None
367
+
368
+ return attn_output, attn_weights, past_key_value
369
+
370
+
371
+ # Copied from transformers.models.mistral.modeling_mistral.MistralFlashAttention2 with Mistral->Mixtral
372
+ class MixtralFlashAttention2(MixtralAttention):
373
+ """
374
+ Mixtral flash attention module. This module inherits from `MixtralAttention` as the weights of the module stays
375
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
376
+ flash attention and deal with padding tokens in case the input contains any of them.
377
+ """
378
+
379
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
380
+ def __init__(self, *args, **kwargs):
381
+ super().__init__(*args, **kwargs)
382
+
383
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
384
+ # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
385
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
386
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ attention_mask: Optional[torch.Tensor] = None,
392
+ position_ids: Optional[torch.LongTensor] = None,
393
+ past_key_value: Optional[Cache] = None,
394
+ output_attentions: bool = False,
395
+ use_cache: bool = False,
396
+ **kwargs,
397
+ ):
398
+ if "padding_mask" in kwargs:
399
+ warnings.warn(
400
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
401
+ )
402
+
403
+ # overwrite attention_mask with padding_mask
404
+ attention_mask = kwargs.pop("padding_mask")
405
+ bsz, q_len, _ = hidden_states.size()
406
+
407
+ query_states = self.q_proj(hidden_states)
408
+ key_states = self.k_proj(hidden_states)
409
+ value_states = self.v_proj(hidden_states)
410
+
411
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
412
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
413
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
414
+
415
+ kv_seq_len = key_states.shape[-2]
416
+ if past_key_value is not None:
417
+ if self.layer_idx is None:
418
+ raise ValueError(
419
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
420
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
421
+ "with a layer index."
422
+ )
423
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
424
+
425
+ # Because the input can be padded, the absolute sequence length depends on the max position id.
426
+ rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1
427
+ cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len)
428
+
429
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
430
+
431
+ use_sliding_windows = (
432
+ _flash_supports_window_size
433
+ and getattr(self.config, "sliding_window", None) is not None
434
+ and kv_seq_len > self.config.sliding_window
435
+ )
436
+
437
+ if not _flash_supports_window_size:
438
+ logger.warning_once(
439
+ "The current flash attention version does not support sliding window attention, for a more memory efficient implementation"
440
+ " make sure to upgrade flash-attn library."
441
+ )
442
+
443
+ if past_key_value is not None:
444
+ # Activate slicing cache only if the config has a value `sliding_windows` attribute
445
+ cache_has_contents = past_key_value.get_seq_length(self.layer_idx) > 0
446
+ if (
447
+ getattr(self.config, "sliding_window", None) is not None
448
+ and kv_seq_len > self.config.sliding_window
449
+ and cache_has_contents
450
+ ):
451
+ slicing_tokens = 1 - self.config.sliding_window
452
+
453
+ past_key = past_key_value[self.layer_idx][0]
454
+ past_value = past_key_value[self.layer_idx][1]
455
+
456
+ past_key = past_key[:, :, slicing_tokens:, :].contiguous()
457
+ past_value = past_value[:, :, slicing_tokens:, :].contiguous()
458
+
459
+ if past_key.shape[-2] != self.config.sliding_window - 1:
460
+ raise ValueError(
461
+ f"past key must have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got"
462
+ f" {past_key.shape}"
463
+ )
464
+
465
+ if attention_mask is not None:
466
+ attention_mask = attention_mask[:, slicing_tokens:]
467
+ attention_mask = torch.cat([attention_mask, torch.ones_like(attention_mask[:, -1:])], dim=-1)
468
+
469
+ cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
470
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
471
+
472
+ # repeat k/v heads if n_kv_heads < n_heads
473
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
474
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
475
+ dropout_rate = 0.0 if not self.training else self.attention_dropout
476
+
477
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
478
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
479
+ # cast them back in float16 just to be sure everything works as expected.
480
+ input_dtype = query_states.dtype
481
+ if input_dtype == torch.float32:
482
+ # Handle the case where the model is quantized
483
+ if hasattr(self.config, "_pre_quantization_dtype"):
484
+ target_dtype = self.config._pre_quantization_dtype
485
+ else:
486
+ target_dtype = self.q_proj.weight.dtype
487
+
488
+ logger.warning_once(
489
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
490
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
491
+ f" {target_dtype}."
492
+ )
493
+
494
+ query_states = query_states.to(target_dtype)
495
+ key_states = key_states.to(target_dtype)
496
+ value_states = value_states.to(target_dtype)
497
+
498
+ # Reashape to the expected shape for Flash Attention
499
+ query_states = query_states.transpose(1, 2)
500
+ key_states = key_states.transpose(1, 2)
501
+ value_states = value_states.transpose(1, 2)
502
+
503
+ attn_output = self._flash_attention_forward(
504
+ query_states,
505
+ key_states,
506
+ value_states,
507
+ attention_mask,
508
+ q_len,
509
+ dropout=dropout_rate,
510
+ use_sliding_windows=use_sliding_windows,
511
+ )
512
+
513
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
514
+ attn_output = self.o_proj(attn_output)
515
+
516
+ if not output_attentions:
517
+ attn_weights = None
518
+
519
+ return attn_output, attn_weights, past_key_value
520
+
521
+ def _flash_attention_forward(
522
+ self,
523
+ query_states,
524
+ key_states,
525
+ value_states,
526
+ attention_mask,
527
+ query_length,
528
+ dropout=0.0,
529
+ softmax_scale=None,
530
+ use_sliding_windows=False,
531
+ ):
532
+ """
533
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
534
+ first unpad the input, then computes the attention scores and pad the final attention scores.
535
+
536
+ Args:
537
+ query_states (`torch.Tensor`):
538
+ Input query states to be passed to Flash Attention API
539
+ key_states (`torch.Tensor`):
540
+ Input key states to be passed to Flash Attention API
541
+ value_states (`torch.Tensor`):
542
+ Input value states to be passed to Flash Attention API
543
+ attention_mask (`torch.Tensor`):
544
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
545
+ position of padding tokens and 1 for the position of non-padding tokens.
546
+ dropout (`int`, *optional*):
547
+ Attention dropout
548
+ softmax_scale (`float`, *optional*):
549
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
550
+ use_sliding_windows (`bool`, *optional*):
551
+ Whether to activate sliding window attention.
552
+ """
553
+ if not self._flash_attn_uses_top_left_mask:
554
+ causal = self.is_causal
555
+ else:
556
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
557
+ causal = self.is_causal and query_length != 1
558
+
559
+ # Contains at least one padding token in the sequence
560
+ if attention_mask is not None:
561
+ batch_size = query_states.shape[0]
562
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
563
+ query_states, key_states, value_states, attention_mask, query_length
564
+ )
565
+
566
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
567
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
568
+
569
+ if not use_sliding_windows:
570
+ attn_output_unpad = flash_attn_varlen_func(
571
+ query_states,
572
+ key_states,
573
+ value_states,
574
+ cu_seqlens_q=cu_seqlens_q,
575
+ cu_seqlens_k=cu_seqlens_k,
576
+ max_seqlen_q=max_seqlen_in_batch_q,
577
+ max_seqlen_k=max_seqlen_in_batch_k,
578
+ dropout_p=dropout,
579
+ softmax_scale=softmax_scale,
580
+ causal=causal,
581
+ )
582
+ else:
583
+ attn_output_unpad = flash_attn_varlen_func(
584
+ query_states,
585
+ key_states,
586
+ value_states,
587
+ cu_seqlens_q=cu_seqlens_q,
588
+ cu_seqlens_k=cu_seqlens_k,
589
+ max_seqlen_q=max_seqlen_in_batch_q,
590
+ max_seqlen_k=max_seqlen_in_batch_k,
591
+ dropout_p=dropout,
592
+ softmax_scale=softmax_scale,
593
+ causal=causal,
594
+ window_size=(self.config.sliding_window, self.config.sliding_window),
595
+ )
596
+
597
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
598
+ else:
599
+ if not use_sliding_windows:
600
+ attn_output = flash_attn_func(
601
+ query_states,
602
+ key_states,
603
+ value_states,
604
+ dropout,
605
+ softmax_scale=softmax_scale,
606
+ causal=causal,
607
+ )
608
+ else:
609
+ attn_output = flash_attn_func(
610
+ query_states,
611
+ key_states,
612
+ value_states,
613
+ dropout,
614
+ softmax_scale=softmax_scale,
615
+ causal=causal,
616
+ window_size=(self.config.sliding_window, self.config.sliding_window),
617
+ )
618
+
619
+ return attn_output
620
+
621
+ def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
622
+ batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape
623
+
624
+ # On the first iteration we need to properly re-create the padding mask
625
+ # by slicing it on the proper place
626
+ if kv_seq_len != attention_mask.shape[-1]:
627
+ attention_mask_num_tokens = attention_mask.shape[-1]
628
+ attention_mask = attention_mask[:, attention_mask_num_tokens - kv_seq_len :]
629
+
630
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
631
+
632
+ key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
633
+ value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k)
634
+
635
+ if query_length == kv_seq_len:
636
+ query_layer = index_first_axis(
637
+ query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k
638
+ )
639
+ cu_seqlens_q = cu_seqlens_k
640
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
641
+ indices_q = indices_k
642
+ elif query_length == 1:
643
+ max_seqlen_in_batch_q = 1
644
+ cu_seqlens_q = torch.arange(
645
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
646
+ ) # There is a memcpy here, that is very bad.
647
+ indices_q = cu_seqlens_q[:-1]
648
+ query_layer = query_layer.squeeze(1)
649
+ else:
650
+ # The -q_len: slice assumes left padding.
651
+ attention_mask = attention_mask[:, -query_length:]
652
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
653
+
654
+ return (
655
+ query_layer,
656
+ key_layer,
657
+ value_layer,
658
+ indices_q,
659
+ (cu_seqlens_q, cu_seqlens_k),
660
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
661
+ )
662
+
663
+
664
+ class MixtralBLockSparseTop2MLP(nn.Module):
665
+ def __init__(self, config: MixtralConfig):
666
+ super().__init__()
667
+ self.ffn_dim = config.intermediate_size
668
+ self.hidden_dim = config.hidden_size
669
+
670
+ self.w1 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
671
+ self.w2 = nn.Linear(self.ffn_dim, self.hidden_dim, bias=False)
672
+ self.w3 = nn.Linear(self.hidden_dim, self.ffn_dim, bias=False)
673
+
674
+ self.act_fn = ACT2FN[config.hidden_act]
675
+
676
+ def forward(self, hidden_states, routing_weights):
677
+ current_hidden_states = self.act_fn(self.w1(hidden_states)) * self.w3(hidden_states)
678
+ current_hidden_states = self.w2(current_hidden_states)
679
+ return routing_weights * current_hidden_states
680
+
681
+
682
+ MISTRAL_ATTENTION_CLASSES = {
683
+ "eager": MixtralAttention,
684
+ "flash_attention_2": MixtralFlashAttention2,
685
+ }
686
+
687
+
688
+ class MixtralSparseMoeBlock(nn.Module):
689
+ """
690
+ This implementation is
691
+ strictly equivalent to standard MoE with full capacity (no
692
+ dropped tokens). It's faster since it formulates MoE operations
693
+ in terms of block-sparse operations to accomodate imbalanced
694
+ assignments of tokens to experts, whereas standard MoE either
695
+ (1) drop tokens at the cost of reduced performance or (2) set
696
+ capacity factor to number of experts and thus waste computation
697
+ and memory on padding.
698
+ """
699
+
700
+ def __init__(self, config):
701
+ super().__init__()
702
+ self.hidden_dim = config.hidden_size
703
+ self.ffn_dim = config.intermediate_size
704
+ self.num_experts = config.num_local_experts
705
+ self.top_k = config.num_experts_per_tok
706
+
707
+ # gating
708
+ self.gate = nn.Linear(self.hidden_dim, self.num_experts, bias=False)
709
+
710
+ self.experts = nn.ModuleList([MixtralBLockSparseTop2MLP(config) for _ in range(self.num_experts)])
711
+
712
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
713
+ """ """
714
+ batch_size, sequence_length, hidden_dim = hidden_states.shape
715
+ hidden_states = hidden_states.view(-1, hidden_dim)
716
+ # router_logits: (batch * sequence_length, n_experts)
717
+ router_logits = self.gate(hidden_states)
718
+
719
+ routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
720
+ routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1)
721
+ routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
722
+ # we cast back to the input dtype
723
+ routing_weights = routing_weights.to(hidden_states.dtype)
724
+
725
+ final_hidden_states = torch.zeros(
726
+ (batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
727
+ )
728
+
729
+ # One hot encode the selected experts to create an expert mask
730
+ # this will be used to easily index which expert is going to be sollicitated
731
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
732
+
733
+ # Loop over all available experts in the model and perform the computation on each expert
734
+ for expert_idx in range(self.num_experts):
735
+ expert_layer = self.experts[expert_idx]
736
+ idx, top_x = torch.where(expert_mask[expert_idx])
737
+
738
+ if top_x.shape[0] == 0:
739
+ continue
740
+
741
+ # in torch it is faster to index using lists than torch tensors
742
+ top_x_list = top_x.tolist()
743
+ idx_list = idx.tolist()
744
+
745
+ # Index the correct hidden states and compute the expert hidden state for
746
+ # the current expert. We need to make sure to multiply the output hidden
747
+ # states by `routing_weights` on the corresponding tokens (top-1 and top-2)
748
+ current_state = hidden_states[None, top_x_list].reshape(-1, hidden_dim)
749
+ current_hidden_states = expert_layer(current_state, routing_weights[top_x_list, idx_list, None])
750
+
751
+ # However `index_add_` only support torch tensors for indexing so we'll use
752
+ # the `top_x` tensor here.
753
+ final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
754
+ final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
755
+ return final_hidden_states, router_logits
756
+
757
+
758
+ class MixtralDecoderLayer(nn.Module):
759
+ def __init__(self, config: MixtralConfig, layer_idx: int):
760
+ super().__init__()
761
+ self.hidden_size = config.hidden_size
762
+
763
+ self.self_attn = MISTRAL_ATTENTION_CLASSES[config._attn_implementation](config, layer_idx)
764
+
765
+ self.block_sparse_moe = MixtralSparseMoeBlock(config)
766
+ self.input_layernorm = MixtralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
767
+ self.post_attention_layernorm = MixtralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
768
+
769
+ def forward(
770
+ self,
771
+ hidden_states: torch.Tensor,
772
+ attention_mask: Optional[torch.Tensor] = None,
773
+ position_ids: Optional[torch.LongTensor] = None,
774
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
775
+ output_attentions: Optional[bool] = False,
776
+ output_router_logits: Optional[bool] = False,
777
+ use_cache: Optional[bool] = False,
778
+ **kwargs,
779
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
780
+ if "padding_mask" in kwargs:
781
+ warnings.warn(
782
+ "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
783
+ )
784
+ """
785
+ Args:
786
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
787
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
788
+ `(batch, sequence_length)` where padding elements are indicated by 0.
789
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
790
+ output_attentions (`bool`, *optional*):
791
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
792
+ returned tensors for more detail.
793
+ output_router_logits (`bool`, *optional*):
794
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
795
+ should not be returned during inference.
796
+ use_cache (`bool`, *optional*):
797
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
798
+ (see `past_key_values`).
799
+ """
800
+
801
+ residual = hidden_states
802
+
803
+ hidden_states = self.input_layernorm(hidden_states)
804
+
805
+ # Self Attention
806
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
807
+ hidden_states=hidden_states,
808
+ attention_mask=attention_mask,
809
+ position_ids=position_ids,
810
+ past_key_value=past_key_value,
811
+ output_attentions=output_attentions,
812
+ use_cache=use_cache,
813
+ )
814
+ hidden_states = residual + hidden_states
815
+
816
+ # Fully Connected
817
+ residual = hidden_states
818
+ hidden_states = self.post_attention_layernorm(hidden_states)
819
+ hidden_states, router_logits = self.block_sparse_moe(hidden_states)
820
+ hidden_states = residual + hidden_states
821
+
822
+ outputs = (hidden_states,)
823
+
824
+ if output_attentions:
825
+ outputs += (self_attn_weights,)
826
+
827
+ if use_cache:
828
+ outputs += (present_key_value,)
829
+
830
+ if output_router_logits:
831
+ outputs += (router_logits,)
832
+
833
+ return outputs
834
+
835
+
836
+ MIXTRAL_START_DOCSTRING = r"""
837
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
838
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
839
+ etc.)
840
+
841
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
842
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
843
+ and behavior.
844
+
845
+ Parameters:
846
+ config ([`MixtralConfig`]):
847
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
848
+ load the weights associated with the model, only the configuration. Check out the
849
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
850
+ """
851
+
852
+
853
+ @add_start_docstrings(
854
+ "The bare Mixtral Model outputting raw hidden-states without any specific head on top.",
855
+ MIXTRAL_START_DOCSTRING,
856
+ )
857
+ # Copied from transformers.models.mistral.modeling_mistral.MistralPreTrainedModel with Mistral->Mixtral
858
+ class MixtralPreTrainedModel(PreTrainedModel):
859
+ config_class = MixtralConfig
860
+ base_model_prefix = "model"
861
+ supports_gradient_checkpointing = True
862
+ _no_split_modules = ["MixtralDecoderLayer"]
863
+ _skip_keys_device_placement = "past_key_values"
864
+ _supports_flash_attn_2 = True
865
+ _supports_cache_class = True
866
+
867
+ def _init_weights(self, module):
868
+ std = self.config.initializer_range
869
+ if isinstance(module, nn.Linear):
870
+ module.weight.data.normal_(mean=0.0, std=std)
871
+ if module.bias is not None:
872
+ module.bias.data.zero_()
873
+ elif isinstance(module, nn.Embedding):
874
+ module.weight.data.normal_(mean=0.0, std=std)
875
+ if module.padding_idx is not None:
876
+ module.weight.data[module.padding_idx].zero_()
877
+
878
+
879
+ MIXTRAL_INPUTS_DOCSTRING = r"""
880
+ Args:
881
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
882
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
883
+ it.
884
+
885
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
886
+ [`PreTrainedTokenizer.__call__`] for details.
887
+
888
+ [What are input IDs?](../glossary#input-ids)
889
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
890
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
891
+
892
+ - 1 for tokens that are **not masked**,
893
+ - 0 for tokens that are **masked**.
894
+
895
+ [What are attention masks?](../glossary#attention-mask)
896
+
897
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
898
+ [`PreTrainedTokenizer.__call__`] for details.
899
+
900
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
901
+ `past_key_values`).
902
+
903
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
904
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
905
+ information on the default strategy.
906
+
907
+ - 1 indicates the head is **not masked**,
908
+ - 0 indicates the head is **masked**.
909
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
910
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
911
+ config.n_positions - 1]`.
912
+
913
+ [What are position IDs?](../glossary#position-ids)
914
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
915
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
916
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
917
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
918
+
919
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
920
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
921
+
922
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
923
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
924
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
925
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
926
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
927
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
928
+ model's internal embedding lookup matrix.
929
+ use_cache (`bool`, *optional*):
930
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
931
+ `past_key_values`).
932
+ output_attentions (`bool`, *optional*):
933
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
934
+ tensors for more detail.
935
+ output_hidden_states (`bool`, *optional*):
936
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
937
+ more detail.
938
+ output_router_logits (`bool`, *optional*):
939
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
940
+ should not be returned during inference.
941
+ return_dict (`bool`, *optional*):
942
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
943
+ """
944
+
945
+
946
+ @add_start_docstrings(
947
+ "The bare Mixtral Model outputting raw hidden-states without any specific head on top.",
948
+ MIXTRAL_START_DOCSTRING,
949
+ )
950
+ # Copied from transformers.models.mistral.modeling_mistral.MistralModel with MISTRAL->MIXTRAL,Mistral->Mixtral
951
+ class MixtralModel(MixtralPreTrainedModel):
952
+ """
953
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MixtralDecoderLayer`]
954
+
955
+ Args:
956
+ config: MixtralConfig
957
+ """
958
+
959
+ def __init__(self, config: MixtralConfig):
960
+ super().__init__(config)
961
+ self.padding_idx = config.pad_token_id
962
+ self.vocab_size = config.vocab_size
963
+
964
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
965
+ self.layers = nn.ModuleList(
966
+ [MixtralDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
967
+ )
968
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
969
+ self.norm = MixtralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
970
+
971
+ self.gradient_checkpointing = False
972
+ # Initialize weights and apply final processing
973
+ self.post_init()
974
+
975
+ def get_input_embeddings(self):
976
+ return self.embed_tokens
977
+
978
+ def set_input_embeddings(self, value):
979
+ self.embed_tokens = value
980
+
981
+ # Ignore copy
982
+ @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
983
+ def forward(
984
+ self,
985
+ input_ids: torch.LongTensor = None,
986
+ attention_mask: Optional[torch.Tensor] = None,
987
+ position_ids: Optional[torch.LongTensor] = None,
988
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
989
+ inputs_embeds: Optional[torch.FloatTensor] = None,
990
+ use_cache: Optional[bool] = None,
991
+ output_attentions: Optional[bool] = None,
992
+ output_hidden_states: Optional[bool] = None,
993
+ output_router_logits: Optional[bool] = None,
994
+ return_dict: Optional[bool] = None,
995
+ ) -> Union[Tuple, MoeModelOutputWithPast]:
996
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
997
+ output_router_logits = (
998
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
999
+ )
1000
+ output_hidden_states = (
1001
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1002
+ )
1003
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1004
+
1005
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1006
+
1007
+ # retrieve input_ids and inputs_embeds
1008
+ if input_ids is not None and inputs_embeds is not None:
1009
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
1010
+ elif input_ids is not None:
1011
+ batch_size, seq_length = input_ids.shape
1012
+ elif inputs_embeds is not None:
1013
+ batch_size, seq_length, _ = inputs_embeds.shape
1014
+ else:
1015
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
1016
+
1017
+ past_key_values_length = 0
1018
+
1019
+ if self.gradient_checkpointing and self.training:
1020
+ if use_cache:
1021
+ logger.warning_once(
1022
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1023
+ )
1024
+ use_cache = False
1025
+
1026
+ if use_cache:
1027
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1028
+ if use_legacy_cache:
1029
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1030
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1031
+
1032
+ if position_ids is None:
1033
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1034
+ position_ids = torch.arange(
1035
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1036
+ )
1037
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1038
+ else:
1039
+ position_ids = position_ids.view(-1, seq_length).long()
1040
+
1041
+ if inputs_embeds is None:
1042
+ inputs_embeds = self.embed_tokens(input_ids)
1043
+
1044
+ if attention_mask is not None and self._use_flash_attention_2 and use_cache:
1045
+ is_padding_right = attention_mask[:, -1].sum().item() != batch_size
1046
+ if is_padding_right:
1047
+ raise ValueError(
1048
+ "You are attempting to perform batched generation with padding_side='right'"
1049
+ " this may lead to unexpected behaviour for Flash Attention version of Mixtral. Make sure to "
1050
+ " call `tokenizer.padding_side = 'left'` before tokenizing the input. "
1051
+ )
1052
+
1053
+ if self._use_flash_attention_2:
1054
+ # 2d mask is passed through the layers
1055
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1056
+ else:
1057
+ # 4d mask is passed through the layers
1058
+ attention_mask = _prepare_4d_causal_attention_mask(
1059
+ attention_mask,
1060
+ (batch_size, seq_length),
1061
+ inputs_embeds,
1062
+ past_key_values_length,
1063
+ sliding_window=self.config.sliding_window,
1064
+ )
1065
+
1066
+ hidden_states = inputs_embeds
1067
+
1068
+ # decoder layers
1069
+ all_hidden_states = () if output_hidden_states else None
1070
+ all_self_attns = () if output_attentions else None
1071
+ all_router_logits = () if output_router_logits else None
1072
+ next_decoder_cache = None
1073
+
1074
+ for decoder_layer in self.layers:
1075
+ if output_hidden_states:
1076
+ all_hidden_states += (hidden_states,)
1077
+
1078
+ if self.gradient_checkpointing and self.training:
1079
+ layer_outputs = self._gradient_checkpointing_func(
1080
+ decoder_layer.__call__,
1081
+ hidden_states,
1082
+ attention_mask,
1083
+ position_ids,
1084
+ past_key_values,
1085
+ output_attentions,
1086
+ output_router_logits,
1087
+ use_cache,
1088
+ )
1089
+ else:
1090
+ layer_outputs = decoder_layer(
1091
+ hidden_states,
1092
+ attention_mask=attention_mask,
1093
+ position_ids=position_ids,
1094
+ past_key_value=past_key_values,
1095
+ output_attentions=output_attentions,
1096
+ output_router_logits=output_router_logits,
1097
+ use_cache=use_cache,
1098
+ )
1099
+
1100
+ hidden_states = layer_outputs[0]
1101
+
1102
+ if use_cache:
1103
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1104
+
1105
+ if output_attentions:
1106
+ all_self_attns += (layer_outputs[1],)
1107
+
1108
+ if output_router_logits:
1109
+ all_router_logits += (layer_outputs[-1],)
1110
+
1111
+ hidden_states = self.norm(hidden_states)
1112
+
1113
+ # add hidden states from the last decoder layer
1114
+ if output_hidden_states:
1115
+ all_hidden_states += (hidden_states,)
1116
+
1117
+ next_cache = None
1118
+ if use_cache:
1119
+ next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1120
+
1121
+ if not return_dict:
1122
+ return tuple(
1123
+ v
1124
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_router_logits]
1125
+ if v is not None
1126
+ )
1127
+ return MoeModelOutputWithPast(
1128
+ last_hidden_state=hidden_states,
1129
+ past_key_values=next_cache,
1130
+ hidden_states=all_hidden_states,
1131
+ attentions=all_self_attns,
1132
+ router_logits=all_router_logits,
1133
+ )
1134
+
1135
+
1136
+ class MixtralForCausalLM(MixtralPreTrainedModel):
1137
+ _tied_weights_keys = ["lm_head.weight"]
1138
+
1139
+ def __init__(self, config):
1140
+ super().__init__(config)
1141
+ self.model = MixtralModel(config)
1142
+ self.vocab_size = config.vocab_size
1143
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1144
+ self.router_aux_loss_coef = config.router_aux_loss_coef
1145
+ self.num_experts = config.num_local_experts
1146
+ self.num_experts_per_tok = config.num_experts_per_tok
1147
+ # Initialize weights and apply final processing
1148
+ self.post_init()
1149
+
1150
+ def get_input_embeddings(self):
1151
+ return self.model.embed_tokens
1152
+
1153
+ def set_input_embeddings(self, value):
1154
+ self.model.embed_tokens = value
1155
+
1156
+ def get_output_embeddings(self):
1157
+ return self.lm_head
1158
+
1159
+ def set_output_embeddings(self, new_embeddings):
1160
+ self.lm_head = new_embeddings
1161
+
1162
+ def set_decoder(self, decoder):
1163
+ self.model = decoder
1164
+
1165
+ def get_decoder(self):
1166
+ return self.model
1167
+
1168
+ @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
1169
+ @replace_return_docstrings(output_type=MoeCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1170
+ # Ignore copy
1171
+ def forward(
1172
+ self,
1173
+ input_ids: torch.LongTensor = None,
1174
+ attention_mask: Optional[torch.Tensor] = None,
1175
+ position_ids: Optional[torch.LongTensor] = None,
1176
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1177
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1178
+ labels: Optional[torch.LongTensor] = None,
1179
+ use_cache: Optional[bool] = None,
1180
+ output_attentions: Optional[bool] = None,
1181
+ output_hidden_states: Optional[bool] = None,
1182
+ output_router_logits: Optional[bool] = None,
1183
+ return_dict: Optional[bool] = None,
1184
+ ) -> Union[Tuple, MoeCausalLMOutputWithPast]:
1185
+ r"""
1186
+ Args:
1187
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1188
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1189
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1190
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1191
+
1192
+ Returns:
1193
+
1194
+ Example:
1195
+
1196
+ ```python
1197
+ >>> from transformers import AutoTokenizer, MixtralForCausalLM
1198
+
1199
+ >>> model = MixtralForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1200
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1201
+
1202
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1203
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1204
+
1205
+ >>> # Generate
1206
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1207
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1208
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1209
+ ```"""
1210
+
1211
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1212
+ output_router_logits = (
1213
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1214
+ )
1215
+
1216
+ output_hidden_states = (
1217
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1218
+ )
1219
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1220
+
1221
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1222
+ outputs = self.model(
1223
+ input_ids=input_ids,
1224
+ attention_mask=attention_mask,
1225
+ position_ids=position_ids,
1226
+ past_key_values=past_key_values,
1227
+ inputs_embeds=inputs_embeds,
1228
+ use_cache=use_cache,
1229
+ output_attentions=output_attentions,
1230
+ output_hidden_states=output_hidden_states,
1231
+ output_router_logits=output_router_logits,
1232
+ return_dict=return_dict,
1233
+ )
1234
+
1235
+ hidden_states = outputs[0]
1236
+ logits = self.lm_head(hidden_states)
1237
+ logits = logits.float()
1238
+
1239
+ loss = None
1240
+ if labels is not None:
1241
+ # Shift so that tokens < n predict n
1242
+ shift_logits = logits[..., :-1, :].contiguous()
1243
+ shift_labels = labels[..., 1:].contiguous()
1244
+ # Flatten the tokens
1245
+ loss_fct = CrossEntropyLoss()
1246
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1247
+ shift_labels = shift_labels.view(-1)
1248
+ # Enable model parallelism
1249
+ shift_labels = shift_labels.to(shift_logits.device)
1250
+ loss = loss_fct(shift_logits, shift_labels)
1251
+
1252
+ aux_loss = None
1253
+ if output_router_logits:
1254
+ aux_loss = load_balancing_loss_func(
1255
+ outputs.router_logits if return_dict else outputs[-1], self.num_experts, self.num_experts_per_tok
1256
+ )
1257
+ if labels is not None:
1258
+ loss += self.router_aux_loss_coef * aux_loss
1259
+
1260
+ if not return_dict:
1261
+ output = (logits,) + outputs[1:]
1262
+ if output_router_logits:
1263
+ output = (aux_loss,) + output
1264
+ return (loss,) + output if loss is not None else output
1265
+
1266
+ return MoeCausalLMOutputWithPast(
1267
+ loss=loss,
1268
+ aux_loss=aux_loss,
1269
+ logits=logits,
1270
+ past_key_values=outputs.past_key_values,
1271
+ hidden_states=outputs.hidden_states,
1272
+ attentions=outputs.attentions,
1273
+ router_logits=outputs.router_logits,
1274
+ )
1275
+
1276
+ def prepare_inputs_for_generation(
1277
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1278
+ ):
1279
+ # Omit tokens covered by past_key_values
1280
+ if past_key_values is not None:
1281
+ if isinstance(past_key_values, Cache):
1282
+ cache_length = past_key_values.get_seq_length()
1283
+ past_length = past_key_values.seen_tokens
1284
+ max_cache_length = past_key_values.get_max_length()
1285
+ else:
1286
+ cache_length = past_length = past_key_values[0][0].shape[2]
1287
+ max_cache_length = None
1288
+
1289
+ # Keep only the unprocessed tokens:
1290
+ # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1291
+ # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1292
+ # input)
1293
+ if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1294
+ input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1295
+ # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1296
+ # input_ids based on the past_length.
1297
+ elif past_length < input_ids.shape[1]:
1298
+ input_ids = input_ids[:, past_length:]
1299
+ # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1300
+
1301
+ # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1302
+ if (
1303
+ max_cache_length is not None
1304
+ and attention_mask is not None
1305
+ and cache_length + input_ids.shape[1] > max_cache_length
1306
+ ):
1307
+ attention_mask = attention_mask[:, -max_cache_length:]
1308
+
1309
+ position_ids = kwargs.get("position_ids", None)
1310
+ if attention_mask is not None and position_ids is None:
1311
+ # create position_ids on the fly for batch generation
1312
+ position_ids = attention_mask.long().cumsum(-1) - 1
1313
+ position_ids.masked_fill_(attention_mask == 0, 1)
1314
+ if past_key_values:
1315
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1316
+
1317
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1318
+ if inputs_embeds is not None and past_key_values is None:
1319
+ model_inputs = {"inputs_embeds": inputs_embeds}
1320
+ else:
1321
+ model_inputs = {"input_ids": input_ids}
1322
+
1323
+ model_inputs.update(
1324
+ {
1325
+ "position_ids": position_ids,
1326
+ "past_key_values": past_key_values,
1327
+ "use_cache": kwargs.get("use_cache"),
1328
+ "attention_mask": attention_mask,
1329
+ }
1330
+ )
1331
+ return model_inputs
1332
+
1333
+ @staticmethod
1334
+ def _reorder_cache(past_key_values, beam_idx):
1335
+ reordered_past = ()
1336
+ for layer_past in past_key_values:
1337
+ reordered_past += (
1338
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1339
+ )
1340
+ return reordered_past
1341
+
1342
+
1343
+ @add_start_docstrings(
1344
+ """
1345
+ The Mixtral Model transformer with a sequence classification head on top (linear layer).
1346
+
1347
+ [`MixtralForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1348
+ (e.g. GPT-2) do.
1349
+
1350
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1351
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1352
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1353
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1354
+ each row of the batch).
1355
+ """,
1356
+ MIXTRAL_START_DOCSTRING,
1357
+ )
1358
+ # Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Mixtral, LLAMA->MIXTRAL
1359
+ class MixtralForSequenceClassification(MixtralPreTrainedModel):
1360
+ def __init__(self, config):
1361
+ super().__init__(config)
1362
+ self.num_labels = config.num_labels
1363
+ self.model = MixtralModel(config)
1364
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1365
+
1366
+ # Initialize weights and apply final processing
1367
+ self.post_init()
1368
+
1369
+ def get_input_embeddings(self):
1370
+ return self.model.embed_tokens
1371
+
1372
+ def set_input_embeddings(self, value):
1373
+ self.model.embed_tokens = value
1374
+
1375
+ @add_start_docstrings_to_model_forward(MIXTRAL_INPUTS_DOCSTRING)
1376
+ def forward(
1377
+ self,
1378
+ input_ids: torch.LongTensor = None,
1379
+ attention_mask: Optional[torch.Tensor] = None,
1380
+ position_ids: Optional[torch.LongTensor] = None,
1381
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1382
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1383
+ labels: Optional[torch.LongTensor] = None,
1384
+ use_cache: Optional[bool] = None,
1385
+ output_attentions: Optional[bool] = None,
1386
+ output_hidden_states: Optional[bool] = None,
1387
+ return_dict: Optional[bool] = None,
1388
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1389
+ r"""
1390
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1391
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1392
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1393
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1394
+ """
1395
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1396
+
1397
+ transformer_outputs = self.model(
1398
+ input_ids,
1399
+ attention_mask=attention_mask,
1400
+ position_ids=position_ids,
1401
+ past_key_values=past_key_values,
1402
+ inputs_embeds=inputs_embeds,
1403
+ use_cache=use_cache,
1404
+ output_attentions=output_attentions,
1405
+ output_hidden_states=output_hidden_states,
1406
+ return_dict=return_dict,
1407
+ )
1408
+ hidden_states = transformer_outputs[0]
1409
+ logits = self.score(hidden_states)
1410
+
1411
+ if input_ids is not None:
1412
+ batch_size = input_ids.shape[0]
1413
+ else:
1414
+ batch_size = inputs_embeds.shape[0]
1415
+
1416
+ if self.config.pad_token_id is None and batch_size != 1:
1417
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1418
+ if self.config.pad_token_id is None:
1419
+ sequence_lengths = -1
1420
+ else:
1421
+ if input_ids is not None:
1422
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1423
+ logits.device
1424
+ )
1425
+ else:
1426
+ sequence_lengths = -1
1427
+
1428
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1429
+
1430
+ loss = None
1431
+ if labels is not None:
1432
+ labels = labels.to(logits.device)
1433
+ if self.config.problem_type is None:
1434
+ if self.num_labels == 1:
1435
+ self.config.problem_type = "regression"
1436
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1437
+ self.config.problem_type = "single_label_classification"
1438
+ else:
1439
+ self.config.problem_type = "multi_label_classification"
1440
+
1441
+ if self.config.problem_type == "regression":
1442
+ loss_fct = MSELoss()
1443
+ if self.num_labels == 1:
1444
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1445
+ else:
1446
+ loss = loss_fct(pooled_logits, labels)
1447
+ elif self.config.problem_type == "single_label_classification":
1448
+ loss_fct = CrossEntropyLoss()
1449
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1450
+ elif self.config.problem_type == "multi_label_classification":
1451
+ loss_fct = BCEWithLogitsLoss()
1452
+ loss = loss_fct(pooled_logits, labels)
1453
+ if not return_dict:
1454
+ output = (pooled_logits,) + transformer_outputs[1:]
1455
+ return ((loss,) + output) if loss is not None else output
1456
+
1457
+ return SequenceClassifierOutputWithPast(
1458
+ loss=loss,
1459
+ logits=pooled_logits,
1460
+ past_key_values=transformer_outputs.past_key_values,
1461
+ hidden_states=transformer_outputs.hidden_states,
1462
+ attentions=transformer_outputs.attentions,
1463
+ )