Muennighoff commited on
Commit
1e22ca5
1 Parent(s): 3dfbf47

Create modeling_gritlm8x7b.py

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