IEIT-Yuan commited on
Commit
ee5c0f2
1 Parent(s): 584652c

update cpu

Browse files
Files changed (2) hide show
  1. config_cpu.json +40 -0
  2. yuan_hf_model_cpu.py +1141 -0
config_cpu.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config":true,
3
+ "architectures": [
4
+ "YuanForCausalLM"
5
+ ],
6
+ "auto_map":{
7
+ "AutoConfig":"configuration_yuan.YuanConfig",
8
+ "AutoModelForCausalLM":"yuan_hf_model.YuanForCausalLM"
9
+ },
10
+ "tokenizer_class":"YuanTokenizer",
11
+ "hidden_act": "silu",
12
+ "hidden_size": 2048,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 8192,
15
+ "max_position_embeddings": 8192,
16
+ "model_type": "yuan",
17
+ "num_attention_heads": 32,
18
+ "num_hidden_layers": 24,
19
+ "rms_norm_eps": 1e-06,
20
+ "dropout": 0.1,
21
+ "tie_word_embeddings": true,
22
+ "torch_dtype": "bfloat16",
23
+ "transformers_version": "4.30.0.dev0",
24
+ "use_cache": true,
25
+ "causal_mask": true,
26
+ "use_flash_attention": false,
27
+ "reset_attention_mask": true,
28
+ "reset_position_ids": true,
29
+ "use_loss_mask": false,
30
+ "eod_token": 77185,
31
+ "sep_token": 77187,
32
+ "eod_token_id": 77185,
33
+ "sep_token_id": 77185,
34
+ "pad_token_id": 77185,
35
+ "bos_token_id": 77185,
36
+ "eos_token_id": 77185,
37
+ "mask_token_id": 77185,
38
+ "vocab_size": 135040
39
+ }
40
+
yuan_hf_model_cpu.py ADDED
@@ -0,0 +1,1141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ inference_hidden_states_memory = torch.empty(bsz, 2, hidden_states.shape[2], dtype=hidden_states.dtype)
273
+ is_first_step = True
274
+ else:
275
+ before_hidden_states = past_key_value[2]
276
+
277
+ if use_cache:
278
+ if is_first_step:
279
+ if q_len >= 2:
280
+ inference_hidden_states_memory = hidden_states[ :, -2:, :]
281
+ else:
282
+ inference_hidden_states_memory[:, :, :] = 0
283
+ inference_hidden_states_memory[:, -1:, :] = hidden_states[:, -1:, :]
284
+ else:
285
+ hidden_states_tmp = before_hidden_states[:, -1:, :]
286
+ inference_hidden_states_memory = copy.deepcopy(torch.cat((hidden_states_tmp, hidden_states), dim=1))
287
+
288
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
289
+ if self.use_shareqk:
290
+ qk_states = self.qk_proj(hidden_states).view(bsz, q_len, self.num_heads*self.head_dim)
291
+ query_key = qk_states.unsqueeze(2) * self.qk_weight + self.qk_bias
292
+ query_states, key_states = torch.unbind(query_key, dim=2)
293
+
294
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
295
+ key_states = key_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
296
+ else:
297
+ hidden_states = self.lf_gate(hidden_states,before_hidden_states)
298
+ query_states = self.q_proj(hidden_states)
299
+ key_states = self.k_proj(hidden_states)
300
+ qk_states = torch.cat([query_states, key_states], dim=-1)
301
+ qk_states = qk_states.view(bsz,q_len,self.num_heads,int(qk_states.shape[-1]//self.num_heads))
302
+ (query_states,key_states) = torch.chunk(qk_states, 2, dim=-1)
303
+ query_states = query_states.transpose(1, 2)
304
+ key_states = key_states.transpose(1, 2)
305
+
306
+
307
+ kv_seq_len = key_states.shape[-2]
308
+ if past_key_value is not None:
309
+ kv_seq_len += past_key_value[0].shape[-2]
310
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
311
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
312
+
313
+ if past_key_value is not None:
314
+ # reuse k, v, self_attention
315
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
316
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
317
+
318
+ past_key_value = (key_states, value_states,inference_hidden_states_memory) if use_cache else None
319
+
320
+ if self.use_flash_attention:
321
+ attn_weights = None
322
+ query_states = query_states.transpose(1, 2)
323
+ key_states = key_states.transpose(1, 2)
324
+ value_states = value_states.transpose(1, 2)
325
+
326
+ batch_size, seqlen_q = query_states.shape[0], query_states.shape[1]
327
+ seqlen_k = key_states.shape[1]
328
+
329
+ q, k, v = [rearrange(x, 'b s ... -> (b s) ...') for x in [query_states, key_states, value_states]]
330
+
331
+ cu_seqlens_q = torch.arange(0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int,
332
+ device=q.device)
333
+
334
+ if self.training:
335
+ assert seqlen_k == seqlen_q
336
+ cu_seqlens_k = cu_seqlens_q
337
+ is_causal = self.causal_mask
338
+ else:
339
+ is_causal = seqlen_q == seqlen_k
340
+ cu_seqlens_k = torch.arange(0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int,
341
+ device=q.device)
342
+ self.dropout=0
343
+
344
+ output = flash_attn_unpadded_func(
345
+ q, k, v, cu_seqlens_q, cu_seqlens_k, seqlen_q, seqlen_k, self.dropout, causal=is_causal
346
+ )
347
+
348
+ attn_output = rearrange(output, '(b s) ... -> b s ...', b=batch_size)
349
+ else:
350
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
351
+
352
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
353
+ raise ValueError(
354
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
355
+ f" {attn_weights.size()}"
356
+ )
357
+ if attention_mask is not None:
358
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
359
+ raise ValueError(
360
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
361
+ )
362
+ attn_weights = attn_weights + attention_mask
363
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
364
+
365
+ # upcast attention to fp32
366
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
367
+ attn_output = torch.matmul(attn_weights, value_states)
368
+
369
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
370
+ raise ValueError(
371
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
372
+ f" {attn_output.size()}"
373
+ )
374
+
375
+ attn_output = attn_output.transpose(1, 2)
376
+
377
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
378
+
379
+ attn_output = self.o_proj(attn_output)
380
+
381
+ if not output_attentions:
382
+ attn_weights = None
383
+ return attn_output, attn_weights, past_key_value
384
+
385
+
386
+ class YuanDecoderLayer(nn.Module):
387
+ def __init__(self, config: YuanConfig):
388
+ super().__init__()
389
+ self.hidden_size = config.hidden_size
390
+ self.self_attn = YuanAttention(config=config)
391
+ self.mlp = YuanMLP(
392
+ hidden_size=self.hidden_size,
393
+ intermediate_size=config.intermediate_size,
394
+ hidden_act=config.hidden_act,
395
+ )
396
+ #Use the same RMSNorm as llama
397
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
398
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
399
+
400
+ def forward(
401
+ self,
402
+ hidden_states: torch.Tensor,
403
+ attention_mask: Optional[torch.Tensor] = None,
404
+ position_ids: Optional[torch.LongTensor] = None,
405
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
406
+ output_attentions: Optional[bool] = False,
407
+ use_cache: Optional[bool] = False,
408
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
409
+ """
410
+ Args:
411
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
412
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
413
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
414
+ output_attentions (`bool`, *optional*):
415
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
416
+ returned tensors for more detail.
417
+ use_cache (`bool`, *optional*):
418
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
419
+ (see `past_key_values`).
420
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
421
+ """
422
+
423
+ residual = hidden_states
424
+ hidden_states = self.input_layernorm(hidden_states)
425
+
426
+ # Self Attention
427
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
428
+ hidden_states=hidden_states,
429
+ attention_mask=attention_mask,
430
+ position_ids=position_ids,
431
+ past_key_value=past_key_value,
432
+ output_attentions=output_attentions,
433
+ use_cache=use_cache,
434
+ )
435
+ hidden_states = residual + hidden_states
436
+
437
+ # Fully Connected
438
+ residual = hidden_states
439
+ hidden_states = self.post_attention_layernorm(hidden_states)
440
+ hidden_states = self.mlp(hidden_states)
441
+ hidden_states = residual + hidden_states
442
+
443
+ outputs = (hidden_states,)
444
+
445
+ if output_attentions:
446
+ outputs += (self_attn_weights,)
447
+
448
+ if use_cache:
449
+ outputs += (present_key_value,)
450
+
451
+ return outputs
452
+
453
+
454
+ YUAN_START_DOCSTRING = r"""
455
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
456
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
457
+ etc.)
458
+
459
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
460
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
461
+ and behavior.
462
+
463
+ Parameters:
464
+ config ([`YuanConfig`]):
465
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
466
+ load the weights associated with the model, only the configuration. Check out the
467
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
468
+ """
469
+
470
+
471
+ @add_start_docstrings(
472
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
473
+ YUAN_START_DOCSTRING,
474
+ )
475
+ class YuanPreTrainedModel(PreTrainedModel):
476
+ config_class = YuanConfig
477
+ base_model_prefix = "model"
478
+ supports_gradient_checkpointing = True
479
+ _no_split_modules = ["YuanDecoderLayer"]
480
+ _skip_keys_device_placement = "past_key_values"
481
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
482
+
483
+ def _init_weights(self, module):
484
+ std = self.config.initializer_range
485
+ if isinstance(module, nn.Linear):
486
+ module.weight.data.normal_(mean=0.0, std=std)
487
+ if module.bias is not None:
488
+ module.bias.data.zero_()
489
+ elif isinstance(module, nn.Embedding):
490
+ module.weight.data.normal_(mean=0.0, std=std)
491
+ if module.padding_idx is not None:
492
+ module.weight.data[module.padding_idx].zero_()
493
+
494
+ def _set_gradient_checkpointing(self, module, value=False):
495
+ if isinstance(module, YuanModel):
496
+ module.gradient_checkpointing = value
497
+
498
+
499
+ YUAN_INPUTS_DOCSTRING = r"""
500
+ Args:
501
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
502
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
503
+ it.
504
+
505
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
506
+ [`PreTrainedTokenizer.__call__`] for details.
507
+
508
+ [What are input IDs?](../glossary#input-ids)
509
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
510
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
511
+
512
+ - 1 for tokens that are **not masked**,
513
+ - 0 for tokens that are **masked**.
514
+
515
+ [What are attention masks?](../glossary#attention-mask)
516
+
517
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
518
+ [`PreTrainedTokenizer.__call__`] for details.
519
+
520
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
521
+ `past_key_values`).
522
+
523
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
524
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
525
+ information on the default strategy.
526
+
527
+ - 1 indicates the head is **not masked**,
528
+ - 0 indicates the head is **masked**.
529
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
530
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
531
+ config.n_positions - 1]`.
532
+
533
+ [What are position IDs?](../glossary#position-ids)
534
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
535
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
536
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
537
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
538
+
539
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
540
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
541
+
542
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
543
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
544
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
545
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
546
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
547
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
548
+ model's internal embedding lookup matrix.
549
+ use_cache (`bool`, *optional*):
550
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
551
+ `past_key_values`).
552
+ output_attentions (`bool`, *optional*):
553
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
554
+ tensors for more detail.
555
+ output_hidden_states (`bool`, *optional*):
556
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
557
+ more detail.
558
+ return_dict (`bool`, *optional*):
559
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
560
+ """
561
+
562
+
563
+ @add_start_docstrings(
564
+ "The bare Yuan Model outputting raw hidden-states without any specific head on top.",
565
+ YUAN_START_DOCSTRING,
566
+ )
567
+ class YuanModel(YuanPreTrainedModel):
568
+ """
569
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`YuanDecoderLayer`]
570
+
571
+ Args:
572
+ config: YuanConfig
573
+ """
574
+
575
+ def __init__(self, config: YuanConfig):
576
+ super().__init__(config)
577
+ self.padding_idx = config.pad_token_id
578
+ self.vocab_size = config.vocab_size
579
+
580
+ #TODO: control it by config
581
+ self.eod_token = config.eod_token
582
+ self.reset_attention_mask = config.reset_attention_mask
583
+ self.reset_position_ids = config.reset_position_ids
584
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
585
+ self.layers = nn.ModuleList([YuanDecoderLayer(config) for _ in range(config.num_hidden_layers)])
586
+ #Use the same RMSNorm as llama
587
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
588
+ self.gradient_checkpointing = False
589
+ # Initialize weights and apply final processing
590
+ self.post_init()
591
+
592
+ def get_input_embeddings(self):
593
+ return self.embed_tokens
594
+
595
+ def set_input_embeddings(self, value):
596
+ self.embed_tokens = value
597
+
598
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
599
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
600
+ # create causal mask
601
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
602
+ combined_attention_mask = None
603
+ if input_shape[-1] > 1:
604
+ combined_attention_mask = _make_causal_mask(
605
+ input_shape,
606
+ inputs_embeds.dtype,
607
+ device=inputs_embeds.device,
608
+ past_key_values_length=past_key_values_length,
609
+ )
610
+
611
+ if attention_mask is not None:
612
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
613
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
614
+ inputs_embeds.device
615
+ )
616
+ combined_attention_mask = (
617
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
618
+ )
619
+
620
+ return combined_attention_mask
621
+
622
+ def _prepare_decoder_attention_mask_training(self, input_id, inputs_embeds, eod_token, reset_mask_flag ,reset_attention_mask=True, reset_position_ids=True):
623
+
624
+ micro_batch_size, seq_length = input_id.size()
625
+
626
+ attention_mask = torch.tril(torch.ones(
627
+ (micro_batch_size, seq_length, seq_length), device=inputs_embeds.device)).view(
628
+ micro_batch_size, 1, seq_length, seq_length)
629
+
630
+ position_ids = torch.arange(seq_length, dtype=torch.long,
631
+ device=inputs_embeds.device)
632
+ position_ids = position_ids.unsqueeze(0).expand_as(input_id)
633
+
634
+ if reset_position_ids:
635
+ position_ids = position_ids.clone()
636
+
637
+ if reset_position_ids or reset_attention_mask:
638
+ # Loop through the batches:
639
+ for b in range(micro_batch_size):
640
+
641
+ # Find indecies where EOD token is.
642
+ eod_index = position_ids[b, input_id[b] == eod_token]
643
+
644
+ # Detach indecies from positions if going to modify positions.
645
+ if reset_position_ids:
646
+ eod_index = eod_index.clone()
647
+ # Loop through EOD indecies:
648
+ prev_index = 0
649
+ for j in range(eod_index.size()[0]):
650
+ i = eod_index[j]
651
+ # Mask attention loss.
652
+ if reset_attention_mask:
653
+ attention_mask[b, 0, (i + 1):, :(i + 1)] = 0
654
+ # Reset positions.
655
+ if reset_position_ids:
656
+ position_ids[b, (i + 1):] -= (i + 1 - prev_index)
657
+ prev_index = i + 1
658
+
659
+ inverted_mask = 1 - attention_mask
660
+ output_attn_mask = inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(inputs_embeds.dtype).min)
661
+ if reset_mask_flag:
662
+ output_attn_mask = output_attn_mask[:,:,-1:,:]
663
+ return output_attn_mask, position_ids
664
+
665
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
666
+ def forward(
667
+ self,
668
+ input_ids: torch.LongTensor = None,
669
+ attention_mask: Optional[torch.Tensor] = None,
670
+ position_ids: Optional[torch.LongTensor] = None,
671
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
672
+ inputs_embeds: Optional[torch.FloatTensor] = None,
673
+ use_cache: Optional[bool] = None,
674
+ output_attentions: Optional[bool] = None,
675
+ output_hidden_states: Optional[bool] = None,
676
+ return_dict: Optional[bool] = None,
677
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
678
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
679
+ output_hidden_states = (
680
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
681
+ )
682
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
683
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
684
+ input_ids1 = copy.deepcopy(input_ids)
685
+ reset_mask_flag = False
686
+ if past_key_values:
687
+ input_ids = input_ids[:, -1:]
688
+ if use_cache:
689
+ reset_mask_flag = True
690
+ # retrieve input_ids and inputs_embeds
691
+ if input_ids is not None and inputs_embeds is not None:
692
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
693
+ elif input_ids is not None:
694
+ batch_size, seq_length = input_ids.shape
695
+ elif inputs_embeds is not None:
696
+ batch_size, seq_length, _ = inputs_embeds.shape
697
+ else:
698
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
699
+
700
+ seq_length_with_past = seq_length
701
+ past_key_values_length = 0
702
+
703
+ if past_key_values is not None:
704
+ past_key_values_length = past_key_values[0][0].shape[2]
705
+ seq_length_with_past = seq_length_with_past + past_key_values_length
706
+
707
+ if position_ids is None:
708
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
709
+ position_ids = torch.arange(
710
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
711
+ )
712
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
713
+ else:
714
+ position_ids = position_ids.view(-1, seq_length).long()
715
+ if inputs_embeds is None:
716
+ inputs_embeds = self.embed_tokens(input_ids)
717
+ if self.training or self.reset_position_ids:
718
+ 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)
719
+
720
+ else:
721
+ if attention_mask is None:
722
+ attention_mask = torch.ones(
723
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
724
+ )
725
+ attention_mask = self._prepare_decoder_attention_mask(
726
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
727
+ )
728
+
729
+ hidden_states = inputs_embeds
730
+
731
+ if self.gradient_checkpointing and self.training:
732
+ if use_cache:
733
+ logger.warning_once(
734
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
735
+ )
736
+ use_cache = False
737
+
738
+ # decoder layers
739
+ all_hidden_states = () if output_hidden_states else None
740
+ all_self_attns = () if output_attentions else None
741
+ next_decoder_cache = () if use_cache else None
742
+
743
+ for idx, decoder_layer in enumerate(self.layers):
744
+ if output_hidden_states:
745
+ all_hidden_states += (hidden_states,)
746
+
747
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
748
+
749
+ if self.gradient_checkpointing and self.training:
750
+
751
+ def create_custom_forward(module):
752
+ def custom_forward(*inputs):
753
+ # None for past_key_value
754
+ return module(*inputs, output_attentions, None)
755
+
756
+ return custom_forward
757
+
758
+ layer_outputs = torch.utils.checkpoint.checkpoint(
759
+ create_custom_forward(decoder_layer),
760
+ hidden_states,
761
+ attention_mask,
762
+ position_ids,
763
+ None,
764
+ )
765
+ else:
766
+ layer_outputs = decoder_layer(
767
+ hidden_states,
768
+ attention_mask=attention_mask,
769
+ position_ids=position_ids,
770
+ past_key_value=past_key_value,
771
+ output_attentions=output_attentions,
772
+ use_cache=use_cache,
773
+ )
774
+
775
+ hidden_states = layer_outputs[0]
776
+
777
+ if use_cache:
778
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
779
+
780
+ if output_attentions:
781
+ all_self_attns += (layer_outputs[1],)
782
+ hidden_states = self.norm(hidden_states)
783
+
784
+ # add hidden states from the last decoder layer
785
+ if output_hidden_states:
786
+ all_hidden_states += (hidden_states,)
787
+ next_cache = next_decoder_cache if use_cache else None
788
+ if not return_dict:
789
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
790
+ return BaseModelOutputWithPast(
791
+ last_hidden_state=hidden_states,
792
+ past_key_values=next_cache,
793
+ hidden_states=all_hidden_states,
794
+ attentions=all_self_attns,
795
+ )
796
+
797
+
798
+ class YuanForCausalLM(YuanPreTrainedModel):
799
+ def __init__(self, config):
800
+ super().__init__(config)
801
+ self.eod_token = config.eod_token
802
+ self.sep_token = config.sep_token
803
+ self.use_loss_mask = config.use_loss_mask
804
+ self.model = YuanModel(config)
805
+
806
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
807
+
808
+ # Initialize weights and apply final processing
809
+ self.post_init()
810
+
811
+ def get_input_embeddings(self):
812
+ return self.model.embed_tokens
813
+
814
+ def set_input_embeddings(self, value):
815
+ self.model.embed_tokens = value
816
+
817
+ def get_output_embeddings(self):
818
+ return self.lm_head
819
+
820
+ def set_output_embeddings(self, new_embeddings):
821
+ self.lm_head = new_embeddings
822
+
823
+ def set_decoder(self, decoder):
824
+ self.model = decoder
825
+
826
+ def get_decoder(self):
827
+ return self.model
828
+
829
+ def get_loss_mask(self, input_ids, labels, eod_token, sep_token):
830
+ micro_batch_size, seq_length = input_ids.size()
831
+ loss_mask = torch.ones(input_ids.size(), dtype=torch.float, device=input_ids.device)
832
+
833
+ position_ids = torch.arange(seq_length, dtype=torch.long,
834
+ device=input_ids.device)
835
+ position_ids = position_ids.unsqueeze(0).expand_as(input_ids)
836
+
837
+
838
+ """modify loss_mask to only calculate the loss of the answer (separated with [SEP])"""
839
+
840
+ for b in range(micro_batch_size):
841
+ eod_indexs = position_ids[b, input_ids[b] == eod_token]
842
+ sep_indexs = position_ids[b, input_ids[b] == sep_token]
843
+
844
+ if len(eod_indexs) == 0 or len(sep_indexs) == 0:
845
+ loss_mask[b] = 1.0
846
+ else:
847
+ if eod_indexs[0] > sep_indexs[0]:
848
+ loss_mask[b, 0:sep_indexs[0]] = 0
849
+
850
+ if len(eod_indexs) == len(sep_indexs):
851
+ for ii, eod_index in enumerate(eod_indexs):
852
+ start_index = eod_index
853
+ if ii == (len(sep_indexs) - 1):
854
+ stop_index = seq_length
855
+ else:
856
+ stop_index = sep_indexs[ii + 1]
857
+ loss_mask[b, start_index:stop_index] = 0.0
858
+ else:
859
+ if len(eod_indexs) > len(sep_indexs):
860
+ loss_mask[b,:] = 1.0
861
+ else:
862
+ for ii, eod_index in enumerate(eod_indexs):
863
+ start_index = eod_index
864
+ stop_index = sep_indexs[ii + 1]
865
+
866
+ loss_mask[b, start_index:stop_index] = 0.0
867
+
868
+ elif eod_indexs[0] < sep_indexs[0]:
869
+
870
+ if len(eod_indexs) == len(sep_indexs):
871
+ for ii, eod_index in enumerate(eod_indexs):
872
+ start_index = eod_index
873
+ stop_index = sep_indexs[ii]
874
+ loss_mask[b, start_index:stop_index] = 0.0
875
+
876
+ else:
877
+ if len(eod_indexs) < len(sep_indexs):
878
+ loss_mask[b,:] = 1.0
879
+ else:
880
+ for ii, eod_index in enumerate(eod_indexs):
881
+ start_index = eod_index
882
+ if ii >= len(sep_indexs):
883
+ stop_index = seq_length
884
+ else:
885
+ stop_index = sep_indexs[ii]
886
+ loss_mask[b, start_index:stop_index] = 0.0
887
+
888
+ loss_mask[input_ids == eod_token] = 1.0
889
+ return loss_mask
890
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
891
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
892
+ def forward(
893
+ self,
894
+ input_ids: torch.LongTensor = None,
895
+ attention_mask: Optional[torch.Tensor] = None,
896
+ position_ids: Optional[torch.LongTensor] = None,
897
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
898
+ inputs_embeds: Optional[torch.FloatTensor] = None,
899
+ labels: Optional[torch.LongTensor] = None,
900
+ use_cache: Optional[bool] = None,
901
+ output_attentions: Optional[bool] = None,
902
+ output_hidden_states: Optional[bool] = None,
903
+ return_dict: Optional[bool] = None,
904
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
905
+ r"""
906
+ Args:
907
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
908
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
909
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
910
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
911
+
912
+ Returns:
913
+
914
+ Example:
915
+
916
+ ```python
917
+ >>> from transformers import AutoTokenizer, YuanForCausalLM
918
+
919
+ >>> model = YuanForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
920
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
921
+
922
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
923
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
924
+
925
+ >>> # Generate
926
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
927
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
928
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
929
+ ```"""
930
+
931
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
932
+ output_hidden_states = (
933
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
934
+ )
935
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
936
+ outputs = self.model(
937
+ input_ids=input_ids,
938
+ attention_mask=attention_mask,
939
+ position_ids=position_ids,
940
+ past_key_values=past_key_values,
941
+ inputs_embeds=inputs_embeds,
942
+ use_cache=use_cache,
943
+ output_attentions=output_attentions,
944
+ output_hidden_states=output_hidden_states,
945
+ return_dict=return_dict,
946
+ )
947
+
948
+ hidden_states = outputs[0]
949
+ logits = self.lm_head(hidden_states)
950
+ loss = None
951
+ if labels is not None:
952
+ if self.use_loss_mask:
953
+ loss_mask = self.get_loss_mask(input_ids, labels, self.eod_token, self.sep_token)
954
+ # Shift so that tokens < n predict n
955
+ shift_logits = logits[..., :-1, :].contiguous()
956
+ shift_labels = labels[..., 1:].contiguous()
957
+ # Flatten the tokens
958
+ if self.use_loss_mask:
959
+ loss_fct = CrossEntropyLoss(reduction='none')
960
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
961
+ shift_labels = shift_labels.view(-1)
962
+ # Enable model parallelism
963
+ shift_labels = shift_labels.to(shift_logits.device)
964
+ loss = loss_fct(shift_logits, shift_labels)
965
+ loss = torch.sum(loss * loss_mask) / loss_mask.sum()
966
+ else:
967
+ loss_fct = CrossEntropyLoss()
968
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
969
+ shift_labels = shift_labels.view(-1)
970
+ # Enable model parallelism
971
+ shift_labels = shift_labels.to(shift_logits.device)
972
+ loss = loss_fct(shift_logits, shift_labels)
973
+ if not return_dict:
974
+ output = (logits,) + outputs[1:]
975
+ return (loss,) + output if loss is not None else output
976
+
977
+ return CausalLMOutputWithPast(
978
+ loss=loss,
979
+ logits=logits,
980
+ past_key_values=outputs.past_key_values,
981
+ hidden_states=hidden_states,
982
+ attentions=outputs.attentions,
983
+ )
984
+
985
+ def prepare_inputs_for_generation(
986
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
987
+ ):
988
+
989
+ position_ids = kwargs.get("position_ids", None)
990
+ if attention_mask is not None and position_ids is None:
991
+ # create position_ids on the fly for batch generation
992
+ position_ids = attention_mask.long().cumsum(-1) - 1
993
+ position_ids.masked_fill_(attention_mask == 0, 1)
994
+ if past_key_values:
995
+ position_ids = position_ids[:, -1].unsqueeze(-1)
996
+
997
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
998
+ if inputs_embeds is not None and past_key_values is None:
999
+ model_inputs = {"inputs_embeds": inputs_embeds}
1000
+ else:
1001
+ model_inputs = {"input_ids": input_ids}
1002
+
1003
+ model_inputs.update(
1004
+ {
1005
+ "position_ids": position_ids,
1006
+ "past_key_values": past_key_values,
1007
+ "use_cache": kwargs.get("use_cache"),
1008
+ "attention_mask": attention_mask,
1009
+ }
1010
+ )
1011
+ return model_inputs
1012
+
1013
+ @staticmethod
1014
+ def _reorder_cache(past_key_values, beam_idx):
1015
+ reordered_past = ()
1016
+ for layer_past in past_key_values:
1017
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1018
+ return reordered_past
1019
+
1020
+
1021
+ @add_start_docstrings(
1022
+ """
1023
+ The Yuan Model transformer with a sequence classification head on top (linear layer).
1024
+
1025
+ [`YuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1026
+ (e.g. GPT-2) do.
1027
+
1028
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1029
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1030
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1031
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1032
+ each row of the batch).
1033
+ """,
1034
+ YUAN_START_DOCSTRING,
1035
+ )
1036
+ class YuanForSequenceClassification(YuanPreTrainedModel):
1037
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1038
+
1039
+ def __init__(self, config):
1040
+ super().__init__(config)
1041
+ self.num_labels = config.num_labels
1042
+ self.model = YuanModel(config)
1043
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1044
+
1045
+ # Initialize weights and apply final processing
1046
+ self.post_init()
1047
+
1048
+ def get_input_embeddings(self):
1049
+ return self.model.embed_tokens
1050
+
1051
+ def set_input_embeddings(self, value):
1052
+ self.model.embed_tokens = value
1053
+
1054
+ @add_start_docstrings_to_model_forward(YUAN_INPUTS_DOCSTRING)
1055
+ def forward(
1056
+ self,
1057
+ input_ids: torch.LongTensor = None,
1058
+ attention_mask: Optional[torch.Tensor] = None,
1059
+ position_ids: Optional[torch.LongTensor] = None,
1060
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1061
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1062
+ labels: Optional[torch.LongTensor] = None,
1063
+ use_cache: Optional[bool] = None,
1064
+ output_attentions: Optional[bool] = None,
1065
+ output_hidden_states: Optional[bool] = None,
1066
+ return_dict: Optional[bool] = None,
1067
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1068
+ r"""
1069
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1070
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1071
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1072
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1073
+ """
1074
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1075
+ transformer_outputs = self.model(
1076
+ input_ids,
1077
+ attention_mask=attention_mask,
1078
+ position_ids=position_ids,
1079
+ past_key_values=past_key_values,
1080
+ inputs_embeds=inputs_embeds,
1081
+ use_cache=use_cache,
1082
+ output_attentions=output_attentions,
1083
+ output_hidden_states=output_hidden_states,
1084
+ return_dict=return_dict,
1085
+ )
1086
+ hidden_states = transformer_outputs[0]
1087
+ logits = self.score(hidden_states)
1088
+
1089
+ if input_ids is not None:
1090
+ batch_size = input_ids.shape[0]
1091
+ else:
1092
+ batch_size = inputs_embeds.shape[0]
1093
+
1094
+ if self.config.pad_token_id is None and batch_size != 1:
1095
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1096
+ if self.config.pad_token_id is None:
1097
+ sequence_lengths = -1
1098
+ else:
1099
+ if input_ids is not None:
1100
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1101
+ else:
1102
+ sequence_lengths = -1
1103
+
1104
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1105
+
1106
+ loss = None
1107
+ if labels is not None:
1108
+ labels = labels.to(logits.device)
1109
+ if self.config.problem_type is None:
1110
+ if self.num_labels == 1:
1111
+ self.config.problem_type = "regression"
1112
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1113
+ self.config.problem_type = "single_label_classification"
1114
+ else:
1115
+ self.config.problem_type = "multi_label_classification"
1116
+
1117
+ if self.config.problem_type == "regression":
1118
+ loss_fct = MSELoss()
1119
+ if self.num_labels == 1:
1120
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1121
+ else:
1122
+ loss = loss_fct(pooled_logits, labels)
1123
+ elif self.config.problem_type == "single_label_classification":
1124
+ loss_fct = CrossEntropyLoss()
1125
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1126
+ elif self.config.problem_type == "multi_label_classification":
1127
+ loss_fct = BCEWithLogitsLoss()
1128
+ loss = loss_fct(pooled_logits, labels)
1129
+ if not return_dict:
1130
+ output = (pooled_logits,) + transformer_outputs[1:]
1131
+ return ((loss,) + output) if loss is not None else output
1132
+
1133
+ return SequenceClassifierOutputWithPast(
1134
+ loss=loss,
1135
+ logits=pooled_logits,
1136
+ past_key_values=transformer_outputs.past_key_values,
1137
+ hidden_states=transformer_outputs.hidden_states,
1138
+ attentions=transformer_outputs.attentions,
1139
+ )
1140
+
1141
+