HongzheBi commited on
Commit
f8955dd
·
verified ·
1 Parent(s): d4d09e5

Upload modeling_aquarius.py

Browse files
Files changed (1) hide show
  1. modeling_aquarius.py +1246 -0
modeling_aquarius.py ADDED
@@ -0,0 +1,1246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ import copy
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+ from torch.distributions.normal import Normal
33
+
34
+ from transformers.activations import ACT2FN
35
+ from transformers.modeling_outputs import (
36
+ BaseModelOutputWithPast,
37
+ CausalLMOutputWithPast,
38
+ MoECausalLMOutputWithPast,
39
+ )
40
+ from transformers.modeling_utils import PreTrainedModel
41
+ from transformers.utils import (
42
+ ModelOutput,
43
+ add_start_docstrings,
44
+ add_start_docstrings_to_model_forward,
45
+ logging,
46
+ replace_return_docstrings,
47
+ )
48
+
49
+ from .configuration_aquarius import AquariusConfig
50
+
51
+ from dataclasses import dataclass
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "AquariusConfig"
56
+
57
+
58
+ @dataclass
59
+ class MoEModelOutputWithPast(ModelOutput):
60
+ last_hidden_state: torch.FloatTensor = None
61
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
62
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
63
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
64
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
65
+
66
+
67
+ @dataclass
68
+ class MoECausalLMOutputWithPast(ModelOutput):
69
+ loss: Optional[torch.FloatTensor] = None
70
+ aux_loss: Optional[torch.FloatTensor] = None
71
+ logits: torch.FloatTensor = None
72
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
73
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
74
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
75
+ router_logits: Optional[Tuple[torch.FloatTensor]] = None
76
+
77
+
78
+
79
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
80
+ def _make_causal_mask(
81
+ input_ids_shape: torch.Size,
82
+ dtype: torch.dtype,
83
+ device: torch.device,
84
+ past_key_values_length: int = 0,
85
+ ):
86
+ """
87
+ Make causal mask used for bi-directional self-attention.
88
+ """
89
+ bsz, tgt_len = input_ids_shape
90
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
91
+ mask_cond = torch.arange(mask.size(-1), device=device)
92
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
93
+ mask = mask.to(dtype)
94
+
95
+ if past_key_values_length > 0:
96
+ mask = torch.cat(
97
+ [
98
+ torch.zeros(
99
+ tgt_len, past_key_values_length, dtype=dtype, device=device
100
+ ),
101
+ mask,
102
+ ],
103
+ dim=-1,
104
+ )
105
+ return mask[None, None, :, :].expand(
106
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
107
+ )
108
+
109
+
110
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
111
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
112
+ """
113
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
114
+ """
115
+ bsz, src_len = mask.size()
116
+ tgt_len = tgt_len if tgt_len is not None else src_len
117
+
118
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
119
+
120
+ inverted_mask = 1.0 - expanded_mask
121
+
122
+ return inverted_mask.masked_fill(
123
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
124
+ )
125
+
126
+
127
+ class LlamaRMSNorm(nn.Module):
128
+ def __init__(self, hidden_size, eps=1e-6):
129
+ """
130
+ LlamaRMSNorm is equivalent to T5LayerNorm
131
+ """
132
+ super().__init__()
133
+ self.weight = nn.Parameter(torch.ones(hidden_size))
134
+ self.variance_epsilon = eps
135
+
136
+ def forward(self, hidden_states):
137
+ input_dtype = hidden_states.dtype
138
+ hidden_states = hidden_states.to(torch.float32)
139
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
140
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
141
+ return self.weight * hidden_states.to(input_dtype)
142
+
143
+
144
+ class LlamaRotaryEmbedding(torch.nn.Module):
145
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
146
+ super().__init__()
147
+
148
+ self.dim = dim
149
+ self.max_position_embeddings = max_position_embeddings
150
+ self.base = base
151
+ inv_freq = 1.0 / (
152
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
153
+ )
154
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
155
+
156
+ # Build here to make `torch.jit.trace` work.
157
+ self._set_cos_sin_cache(
158
+ seq_len=max_position_embeddings,
159
+ device=self.inv_freq.device,
160
+ dtype=torch.get_default_dtype(),
161
+ )
162
+
163
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
164
+ self.max_seq_len_cached = seq_len
165
+ t = torch.arange(
166
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
167
+ )
168
+
169
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
170
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
171
+ emb = torch.cat((freqs, freqs), dim=-1)
172
+ self.register_buffer(
173
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
174
+ )
175
+ self.register_buffer(
176
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
177
+ )
178
+
179
+ def forward(self, x, seq_len=None):
180
+ # x: [bs, num_attention_heads, seq_len, head_size]
181
+ if seq_len > self.max_seq_len_cached:
182
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
183
+
184
+ return (
185
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
186
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
187
+ )
188
+
189
+
190
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
191
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
192
+
193
+ def __init__(
194
+ self,
195
+ dim,
196
+ max_position_embeddings=2048,
197
+ base=10000,
198
+ device=None,
199
+ scaling_factor=1.0,
200
+ ):
201
+ self.scaling_factor = scaling_factor
202
+ super().__init__(dim, max_position_embeddings, base, device)
203
+
204
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
205
+ self.max_seq_len_cached = seq_len
206
+ t = torch.arange(
207
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
208
+ )
209
+ t = t / self.scaling_factor
210
+
211
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
212
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
213
+ emb = torch.cat((freqs, freqs), dim=-1)
214
+ self.register_buffer(
215
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
216
+ )
217
+ self.register_buffer(
218
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
219
+ )
220
+
221
+
222
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
223
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
224
+
225
+ def __init__(
226
+ self,
227
+ dim,
228
+ max_position_embeddings=2048,
229
+ base=10000,
230
+ device=None,
231
+ scaling_factor=1.0,
232
+ ):
233
+ self.scaling_factor = scaling_factor
234
+ super().__init__(dim, max_position_embeddings, base, device)
235
+
236
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
237
+ self.max_seq_len_cached = seq_len
238
+
239
+ if seq_len > self.max_position_embeddings:
240
+ base = self.base * (
241
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
242
+ - (self.scaling_factor - 1)
243
+ ) ** (self.dim / (self.dim - 2))
244
+ inv_freq = 1.0 / (
245
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
246
+ )
247
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
248
+
249
+ t = torch.arange(
250
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
251
+ )
252
+
253
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
254
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
255
+ emb = torch.cat((freqs, freqs), dim=-1)
256
+ self.register_buffer(
257
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
258
+ )
259
+ self.register_buffer(
260
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
261
+ )
262
+
263
+
264
+ def rotate_half(x):
265
+ """Rotates half the hidden dims of the input."""
266
+ x1 = x[..., : x.shape[-1] // 2]
267
+ x2 = x[..., x.shape[-1] // 2 :]
268
+ return torch.cat((-x2, x1), dim=-1)
269
+
270
+
271
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
272
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
273
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
274
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
275
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
276
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
277
+ q_embed = (q * cos) + (rotate_half(q) * sin)
278
+ k_embed = (k * cos) + (rotate_half(k) * sin)
279
+ return q_embed, k_embed
280
+
281
+
282
+ # Llama MoE
283
+ def load_balancing_loss_func(gate_logits: torch.Tensor, num_experts: torch.Tensor = None, top_k=2) -> float:
284
+ r"""
285
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
286
+
287
+ See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
288
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
289
+ experts is too unbalanced.
290
+
291
+ Args:
292
+ gate_logits (Union[`torch.Tensor`, Tuple[torch.Tensor]):
293
+ Logits from the `gate`, should be a tuple of tensors. Shape: [batch_size, seqeunce_length, num_experts].
294
+ num_experts (`int`, *optional*):
295
+ Number of experts
296
+
297
+ Returns:
298
+ The auxiliary loss.
299
+ """
300
+ if gate_logits is None:
301
+ return 0
302
+
303
+ if isinstance(gate_logits, tuple):
304
+ # cat along the layers?
305
+ compute_device = gate_logits[0].device
306
+ gate_logits = torch.cat([gate.to(compute_device) for gate in gate_logits], dim=0)
307
+
308
+ routing_weights, selected_experts = torch.topk(gate_logits, top_k, dim=-1)
309
+ routing_weights = routing_weights.softmax(dim=-1)
310
+
311
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
312
+ if selected_experts.dtype != torch.int64:
313
+ selected_experts = selected_experts.to(torch.int64)
314
+
315
+ if len(selected_experts.shape) == 2:
316
+ selected_experts = selected_experts.unsqueeze(2)
317
+
318
+ expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
319
+
320
+ # For a given token, determine if it was routed to a given expert.
321
+ expert_mask = torch.max(expert_mask, axis=-2).values
322
+
323
+ # cast to float32 otherwise mean will fail
324
+ expert_mask = expert_mask.to(torch.float32)
325
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
326
+
327
+ router_prob_per_group_and_expert = torch.mean(routing_weights, axis=-1)
328
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert.unsqueeze(-1)) * (num_experts**2)
329
+
330
+
331
+ class ParallelAdapterMLP(nn.Module):
332
+ def __init__(self, config, adapter_dim, adapter_scaling):
333
+ super().__init__()
334
+ self.config = config
335
+ self.intermediate_size = config.intermediate_size
336
+ self.hidden_size = config.hidden_size
337
+ self.adapter_down = nn.Linear(self.hidden_size, adapter_dim, bias=False)
338
+ self.adapter_up = nn.Linear(adapter_dim, self.hidden_size, bias=False)
339
+ self.adapter_act = nn.GELU()
340
+
341
+ self.adapter_dropout = nn.Dropout(p=0.1)
342
+ self.adapter_scaling = adapter_scaling
343
+
344
+ def forward(self, x):
345
+ x = self.adapter_dropout(x)
346
+ x = self.adapter_scaling * self.adapter_up(self.adapter_act(self.adapter_down(x)))
347
+ return x
348
+
349
+
350
+ class AquariusGateAdapter(nn.Module):
351
+ def __init__(self, config: AquariusConfig):
352
+ super().__init__()
353
+
354
+ self.intermediate_size = config.intermediate_size
355
+ self.hidden_size = config.hidden_size
356
+
357
+ # Step 1: Router
358
+ self.num_experts = config.num_experts
359
+ self.topk = config.topk
360
+ self.router = nn.Linear(
361
+ config.hidden_size, self.num_experts, bias=False
362
+ )
363
+ self.dtype = getattr(torch, config.moe_dtype)
364
+
365
+ # Step 2: Get the experts
366
+ self.experts = nn.ModuleDict()
367
+ for idx in range(config.num_experts):
368
+ self.experts[f"expert_{idx}"] = ParallelAdapterMLP(config, config.adapter_dim, config.moe_scaling)
369
+
370
+ def forward(self, input_hidden_states, output_hidden_states, router_hidden_states):
371
+ orig_shape = output_hidden_states.shape
372
+ input_hidden_states = input_hidden_states.view(-1, input_hidden_states.shape[-1])
373
+ output_hidden_states = output_hidden_states.view(-1, output_hidden_states.shape[-1])
374
+ router_hidden_states = router_hidden_states.view(-1, router_hidden_states.shape[-1])
375
+ #print("orig_shape",orig_shape)
376
+ #print("input_hidden_states",input_hidden_states.shape)
377
+ #print("router_hidden_states", router_hidden_states.shape)
378
+
379
+ router_logits = self.router(router_hidden_states)
380
+
381
+ expert_weights, expert_indices = torch.topk(router_logits, self.topk, dim=-1)
382
+ #print("expert_weights",expert_weights.shape)
383
+ expert_weights = expert_weights.softmax(dim=-1)
384
+ flat_expert_indices = expert_indices.view(-1)
385
+
386
+ input_hidden_states = input_hidden_states.repeat_interleave(self.topk, dim=0)
387
+ expert_hidden_states = output_hidden_states.repeat_interleave(self.topk, dim=0)
388
+ for idx, expert in enumerate(self.experts.values()):
389
+ expert_hidden_states[flat_expert_indices == idx] += expert(input_hidden_states[flat_expert_indices == idx])
390
+ hidden_states = (expert_hidden_states.view(*expert_weights.shape, -1) * expert_weights.unsqueeze(-1)).sum(dim=1)
391
+
392
+ return hidden_states.view(*orig_shape), router_logits
393
+
394
+
395
+ class LlamaMLP(nn.Module):
396
+ def __init__(self, config):
397
+ super().__init__()
398
+ self.config = config
399
+ self.hidden_size = config.hidden_size
400
+ self.intermediate_size = config.intermediate_size
401
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
402
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
403
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
404
+ self.act_fn = ACT2FN[config.hidden_act]
405
+
406
+ self.moe_adapter = AquariusGateAdapter(config)
407
+
408
+ def forward(self, x):
409
+ router_hidden_states = x
410
+ up_proj = self.act_fn(self.gate_proj(x)) * self.up_proj(x)
411
+ down_proj = self.down_proj(up_proj)
412
+ down_proj, router_logits = self.moe_adapter(down_proj, down_proj, router_hidden_states)
413
+
414
+ return down_proj, router_logits
415
+
416
+
417
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
418
+ """
419
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
420
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
421
+ """
422
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
423
+ if n_rep == 1:
424
+ return hidden_states
425
+ hidden_states = hidden_states[:, :, None, :, :].expand(
426
+ batch, num_key_value_heads, n_rep, slen, head_dim
427
+ )
428
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
429
+
430
+
431
+ class LlamaAttention(nn.Module):
432
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
433
+
434
+ def __init__(self, config: AquariusConfig):
435
+ super().__init__()
436
+ self.config = config
437
+ self.hidden_size = config.hidden_size
438
+ self.num_heads = config.num_attention_heads
439
+ self.head_dim = self.hidden_size // self.num_heads
440
+ self.num_key_value_heads = config.num_key_value_heads
441
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
442
+ self.max_position_embeddings = config.max_position_embeddings
443
+
444
+ if (self.head_dim * self.num_heads) != self.hidden_size:
445
+ raise ValueError(
446
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
447
+ f" and `num_heads`: {self.num_heads})."
448
+ )
449
+ self.q_proj = nn.Linear(
450
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
451
+ )
452
+ self.k_proj = nn.Linear(
453
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
454
+ )
455
+ self.v_proj = nn.Linear(
456
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
457
+ )
458
+ self.o_proj = nn.Linear(
459
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
460
+ )
461
+ self._init_rope()
462
+
463
+ def _init_rope(self):
464
+ if self.config.rope_scaling is None:
465
+ self.rotary_emb = LlamaRotaryEmbedding(
466
+ self.head_dim, max_position_embeddings=self.max_position_embeddings
467
+ )
468
+ else:
469
+ scaling_type = self.config.rope_scaling["type"]
470
+ scaling_factor = self.config.rope_scaling["factor"]
471
+ if scaling_type == "linear":
472
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
473
+ self.head_dim,
474
+ max_position_embeddings=self.max_position_embeddings,
475
+ scaling_factor=scaling_factor,
476
+ )
477
+ elif scaling_type == "dynamic":
478
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
479
+ self.head_dim,
480
+ max_position_embeddings=self.max_position_embeddings,
481
+ scaling_factor=scaling_factor,
482
+ )
483
+ else:
484
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
485
+
486
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
487
+ return (
488
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
489
+ .transpose(1, 2)
490
+ .contiguous()
491
+ )
492
+
493
+ def forward(
494
+ self,
495
+ hidden_states: torch.Tensor,
496
+ attention_mask: Optional[torch.Tensor] = None,
497
+ position_ids: Optional[torch.LongTensor] = None,
498
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
499
+ output_attentions: bool = False,
500
+ use_cache: bool = False,
501
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
502
+ bsz, q_len, _ = hidden_states.size()
503
+
504
+ if self.config.pretraining_tp > 1:
505
+ key_value_slicing = (
506
+ self.num_key_value_heads * self.head_dim
507
+ ) // self.config.pretraining_tp
508
+ query_slices = self.q_proj.weight.split(
509
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
510
+ )
511
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
512
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
513
+
514
+ query_states = [
515
+ F.linear(hidden_states, query_slices[i])
516
+ for i in range(self.config.pretraining_tp)
517
+ ]
518
+ query_states = torch.cat(query_states, dim=-1)
519
+
520
+ key_states = [
521
+ F.linear(hidden_states, key_slices[i])
522
+ for i in range(self.config.pretraining_tp)
523
+ ]
524
+ key_states = torch.cat(key_states, dim=-1)
525
+
526
+ value_states = [
527
+ F.linear(hidden_states, value_slices[i])
528
+ for i in range(self.config.pretraining_tp)
529
+ ]
530
+ value_states = torch.cat(value_states, dim=-1)
531
+
532
+ else:
533
+ query_states = self.q_proj(hidden_states)
534
+ key_states = self.k_proj(hidden_states)
535
+ value_states = self.v_proj(hidden_states)
536
+
537
+ query_states = query_states.view(
538
+ bsz, q_len, self.num_heads, self.head_dim
539
+ ).transpose(1, 2)
540
+ key_states = key_states.view(
541
+ bsz, q_len, self.num_key_value_heads, self.head_dim
542
+ ).transpose(1, 2)
543
+ value_states = value_states.view(
544
+ bsz, q_len, self.num_key_value_heads, self.head_dim
545
+ ).transpose(1, 2)
546
+
547
+ kv_seq_len = key_states.shape[-2]
548
+ if past_key_value is not None:
549
+ kv_seq_len += past_key_value[0].shape[-2]
550
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
551
+ query_states, key_states = apply_rotary_pos_emb(
552
+ query_states, key_states, cos, sin, position_ids
553
+ )
554
+
555
+ if past_key_value is not None:
556
+ # reuse k, v, self_attention
557
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
558
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
559
+
560
+ past_key_value = (key_states, value_states) if use_cache else None
561
+
562
+ # repeat k/v heads if n_kv_heads < n_heads
563
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
564
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
565
+
566
+ attn_weights = torch.matmul(
567
+ query_states, key_states.transpose(2, 3)
568
+ ) / math.sqrt(self.head_dim)
569
+
570
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
571
+ raise ValueError(
572
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
573
+ f" {attn_weights.size()}"
574
+ )
575
+
576
+ if attention_mask is not None:
577
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
578
+ raise ValueError(
579
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
580
+ )
581
+ attn_weights = attn_weights + attention_mask
582
+
583
+ # upcast attention to fp32
584
+ attn_weights = nn.functional.softmax(
585
+ attn_weights, dim=-1, dtype=torch.float32
586
+ ).to(query_states.dtype)
587
+ attn_output = torch.matmul(attn_weights, value_states)
588
+
589
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
590
+ raise ValueError(
591
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
592
+ f" {attn_output.size()}"
593
+ )
594
+
595
+ attn_output = attn_output.transpose(1, 2).contiguous()
596
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
597
+
598
+ if self.config.pretraining_tp > 1:
599
+ attn_output = attn_output.split(
600
+ self.hidden_size // self.config.pretraining_tp, dim=2
601
+ )
602
+ o_proj_slices = self.o_proj.weight.split(
603
+ self.hidden_size // self.config.pretraining_tp, dim=1
604
+ )
605
+ attn_output = sum(
606
+ [
607
+ F.linear(attn_output[i], o_proj_slices[i])
608
+ for i in range(self.config.pretraining_tp)
609
+ ]
610
+ )
611
+ else:
612
+ attn_output = self.o_proj(attn_output)
613
+
614
+ if not output_attentions:
615
+ attn_weights = None
616
+
617
+ return attn_output, attn_weights, past_key_value
618
+
619
+
620
+ class LlamaDecoderLayer(nn.Module):
621
+ def __init__(self, config: AquariusConfig):
622
+ super().__init__()
623
+ self.config = config
624
+ self.hidden_size = config.hidden_size
625
+ self.self_attn = LlamaAttention(config=config)
626
+ self.mlp = LlamaMLP(config)
627
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
628
+ self.post_attention_layernorm = LlamaRMSNorm(
629
+ config.hidden_size, eps=config.rms_norm_eps
630
+ )
631
+
632
+ def forward(
633
+ self,
634
+ hidden_states: torch.Tensor,
635
+ attention_mask: Optional[torch.Tensor] = None,
636
+ position_ids: Optional[torch.LongTensor] = None,
637
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
638
+ output_attentions: Optional[bool] = False,
639
+ output_router_logits: Optional[bool] = False,
640
+ use_cache: Optional[bool] = False,
641
+ ) -> Tuple[
642
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
643
+ ]:
644
+ """
645
+ Args:
646
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
647
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
648
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
649
+ output_attentions (`bool`, *optional*):
650
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
651
+ returned tensors for more detail.
652
+ use_cache (`bool`, *optional*):
653
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
654
+ (see `past_key_values`).
655
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
656
+ """
657
+
658
+ residual = hidden_states
659
+
660
+ hidden_states = self.input_layernorm(hidden_states)
661
+ # router_hidden_states = hidden_states
662
+
663
+ # Self Attention
664
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
665
+ hidden_states=hidden_states,
666
+ attention_mask=attention_mask,
667
+ position_ids=position_ids,
668
+ past_key_value=past_key_value,
669
+ output_attentions=output_attentions,
670
+ use_cache=use_cache,
671
+ )
672
+ hidden_states = residual + hidden_states
673
+
674
+ # Fully Connected
675
+ residual = hidden_states
676
+ hidden_states = self.post_attention_layernorm(hidden_states)
677
+ hidden_states, router_logits = self.mlp(hidden_states)
678
+ hidden_states = residual + hidden_states
679
+
680
+ outputs = (hidden_states,)
681
+
682
+ if output_attentions:
683
+ outputs += (self_attn_weights,)
684
+
685
+ if use_cache:
686
+ outputs += (present_key_value,)
687
+
688
+ if output_router_logits:
689
+ outputs += (router_logits,)
690
+
691
+ return outputs
692
+
693
+
694
+ LLAMA_START_DOCSTRING = r"""
695
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
696
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
697
+ etc.)
698
+
699
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
700
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
701
+ and behavior.
702
+
703
+ Parameters:
704
+ config ([`AquariusConfig`]):
705
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
706
+ load the weights associated with the model, only the configuration. Check out the
707
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
708
+ """
709
+
710
+
711
+ @add_start_docstrings(
712
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
713
+ LLAMA_START_DOCSTRING,
714
+ )
715
+ class LlamaPreTrainedModel(PreTrainedModel):
716
+ config_class = AquariusConfig
717
+ base_model_prefix = "model"
718
+ supports_gradient_checkpointing = True
719
+ _no_split_modules = ["LlamaDecoderLayer"]
720
+ _skip_keys_device_placement = "past_key_values"
721
+
722
+ def _init_weights(self, module):
723
+ std = self.config.initializer_range
724
+ if isinstance(module, nn.Linear):
725
+ module.weight.data.normal_(mean=0.0, std=std)
726
+ if module.bias is not None:
727
+ module.bias.data.zero_()
728
+ elif isinstance(module, nn.Embedding):
729
+ module.weight.data.normal_(mean=0.0, std=std)
730
+ if module.padding_idx is not None:
731
+ module.weight.data[module.padding_idx].zero_()
732
+
733
+ def _set_gradient_checkpointing(self, module, value=False):
734
+ if isinstance(module, LlamaModel):
735
+ module.gradient_checkpointing = value
736
+
737
+
738
+ LLAMA_INPUTS_DOCSTRING = r"""
739
+ Args:
740
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
741
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
742
+ it.
743
+
744
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
745
+ [`PreTrainedTokenizer.__call__`] for details.
746
+
747
+ [What are input IDs?](../glossary#input-ids)
748
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
749
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
750
+
751
+ - 1 for tokens that are **not masked**,
752
+ - 0 for tokens that are **masked**.
753
+
754
+ [What are attention masks?](../glossary#attention-mask)
755
+
756
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
757
+ [`PreTrainedTokenizer.__call__`] for details.
758
+
759
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
760
+ `past_key_values`).
761
+
762
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
763
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
764
+ information on the default strategy.
765
+
766
+ - 1 indicates the head is **not masked**,
767
+ - 0 indicates the head is **masked**.
768
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
769
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
770
+ config.n_positions - 1]`.
771
+
772
+ [What are position IDs?](../glossary#position-ids)
773
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
774
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
775
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
776
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
777
+
778
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
779
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
780
+
781
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
782
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
783
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
784
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
785
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
786
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
787
+ model's internal embedding lookup matrix.
788
+ use_cache (`bool`, *optional*):
789
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
790
+ `past_key_values`).
791
+ output_attentions (`bool`, *optional*):
792
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
793
+ tensors for more detail.
794
+ output_hidden_states (`bool`, *optional*):
795
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
796
+ more detail.
797
+ output_router_logits (`bool`, *optional*):
798
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
799
+ should not be returned during inference.
800
+ return_dict (`bool`, *optional*):
801
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
802
+ """
803
+
804
+
805
+ @add_start_docstrings(
806
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
807
+ LLAMA_START_DOCSTRING,
808
+ )
809
+ class LlamaModel(LlamaPreTrainedModel):
810
+ """
811
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
812
+
813
+ Args:
814
+ config: AquariusConfig
815
+ """
816
+
817
+ def __init__(self, config: AquariusConfig):
818
+ super().__init__(config)
819
+ self.padding_idx = config.pad_token_id
820
+ self.vocab_size = config.vocab_size
821
+
822
+ self.embed_tokens = nn.Embedding(
823
+ config.vocab_size, config.hidden_size, self.padding_idx
824
+ )
825
+ self.layers = nn.ModuleList(
826
+ [LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]
827
+ )
828
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
829
+
830
+ self.gradient_checkpointing = False
831
+ # Initialize weights and apply final processing
832
+ self.post_init()
833
+
834
+ def get_input_embeddings(self):
835
+ return self.embed_tokens
836
+
837
+ def set_input_embeddings(self, value):
838
+ self.embed_tokens = value
839
+
840
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
841
+ def _prepare_decoder_attention_mask(
842
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
843
+ ):
844
+ # create causal mask
845
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
846
+ combined_attention_mask = None
847
+ if input_shape[-1] > 1:
848
+ combined_attention_mask = _make_causal_mask(
849
+ input_shape,
850
+ inputs_embeds.dtype,
851
+ device=inputs_embeds.device,
852
+ past_key_values_length=past_key_values_length,
853
+ )
854
+
855
+ if attention_mask is not None:
856
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
857
+ expanded_attn_mask = _expand_mask(
858
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
859
+ ).to(inputs_embeds.device)
860
+ combined_attention_mask = (
861
+ expanded_attn_mask
862
+ if combined_attention_mask is None
863
+ else expanded_attn_mask + combined_attention_mask
864
+ )
865
+
866
+ return combined_attention_mask
867
+
868
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
869
+ def forward(
870
+ self,
871
+ input_ids: torch.LongTensor = None,
872
+ attention_mask: Optional[torch.Tensor] = None,
873
+ position_ids: Optional[torch.LongTensor] = None,
874
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
875
+ inputs_embeds: Optional[torch.FloatTensor] = None,
876
+ use_cache: Optional[bool] = None,
877
+ output_attentions: Optional[bool] = None,
878
+ output_hidden_states: Optional[bool] = None,
879
+ output_router_logits: Optional[bool] = None,
880
+ return_dict: Optional[bool] = None,
881
+ ) -> Union[Tuple, MoEModelOutputWithPast]:
882
+ output_attentions = (
883
+ output_attentions
884
+ if output_attentions is not None
885
+ else self.config.output_attentions
886
+ )
887
+ output_hidden_states = (
888
+ output_hidden_states
889
+ if output_hidden_states is not None
890
+ else self.config.output_hidden_states
891
+ )
892
+ output_router_logits = (
893
+ output_router_logits
894
+ if output_router_logits is not None
895
+ else self.config.output_router_logits
896
+ )
897
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
898
+
899
+ return_dict = (
900
+ return_dict if return_dict is not None else self.config.use_return_dict
901
+ )
902
+
903
+ # retrieve input_ids and inputs_embeds
904
+ if input_ids is not None and inputs_embeds is not None:
905
+ raise ValueError(
906
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
907
+ )
908
+ elif input_ids is not None:
909
+ batch_size, seq_length = input_ids.shape
910
+ elif inputs_embeds is not None:
911
+ batch_size, seq_length, _ = inputs_embeds.shape
912
+ else:
913
+ raise ValueError(
914
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
915
+ )
916
+
917
+ seq_length_with_past = seq_length
918
+ past_key_values_length = 0
919
+
920
+ if past_key_values is not None:
921
+ past_key_values_length = past_key_values[0][0].shape[2]
922
+ seq_length_with_past = seq_length_with_past + past_key_values_length
923
+
924
+ if position_ids is None:
925
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
926
+ position_ids = torch.arange(
927
+ past_key_values_length,
928
+ seq_length + past_key_values_length,
929
+ dtype=torch.long,
930
+ device=device,
931
+ )
932
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
933
+ else:
934
+ position_ids = position_ids.view(-1, seq_length).long()
935
+
936
+ if inputs_embeds is None:
937
+ inputs_embeds = self.embed_tokens(input_ids)
938
+ # embed positions
939
+ if attention_mask is None:
940
+ attention_mask = torch.ones(
941
+ (batch_size, seq_length_with_past),
942
+ dtype=torch.bool,
943
+ device=inputs_embeds.device,
944
+ )
945
+ attention_mask = self._prepare_decoder_attention_mask(
946
+ attention_mask,
947
+ (batch_size, seq_length),
948
+ inputs_embeds,
949
+ past_key_values_length,
950
+ )
951
+
952
+ hidden_states = inputs_embeds
953
+
954
+ if self.gradient_checkpointing and self.training:
955
+ if use_cache:
956
+ logger.warning_once(
957
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
958
+ )
959
+ use_cache = False
960
+
961
+ # decoder layers
962
+ all_hidden_states = () if output_hidden_states else None
963
+ all_self_attns = () if output_attentions else None
964
+ all_router_logits = () if output_router_logits else None
965
+ next_decoder_cache = () if use_cache else None
966
+
967
+ for idx, decoder_layer in enumerate(self.layers):
968
+ if output_hidden_states:
969
+ all_hidden_states += (hidden_states,)
970
+
971
+ past_key_value = (
972
+ past_key_values[idx] if past_key_values is not None else None
973
+ )
974
+
975
+ if self.gradient_checkpointing and self.training:
976
+
977
+ def create_custom_forward(module):
978
+ def custom_forward(*inputs):
979
+ # None for past_key_value
980
+ return module(
981
+ *inputs, output_attentions, output_router_logits, None
982
+ )
983
+
984
+ return custom_forward
985
+
986
+ layer_outputs = torch.utils.checkpoint.checkpoint(
987
+ create_custom_forward(decoder_layer),
988
+ hidden_states,
989
+ attention_mask,
990
+ position_ids,
991
+ None,
992
+ )
993
+ else:
994
+ layer_outputs = decoder_layer(
995
+ hidden_states,
996
+ attention_mask=attention_mask,
997
+ position_ids=position_ids,
998
+ past_key_value=past_key_value,
999
+ output_attentions=output_attentions,
1000
+ output_router_logits=output_router_logits,
1001
+ use_cache=use_cache,
1002
+ )
1003
+
1004
+ hidden_states = layer_outputs[0]
1005
+
1006
+ if use_cache:
1007
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1008
+
1009
+ if output_attentions:
1010
+ all_self_attns += (layer_outputs[1],)
1011
+
1012
+ if output_router_logits:
1013
+ all_router_logits += (layer_outputs[-1],)
1014
+
1015
+ hidden_states = self.norm(hidden_states)
1016
+
1017
+ # add hidden states from the last decoder layer
1018
+ if output_hidden_states:
1019
+ all_hidden_states += (hidden_states,)
1020
+
1021
+ next_cache = next_decoder_cache if use_cache else None
1022
+ if not return_dict:
1023
+ return tuple(
1024
+ v
1025
+ for v in [
1026
+ hidden_states,
1027
+ next_cache,
1028
+ all_hidden_states,
1029
+ all_self_attns,
1030
+ all_router_logits
1031
+ ]
1032
+ if v is not None
1033
+ )
1034
+ return MoEModelOutputWithPast(
1035
+ last_hidden_state=hidden_states,
1036
+ past_key_values=next_cache,
1037
+ hidden_states=all_hidden_states,
1038
+ attentions=all_self_attns,
1039
+ router_logits=all_router_logits,
1040
+ )
1041
+
1042
+
1043
+ class AquariusModel(LlamaPreTrainedModel):
1044
+ _tied_weights_keys = ["lm_head.weight"]
1045
+
1046
+ def __init__(self, config):
1047
+ super().__init__(config)
1048
+ self.config = config
1049
+ self.model = LlamaModel(config)
1050
+ self.vocab_size = config.vocab_size
1051
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1052
+
1053
+ # Initialize weights and apply final processing
1054
+ self.post_init()
1055
+
1056
+ def get_input_embeddings(self):
1057
+ return self.model.embed_tokens
1058
+
1059
+ def set_input_embeddings(self, value):
1060
+ self.model.embed_tokens = value
1061
+
1062
+ def get_output_embeddings(self):
1063
+ return self.lm_head
1064
+
1065
+ def set_output_embeddings(self, new_embeddings):
1066
+ self.lm_head = new_embeddings
1067
+
1068
+ def set_decoder(self, decoder):
1069
+ self.model = decoder
1070
+
1071
+ def get_decoder(self):
1072
+ return self.model
1073
+
1074
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1075
+ @replace_return_docstrings(
1076
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1077
+ )
1078
+ def forward(
1079
+ self,
1080
+ input_ids: torch.LongTensor = None,
1081
+ attention_mask: Optional[torch.Tensor] = None,
1082
+ position_ids: Optional[torch.LongTensor] = None,
1083
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1084
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1085
+ labels: Optional[torch.LongTensor] = None,
1086
+ use_cache: Optional[bool] = None,
1087
+ output_attentions: Optional[bool] = None,
1088
+ output_hidden_states: Optional[bool] = None,
1089
+ output_router_logits: Optional[bool] = None,
1090
+ return_dict: Optional[bool] = None,
1091
+ ) -> Union[Tuple, MoECausalLMOutputWithPast]:
1092
+ r"""
1093
+ Args:
1094
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1095
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1096
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1097
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1098
+
1099
+ Returns:
1100
+
1101
+ Example:
1102
+
1103
+ ```python
1104
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1105
+
1106
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1107
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1108
+
1109
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1110
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1111
+
1112
+ >>> # Generate
1113
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1114
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1115
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1116
+ ```"""
1117
+
1118
+ output_attentions = (
1119
+ output_attentions
1120
+ if output_attentions is not None
1121
+ else self.config.output_attentions
1122
+ )
1123
+ output_hidden_states = (
1124
+ output_hidden_states
1125
+ if output_hidden_states is not None
1126
+ else self.config.output_hidden_states
1127
+ )
1128
+ output_router_logits = (
1129
+ output_router_logits if output_router_logits is not None else self.config.output_router_logits
1130
+ )
1131
+ return_dict = (
1132
+ return_dict if return_dict is not None else self.config.use_return_dict
1133
+ )
1134
+
1135
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1136
+ outputs = self.model(
1137
+ input_ids=input_ids,
1138
+ attention_mask=attention_mask,
1139
+ position_ids=position_ids,
1140
+ past_key_values=past_key_values,
1141
+ inputs_embeds=inputs_embeds,
1142
+ use_cache=use_cache,
1143
+ output_attentions=output_attentions,
1144
+ output_hidden_states=output_hidden_states,
1145
+ output_router_logits=output_router_logits,
1146
+ return_dict=return_dict,
1147
+ )
1148
+
1149
+ hidden_states = outputs[0]
1150
+ if self.config.pretraining_tp > 1:
1151
+ lm_head_slices = self.lm_head.weight.split(
1152
+ self.vocab_size // self.config.pretraining_tp, dim=0
1153
+ )
1154
+ logits = [
1155
+ F.linear(hidden_states, lm_head_slices[i])
1156
+ for i in range(self.config.pretraining_tp)
1157
+ ]
1158
+ logits = torch.cat(logits, dim=-1)
1159
+ else:
1160
+ logits = self.lm_head(hidden_states)
1161
+ logits = logits.float()
1162
+
1163
+ loss = None
1164
+
1165
+ if labels is not None:
1166
+ # Shift so that tokens < n predict n
1167
+ shift_logits = logits[..., :-1, :].contiguous()
1168
+ shift_labels = labels[..., 1:].contiguous()
1169
+ # Flatten the tokens
1170
+ loss_fct = CrossEntropyLoss()
1171
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1172
+ shift_labels = shift_labels.view(-1)
1173
+ # Enable model parallelism
1174
+ shift_labels = shift_labels.to(shift_logits.device)
1175
+ loss = loss_fct(shift_logits, shift_labels)
1176
+
1177
+ aux_loss = None
1178
+ if output_router_logits:
1179
+ aux_loss = load_balancing_loss_func(
1180
+ outputs.router_logits if return_dict else outputs[-1], self.config.num_experts, self.config.topk
1181
+ )
1182
+ if labels is not None:
1183
+ loss += 0.01 * aux_loss
1184
+
1185
+ if not return_dict:
1186
+ output = (logits,) + outputs[1:]
1187
+ if output_router_logits:
1188
+ output = (aux_loss,) + output
1189
+ return (loss,) + output if loss is not None else output
1190
+
1191
+ return MoECausalLMOutputWithPast(
1192
+ loss=loss,
1193
+ aux_loss=aux_loss,
1194
+ logits=logits,
1195
+ past_key_values=outputs.past_key_values,
1196
+ hidden_states=outputs.hidden_states,
1197
+ attentions=outputs.attentions,
1198
+ router_logits=outputs.router_logits,
1199
+ )
1200
+
1201
+ def prepare_inputs_for_generation(
1202
+ self,
1203
+ input_ids,
1204
+ past_key_values=None,
1205
+ attention_mask=None,
1206
+ inputs_embeds=None,
1207
+ **kwargs,
1208
+ ):
1209
+ if past_key_values:
1210
+ input_ids = input_ids[:, -1:]
1211
+
1212
+ position_ids = kwargs.get("position_ids", None)
1213
+ if attention_mask is not None and position_ids is None:
1214
+ # create position_ids on the fly for batch generation
1215
+ position_ids = attention_mask.long().cumsum(-1) - 1
1216
+ position_ids.masked_fill_(attention_mask == 0, 1)
1217
+ if past_key_values:
1218
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1219
+
1220
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1221
+ if inputs_embeds is not None and past_key_values is None:
1222
+ model_inputs = {"inputs_embeds": inputs_embeds}
1223
+ else:
1224
+ model_inputs = {"input_ids": input_ids}
1225
+
1226
+ model_inputs.update(
1227
+ {
1228
+ "position_ids": position_ids,
1229
+ "past_key_values": past_key_values,
1230
+ "use_cache": kwargs.get("use_cache"),
1231
+ "attention_mask": attention_mask,
1232
+ }
1233
+ )
1234
+ return model_inputs
1235
+
1236
+ @staticmethod
1237
+ def _reorder_cache(past_key_values, beam_idx):
1238
+ reordered_past = ()
1239
+ for layer_past in past_key_values:
1240
+ reordered_past += (
1241
+ tuple(
1242
+ past_state.index_select(0, beam_idx.to(past_state.device))
1243
+ for past_state in layer_past
1244
+ ),
1245
+ )
1246
+ return reordered_past