mattshumer commited on
Commit
7d2f42f
1 Parent(s): 2142302

Create modeling_moe_mistral.py

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