damerajee commited on
Commit
fdf3b4d
1 Parent(s): 63f1b5b

Create modeling_Hixtral.py

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