BAAI
/

hyxmmm commited on
Commit
54c3659
1 Parent(s): 8ecc4e9

Create modeling_aquila.py

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