damerajee commited on
Commit
8067304
1 Parent(s): a336a21

Update modeling_Llamoe.py

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