IEIT-Yuan commited on
Commit
12267e6
1 Parent(s): c7b6a15

upload model

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