skyipeng commited on
Commit
654bb88
·
verified ·
1 Parent(s): 0d73d3b

Upload modeling_skywork_lm2.py

Browse files
Files changed (1) hide show
  1. modeling_skywork_lm2.py +1403 -0
modeling_skywork_lm2.py ADDED
@@ -0,0 +1,1403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) The Skywork team and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # This code is based on transformers/src/transformers/models/llama/modeling_llama.py
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ PyTorch SkyworkLM2 model."""
17
+ import math
18
+ import queue
19
+ import threading
20
+ import warnings
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ SequenceClassifierOutputWithPast)
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (add_start_docstrings,
35
+ add_start_docstrings_to_model_forward, logging,
36
+ replace_return_docstrings)
37
+
38
+ try:
39
+ from transformers.generation.streamers import BaseStreamer
40
+ except:
41
+ BaseStreamer = None
42
+
43
+ from .configuration_skywork_lm2 import SkyworkLM2Config
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CONFIG_FOR_DOC = 'SkyworkLM2Config'
48
+
49
+ flash_attn_func, flash_attn_varlen_func = None, None
50
+ pad_input, index_first_axis, unpad_input = None, None, None
51
+ try:
52
+ from flash_attn import flash_attn_func as _flash_attn_func
53
+ from flash_attn import flash_attn_varlen_func as _flash_attn_varlen_func
54
+ from flash_attn.bert_padding import index_first_axis as _index_first_axis
55
+ from flash_attn.bert_padding import pad_input as _pad_input
56
+ from flash_attn.bert_padding import unpad_input as _unpad_input
57
+
58
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
59
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
60
+ has_flash_attn = True
61
+ except:
62
+ has_flash_attn = False
63
+
64
+
65
+ def _import_flash_attn():
66
+ global flash_attn_func, flash_attn_varlen_func
67
+ global pad_input, index_first_axis, unpad_input
68
+ try:
69
+ from flash_attn import flash_attn_func as _flash_attn_func
70
+ from flash_attn import \
71
+ flash_attn_varlen_func as _flash_attn_varlen_func
72
+ from flash_attn.bert_padding import \
73
+ index_first_axis as _index_first_axis
74
+ from flash_attn.bert_padding import pad_input as _pad_input
75
+ from flash_attn.bert_padding import unpad_input as _unpad_input
76
+ flash_attn_func, flash_attn_varlen_func = _flash_attn_func, _flash_attn_varlen_func
77
+ pad_input, index_first_axis, unpad_input = _pad_input, _index_first_axis, _unpad_input
78
+ except ImportError:
79
+ raise ImportError('flash_attn is not installed.')
80
+
81
+
82
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
83
+ def _get_unpad_data(attention_mask):
84
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
85
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
86
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
87
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
88
+ return (
89
+ indices,
90
+ cu_seqlens,
91
+ max_seqlen_in_batch,
92
+ )
93
+
94
+
95
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
96
+ def _make_causal_mask(
97
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
98
+ ):
99
+ """
100
+ Make causal mask used for bi-directional self-attention.
101
+ """
102
+ bsz, tgt_len = input_ids_shape
103
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
104
+ mask_cond = torch.arange(mask.size(-1), device=device)
105
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
106
+ mask = mask.to(dtype)
107
+
108
+ if past_key_values_length > 0:
109
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
110
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
111
+
112
+
113
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
114
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
115
+ """
116
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
117
+ """
118
+ bsz, src_len = mask.size()
119
+ tgt_len = tgt_len if tgt_len is not None else src_len
120
+
121
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
122
+
123
+ inverted_mask = 1.0 - expanded_mask
124
+
125
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
126
+
127
+
128
+ # Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->SkyworkLM2
129
+ class SkyworkLM2RMSNorm(nn.Module):
130
+ def __init__(self, hidden_size, eps=1e-6):
131
+ """
132
+ SkyworkLM2RMSNorm is equivalent to T5LayerNorm
133
+ """
134
+ super().__init__()
135
+ self.weight = nn.Parameter(torch.ones(hidden_size))
136
+ self.variance_epsilon = eps
137
+
138
+ def forward(self, hidden_states):
139
+ input_dtype = hidden_states.dtype
140
+ hidden_states = hidden_states.to(torch.float32)
141
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
142
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
143
+ return self.weight * hidden_states.to(input_dtype)
144
+
145
+
146
+ # Copied from transformers.model.llama.modeling_llama.LlamaRotaryEmbedding with Llama->SkyworkLM2
147
+ class SkyworkLM2RotaryEmbedding(nn.Module):
148
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
149
+ super().__init__()
150
+
151
+ self.dim = dim
152
+ self.max_position_embeddings = max_position_embeddings
153
+ self.base = base
154
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
155
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
156
+
157
+ # Build here to make `torch.jit.trace` work.
158
+ self._set_cos_sin_cache(
159
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
160
+ )
161
+
162
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
163
+ self.max_seq_len_cached = seq_len
164
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
165
+
166
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
167
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
168
+ emb = torch.cat((freqs, freqs), dim=-1)
169
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
170
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
171
+
172
+ def forward(self, x, seq_len=None):
173
+ # x: [bs, num_attention_heads, seq_len, head_size]
174
+ if seq_len > self.max_seq_len_cached:
175
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=torch.float32)
176
+
177
+ return (
178
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
179
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
180
+ )
181
+
182
+
183
+ # Copied from transformers.model.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->SkyworkLM2
184
+ class SkyworkLM2LinearScalingRotaryEmbedding(SkyworkLM2RotaryEmbedding):
185
+
186
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
187
+ self.scaling_factor = scaling_factor
188
+ super().__init__(dim, max_position_embeddings, base, device)
189
+
190
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
191
+ self.max_seq_len_cached = seq_len
192
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
193
+ t = t / self.scaling_factor
194
+
195
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
196
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
197
+ emb = torch.cat((freqs, freqs), dim=-1)
198
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
199
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
200
+
201
+
202
+ # Copied from transformers.model.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->SkyworkLM2
203
+ class SkyworkLM2DynamicNTKScalingRotaryEmbedding(SkyworkLM2RotaryEmbedding):
204
+
205
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
206
+ self.scaling_factor = scaling_factor
207
+ super().__init__(dim, max_position_embeddings, base, device)
208
+
209
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
210
+ self.max_seq_len_cached = seq_len
211
+
212
+ if seq_len > self.max_position_embeddings:
213
+ base = self.base * (
214
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
215
+ ) ** (self.dim / (self.dim - 2))
216
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
217
+ self.register_buffer('inv_freq', inv_freq, persistent=False)
218
+
219
+ t = torch.arange(self.max_seq_len_cached, device=device).to(dtype=self.inv_freq.dtype)
220
+
221
+ freqs = torch.einsum('i,j->ij', t, self.inv_freq)
222
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
223
+ emb = torch.cat((freqs, freqs), dim=-1)
224
+ self.register_buffer('cos_cached', emb.cos().to(dtype), persistent=False)
225
+ self.register_buffer('sin_cached', emb.sin().to(dtype), persistent=False)
226
+
227
+
228
+ # Copied from transformers.model.llama.modeling_llama.rotate_half
229
+ def rotate_half(x):
230
+ """Rotates half the hidden dims of the input."""
231
+ x1 = x[..., : x.shape[-1] // 2]
232
+ x2 = x[..., x.shape[-1] // 2 :]
233
+ return torch.cat((-x2, x1), dim=-1)
234
+
235
+
236
+ # Copied from transformers.model.llama.modeling_llama.apply_rotary_pos_emb
237
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
238
+ """Applies Rotary Position Embedding to the query and key tensors."""
239
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
240
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
241
+ q_embed = (q * cos) + (rotate_half(q) * sin)
242
+ k_embed = (k * cos) + (rotate_half(k) * sin)
243
+ return q_embed, k_embed
244
+
245
+
246
+ class SkyworkLM2MLP(nn.Module):
247
+ def __init__(self, config):
248
+ super().__init__()
249
+ self.config = config
250
+ self.hidden_size = config.hidden_size
251
+ self.intermediate_size = config.intermediate_size
252
+ self.w1 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
253
+ self.w3 = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
254
+ self.w2 = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
255
+ self.act_fn = ACT2FN[config.hidden_act]
256
+
257
+ def forward(self, x):
258
+ down_proj = self.w2(self.act_fn(self.w1(x)) * self.w3(x))
259
+
260
+ return down_proj
261
+
262
+
263
+ # Copied from transformers.model.llama.modeling_llama.repeat_kv
264
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
265
+ """
266
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
267
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
268
+ """
269
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
270
+ if n_rep == 1:
271
+ return hidden_states
272
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
273
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
274
+
275
+
276
+ # Modified from transformers.model.llama.modeling_llama.LlamaAttention
277
+ class SkyworkLM2Attention(nn.Module):
278
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
279
+
280
+ def __init__(self, config: SkyworkLM2Config):
281
+ super().__init__()
282
+ self.config = config
283
+ self.hidden_size = config.hidden_size
284
+ self.num_heads = config.num_attention_heads
285
+ self.head_dim = self.hidden_size // self.num_heads
286
+ self.num_key_value_heads = config.num_key_value_heads
287
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
288
+ self.max_position_embeddings = config.max_position_embeddings
289
+ self.is_causal = True
290
+
291
+ if (self.head_dim * self.num_heads) != self.hidden_size:
292
+ raise ValueError(
293
+ f'hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}'
294
+ f' and `num_heads`: {self.num_heads}).'
295
+ )
296
+
297
+ self.wqkv = nn.Linear(
298
+ self.hidden_size,
299
+ (self.num_heads + 2 * self.num_key_value_heads) * self.head_dim,
300
+ bias=config.bias,
301
+ )
302
+
303
+ self.wo = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.bias)
304
+ self._init_rope()
305
+
306
+ def _init_rope(self):
307
+ if self.config.rope_scaling is None:
308
+ self.rotary_emb = SkyworkLM2RotaryEmbedding(
309
+ self.head_dim,
310
+ max_position_embeddings=self.max_position_embeddings,
311
+ base=self.config.rope_theta,
312
+ )
313
+ else:
314
+ scaling_type = self.config.rope_scaling['type']
315
+ scaling_factor = self.config.rope_scaling['factor']
316
+ if scaling_type == 'dynamic':
317
+ self.rotary_emb = SkyworkLM2DynamicNTKScalingRotaryEmbedding(
318
+ self.head_dim,
319
+ max_position_embeddings=self.max_position_embeddings,
320
+ base=self.config.rope_theta,
321
+ scaling_factor=scaling_factor,
322
+ )
323
+ elif scaling_type == 'linear':
324
+ self.rotary_emb = SkyworkLM2LinearScalingRotaryEmbedding(
325
+ self.head_dim,
326
+ max_position_embeddings=self.max_position_embeddings,
327
+ base=self.config.rope_theta,
328
+ scaling_factor=scaling_factor,
329
+ )
330
+ else:
331
+ raise ValueError("Currently we only support rotary embedding's type being 'dynamic' or 'linear'.")
332
+ return self.rotary_emb
333
+
334
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
335
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
336
+
337
+ def forward(
338
+ self,
339
+ hidden_states: torch.Tensor,
340
+ attention_mask: Optional[torch.Tensor] = None,
341
+ position_ids: Optional[torch.LongTensor] = None,
342
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
343
+ output_attentions: bool = False,
344
+ use_cache: bool = False,
345
+ **kwargs,
346
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
347
+ if 'padding_mask' in kwargs:
348
+ warnings.warn(
349
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
350
+ 'Please make sure use `attention_mask` instead.`'
351
+ )
352
+
353
+ bsz, q_len, _ = hidden_states.size()
354
+
355
+ qkv_states = self.wqkv(hidden_states)
356
+
357
+ qkv_states = rearrange(
358
+ qkv_states,
359
+ 'b q (h gs d) -> b q h gs d',
360
+ gs=2 + self.num_key_value_groups,
361
+ d=self.head_dim,
362
+ )
363
+
364
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
365
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
366
+ key_states = qkv_states[..., -2, :]
367
+ value_states = qkv_states[..., -1, :]
368
+
369
+ query_states = query_states.transpose(1, 2)
370
+ key_states = key_states.transpose(1, 2)
371
+ value_states = value_states.transpose(1, 2)
372
+
373
+ kv_seq_len = key_states.shape[-2]
374
+ if past_key_value is not None:
375
+ kv_seq_len += past_key_value[0].shape[-2]
376
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
377
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
378
+
379
+ if past_key_value is not None:
380
+ # reuse k, v, self_attention
381
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
382
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
383
+
384
+ past_key_value = (key_states, value_states) if use_cache else None
385
+
386
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
387
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
388
+
389
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
390
+
391
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
392
+ raise ValueError(
393
+ f'Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is'
394
+ f' {attn_weights.size()}'
395
+ )
396
+
397
+ if attention_mask is not None:
398
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
399
+ raise ValueError(
400
+ f'Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}'
401
+ )
402
+ attn_weights = attn_weights + attention_mask
403
+
404
+ # upcast attention to fp32
405
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
406
+ attn_output = torch.matmul(attn_weights, value_states)
407
+
408
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
409
+ raise ValueError(
410
+ f'`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is'
411
+ f' {attn_output.size()}'
412
+ )
413
+
414
+ attn_output = attn_output.transpose(1, 2).contiguous()
415
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
416
+
417
+ attn_output = self.wo(attn_output)
418
+
419
+ if not output_attentions:
420
+ attn_weights = None
421
+
422
+ return attn_output, attn_weights, past_key_value
423
+
424
+
425
+ # Modified from transformers.model.llama.modeling_llama.SkyworkLM2FlashAttention2
426
+ class SkyworkLM2FlashAttention2(SkyworkLM2Attention):
427
+
428
+ def forward(
429
+ self,
430
+ hidden_states: torch.Tensor,
431
+ attention_mask: Optional[torch.LongTensor] = None,
432
+ position_ids: Optional[torch.LongTensor] = None,
433
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
434
+ output_attentions: bool = False,
435
+ use_cache: bool = False,
436
+ **kwargs,
437
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
438
+ if 'padding_mask' in kwargs:
439
+ warnings.warn(
440
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
441
+ 'Please make sure use `attention_mask` instead.`'
442
+ )
443
+
444
+ # overwrite attention_mask with padding_mask
445
+ attention_mask = kwargs.pop('padding_mask')
446
+
447
+ output_attentions = False
448
+
449
+ bsz, q_len, _ = hidden_states.size()
450
+
451
+ qkv_states = self.wqkv(hidden_states)
452
+
453
+ qkv_states = rearrange(
454
+ qkv_states,
455
+ 'b q (h gs d) -> b q h gs d',
456
+ gs=2 + self.num_key_value_groups,
457
+ d=self.head_dim,
458
+ )
459
+
460
+ query_states = qkv_states[..., : self.num_key_value_groups, :]
461
+ query_states = rearrange(query_states, 'b q h gs d -> b q (h gs) d')
462
+ key_states = qkv_states[..., -2, :]
463
+ value_states = qkv_states[..., -1, :]
464
+
465
+ query_states = query_states.transpose(1, 2)
466
+ key_states = key_states.transpose(1, 2)
467
+ value_states = value_states.transpose(1, 2)
468
+
469
+ kv_seq_len = key_states.shape[-2]
470
+ if past_key_value is not None:
471
+ kv_seq_len += past_key_value[0].shape[-2]
472
+
473
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
474
+
475
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
476
+
477
+ if past_key_value is not None:
478
+ # reuse k, v, self_attention
479
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
480
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
481
+
482
+ past_key_value = (key_states, value_states) if use_cache else None
483
+
484
+ query_states = query_states.transpose(1, 2)
485
+ key_states = key_states.transpose(1, 2)
486
+ value_states = value_states.transpose(1, 2)
487
+
488
+ attn_output = self._flash_attention_forward(
489
+ query_states, key_states, value_states, attention_mask, q_len
490
+ )
491
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
492
+ attn_output = self.wo(attn_output)
493
+
494
+ if not output_attentions:
495
+ attn_weights = None
496
+
497
+ return attn_output, attn_weights, past_key_value
498
+
499
+ def _flash_attention_forward(
500
+ self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
501
+ ):
502
+ """
503
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
504
+ first unpad the input, then computes the attention scores and pad the final attention scores.
505
+
506
+ Args:
507
+ query_states (`torch.Tensor`):
508
+ Input query states to be passed to Flash Attention API
509
+ key_states (`torch.Tensor`):
510
+ Input key states to be passed to Flash Attention API
511
+ value_states (`torch.Tensor`):
512
+ Input value states to be passed to Flash Attention API
513
+ attention_mask (`torch.Tensor`):
514
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
515
+ position of padding tokens and 1 for the position of non-padding tokens.
516
+ dropout (`int`, *optional*):
517
+ Attention dropout
518
+ softmax_scale (`float`, *optional*):
519
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
520
+ """
521
+ # Contains at least one padding token in the sequence
522
+ causal = self.is_causal and query_length != 1
523
+ if attention_mask is not None:
524
+ batch_size = query_states.shape[0]
525
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._unpad_input(
526
+ query_states, key_states, value_states, attention_mask, query_length
527
+ )
528
+
529
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
530
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
531
+
532
+ attn_output_unpad = flash_attn_varlen_func(
533
+ query_states,
534
+ key_states,
535
+ value_states,
536
+ cu_seqlens_q=cu_seqlens_q,
537
+ cu_seqlens_k=cu_seqlens_k,
538
+ max_seqlen_q=max_seqlen_in_batch_q,
539
+ max_seqlen_k=max_seqlen_in_batch_k,
540
+ dropout_p=dropout,
541
+ softmax_scale=softmax_scale,
542
+ causal=causal,
543
+ )
544
+
545
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
546
+ else:
547
+ attn_output = flash_attn_func(
548
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
549
+ )
550
+
551
+ return attn_output
552
+
553
+ def _unpad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
554
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
555
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
556
+
557
+ key_layer = index_first_axis(
558
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
559
+ )
560
+ value_layer = index_first_axis(
561
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
562
+ )
563
+
564
+ if query_length == kv_seq_len:
565
+ query_layer = index_first_axis(
566
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
567
+ )
568
+ cu_seqlens_q = cu_seqlens_k
569
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
570
+ indices_q = indices_k
571
+ elif query_length == 1:
572
+ max_seqlen_in_batch_q = 1
573
+ cu_seqlens_q = torch.arange(
574
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
575
+ ) # There is a memcpy here, that is very bad.
576
+ indices_q = cu_seqlens_q[:-1]
577
+ query_layer = query_layer.squeeze(1)
578
+ else:
579
+ # The -q_len: slice assumes left padding.
580
+ attention_mask = attention_mask[:, -query_length:]
581
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
582
+
583
+ return (
584
+ query_layer,
585
+ key_layer,
586
+ value_layer,
587
+ indices_q.to(torch.int64),
588
+ (cu_seqlens_q, cu_seqlens_k),
589
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
590
+ )
591
+
592
+
593
+ INTERNLM2_ATTENTION_CLASSES = {
594
+ 'eager': SkyworkLM2Attention,
595
+ 'flash_attention_2': SkyworkLM2FlashAttention2,
596
+ }
597
+
598
+
599
+ # Modified from transformers.model.llama.modeling_llama.LlamaDecoderLayer
600
+ class SkyworkLM2DecoderLayer(nn.Module):
601
+ def __init__(self, config: SkyworkLM2Config):
602
+ super().__init__()
603
+ self.hidden_size = config.hidden_size
604
+
605
+ self.attention = INTERNLM2_ATTENTION_CLASSES[config.attn_implementation](config=config)
606
+
607
+ self.feed_forward = SkyworkLM2MLP(config)
608
+ self.attention_norm = SkyworkLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
609
+ self.ffn_norm = SkyworkLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
610
+
611
+ def forward(
612
+ self,
613
+ hidden_states: torch.Tensor,
614
+ attention_mask: Optional[torch.Tensor] = None,
615
+ position_ids: Optional[torch.LongTensor] = None,
616
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
617
+ output_attentions: Optional[bool] = False,
618
+ use_cache: Optional[bool] = False,
619
+ **kwargs,
620
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
621
+ """
622
+ Args:
623
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
624
+ attention_mask (`torch.FloatTensor`, *optional*):
625
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
626
+ query_sequence_length, key_sequence_length)` if default attention is used.
627
+ output_attentions (`bool`, *optional*):
628
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
629
+ returned tensors for more detail.
630
+ use_cache (`bool`, *optional*):
631
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
632
+ (see `past_key_values`).
633
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
634
+ """
635
+ if 'padding_mask' in kwargs:
636
+ warnings.warn(
637
+ 'Passing `padding_mask` is deprecated and will be removed in v4.37. '
638
+ 'Please make sure use `attention_mask` instead.`'
639
+ )
640
+
641
+ residual = hidden_states
642
+
643
+ hidden_states = self.attention_norm(hidden_states)
644
+
645
+ # Self Attention
646
+ hidden_states, self_attn_weights, present_key_value = self.attention(
647
+ hidden_states=hidden_states,
648
+ attention_mask=attention_mask,
649
+ position_ids=position_ids,
650
+ past_key_value=past_key_value,
651
+ output_attentions=output_attentions,
652
+ use_cache=use_cache,
653
+ **kwargs,
654
+ )
655
+ hidden_states = residual + hidden_states
656
+
657
+ # Fully Connected
658
+ residual = hidden_states
659
+ hidden_states = self.ffn_norm(hidden_states)
660
+ hidden_states = self.feed_forward(hidden_states)
661
+ hidden_states = residual + hidden_states
662
+
663
+ outputs = (hidden_states,)
664
+
665
+ if output_attentions:
666
+ outputs += (self_attn_weights,)
667
+
668
+ if use_cache:
669
+ outputs += (present_key_value,)
670
+
671
+ return outputs
672
+
673
+
674
+ SkyworkLM2_START_DOCSTRING = r"""
675
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
676
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
677
+ etc.)
678
+
679
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
680
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
681
+ and behavior.
682
+
683
+ Parameters:
684
+ config ([`SkyworkLM2Config`]):
685
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
686
+ load the weights associated with the model, only the configuration. Check out the
687
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
688
+ """
689
+
690
+
691
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel with Llama->SkyworkLM2
692
+ @add_start_docstrings(
693
+ 'The bare SkyworkLM2 Model outputting raw hidden-states without any specific head on top.',
694
+ SkyworkLM2_START_DOCSTRING,
695
+ )
696
+ class SkyworkLM2PreTrainedModel(PreTrainedModel):
697
+ config_class = SkyworkLM2Config
698
+ base_model_prefix = 'model'
699
+ supports_gradient_checkpointing = True
700
+ _no_split_modules = ['SkyworkLM2DecoderLayer']
701
+ _skip_keys_device_placement = 'past_key_values'
702
+ _supports_flash_attn_2 = True
703
+
704
+ def _init_weights(self, module):
705
+ std = self.config.initializer_range
706
+ if isinstance(module, nn.Linear):
707
+ module.weight.data.normal_(mean=0.0, std=std)
708
+ if module.bias is not None:
709
+ module.bias.data.zero_()
710
+ elif isinstance(module, nn.Embedding):
711
+ module.weight.data.normal_(mean=0.0, std=std)
712
+ if module.padding_idx is not None:
713
+ module.weight.data[module.padding_idx].zero_()
714
+
715
+
716
+ SkyworkLM2_INPUTS_DOCSTRING = r"""
717
+ Args:
718
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
719
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
720
+ it.
721
+
722
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
723
+ [`PreTrainedTokenizer.__call__`] for details.
724
+
725
+ [What are input IDs?](../glossary#input-ids)
726
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
727
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
728
+
729
+ - 1 for tokens that are **not masked**,
730
+ - 0 for tokens that are **masked**.
731
+
732
+ [What are attention masks?](../glossary#attention-mask)
733
+
734
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
735
+ [`PreTrainedTokenizer.__call__`] for details.
736
+
737
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
738
+ `past_key_values`).
739
+
740
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
741
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
742
+ information on the default strategy.
743
+
744
+ - 1 indicates the head is **not masked**,
745
+ - 0 indicates the head is **masked**.
746
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
747
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
748
+ config.n_positions - 1]`.
749
+
750
+ [What are position IDs?](../glossary#position-ids)
751
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or
752
+ when `config.use_cache=True`):
753
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
754
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
755
+ `(batch_size, num_heads, decoder_sequence_length, embed_size_per_head)`.
756
+
757
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
758
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
759
+
760
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
761
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
762
+ of shape `(batch_size, sequence_length)`.
763
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
764
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
765
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
766
+ model's skywork embedding lookup matrix.
767
+ use_cache (`bool`, *optional*):
768
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
769
+ `past_key_values`).
770
+ output_attentions (`bool`, *optional*):
771
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
772
+ tensors for more detail.
773
+ output_hidden_states (`bool`, *optional*):
774
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
775
+ more detail.
776
+ return_dict (`bool`, *optional*):
777
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
778
+ """
779
+
780
+
781
+ # Modified from transformers.model.llama.modeling_llama.LlamaModel
782
+ @add_start_docstrings(
783
+ 'The bare SkyworkLM2 Model outputting raw hidden-states without any specific head on top.',
784
+ SkyworkLM2_START_DOCSTRING,
785
+ )
786
+ class SkyworkLM2Model(SkyworkLM2PreTrainedModel):
787
+ """
788
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`SkyworkLM2DecoderLayer`]
789
+
790
+ Args:
791
+ config: SkyworkLM2Config
792
+ """
793
+
794
+ _auto_class = 'AutoModel'
795
+
796
+ def __init__(self, config: SkyworkLM2Config):
797
+ super().__init__(config)
798
+ self.padding_idx = config.pad_token_id
799
+ self.vocab_size = config.vocab_size
800
+ self.config = config
801
+ if not has_flash_attn:
802
+ self.config.attn_implementation = 'eager'
803
+ print('Warning: Flash attention is not available, using eager attention instead.')
804
+
805
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
806
+
807
+ self.layers = nn.ModuleList([SkyworkLM2DecoderLayer(config) for _ in range(config.num_hidden_layers)])
808
+ self.norm = SkyworkLM2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
809
+
810
+ self.gradient_checkpointing = False
811
+ # Initialize weights and apply final processing
812
+ self.post_init()
813
+
814
+ def get_input_embeddings(self):
815
+ return self.tok_embeddings
816
+
817
+ def set_input_embeddings(self, value):
818
+ self.tok_embeddings = value
819
+
820
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
821
+ # create causal mask
822
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
823
+ combined_attention_mask = None
824
+ if input_shape[-1] > 1:
825
+ combined_attention_mask = _make_causal_mask(
826
+ input_shape,
827
+ inputs_embeds.dtype,
828
+ device=inputs_embeds.device,
829
+ past_key_values_length=past_key_values_length,
830
+ )
831
+
832
+ if attention_mask is not None:
833
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
834
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
835
+ inputs_embeds.device
836
+ )
837
+ combined_attention_mask = (
838
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
839
+ )
840
+
841
+ return combined_attention_mask
842
+
843
+ @add_start_docstrings_to_model_forward(SkyworkLM2_INPUTS_DOCSTRING)
844
+ def forward(
845
+ self,
846
+ input_ids: torch.LongTensor = None,
847
+ attention_mask: Optional[torch.Tensor] = None,
848
+ position_ids: Optional[torch.LongTensor] = None,
849
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
850
+ inputs_embeds: Optional[torch.FloatTensor] = None,
851
+ use_cache: Optional[bool] = None,
852
+ output_attentions: Optional[bool] = None,
853
+ output_hidden_states: Optional[bool] = None,
854
+ return_dict: Optional[bool] = None,
855
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
856
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
857
+ output_hidden_states = (
858
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
859
+ )
860
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
861
+
862
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
863
+
864
+ if self.config.attn_implementation == 'flash_attention_2':
865
+ _import_flash_attn()
866
+
867
+ # retrieve input_ids and inputs_embeds
868
+ if input_ids is not None and inputs_embeds is not None:
869
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
870
+ elif input_ids is not None:
871
+ batch_size, seq_length = input_ids.shape[:2]
872
+ elif inputs_embeds is not None:
873
+ batch_size, seq_length = inputs_embeds.shape[:2]
874
+ else:
875
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
876
+
877
+ seq_length_with_past = seq_length
878
+ past_key_values_length = 0
879
+ if past_key_values is not None:
880
+ past_key_values_length = past_key_values[0][0].shape[2]
881
+ seq_length_with_past = seq_length_with_past + past_key_values_length
882
+
883
+ if position_ids is None:
884
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
885
+ position_ids = torch.arange(
886
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
887
+ )
888
+ position_ids = position_ids.unsqueeze(0)
889
+
890
+ if inputs_embeds is None:
891
+ inputs_embeds = self.tok_embeddings(input_ids)
892
+
893
+ if self.config.attn_implementation == 'flash_attention_2':
894
+ # 2d mask is passed through the layers
895
+ attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
896
+ else:
897
+ if attention_mask is None:
898
+ attention_mask = torch.ones(
899
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
900
+ )
901
+ attention_mask = self._prepare_decoder_attention_mask(
902
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
903
+ )
904
+
905
+ # embed positions
906
+ hidden_states = inputs_embeds
907
+
908
+ if self.gradient_checkpointing and self.training:
909
+ if use_cache:
910
+ logger.warning_once(
911
+ '`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...'
912
+ )
913
+ use_cache = False
914
+
915
+ # decoder layers
916
+ all_hidden_states = () if output_hidden_states else None
917
+ all_self_attns = () if output_attentions else None
918
+ next_decoder_cache = () if use_cache else None
919
+
920
+ for idx, decoder_layer in enumerate(self.layers):
921
+ if output_hidden_states:
922
+ all_hidden_states += (hidden_states,)
923
+
924
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
925
+
926
+ if self.gradient_checkpointing and self.training:
927
+
928
+ def create_custom_forward(module):
929
+ def custom_forward(*inputs):
930
+ # None for past_key_value
931
+ return module(*inputs, output_attentions, None)
932
+
933
+ return custom_forward
934
+
935
+ layer_outputs = torch.utils.checkpoint.checkpoint(
936
+ create_custom_forward(decoder_layer),
937
+ hidden_states,
938
+ attention_mask,
939
+ position_ids,
940
+ None,
941
+ )
942
+ else:
943
+ layer_outputs = decoder_layer(
944
+ hidden_states,
945
+ attention_mask=attention_mask,
946
+ position_ids=position_ids,
947
+ past_key_value=past_key_value,
948
+ output_attentions=output_attentions,
949
+ use_cache=use_cache,
950
+ )
951
+
952
+ hidden_states = layer_outputs[0]
953
+
954
+ if use_cache:
955
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
956
+
957
+ if output_attentions:
958
+ all_self_attns += (layer_outputs[1],)
959
+
960
+ hidden_states = self.norm(hidden_states)
961
+
962
+ # add hidden states from the last decoder layer
963
+ if output_hidden_states:
964
+ all_hidden_states += (hidden_states,)
965
+
966
+ next_cache = next_decoder_cache if use_cache else None
967
+ if not return_dict:
968
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
969
+ return BaseModelOutputWithPast(
970
+ last_hidden_state=hidden_states,
971
+ past_key_values=next_cache,
972
+ hidden_states=all_hidden_states,
973
+ attentions=all_self_attns,
974
+ )
975
+
976
+
977
+ # Modified from transformers.model.llama.modeling_llama.LlamaForCausalLM
978
+ class SkyworkLM2ForCausalLM(SkyworkLM2PreTrainedModel):
979
+ _auto_class = 'AutoModelForCausalLM'
980
+
981
+ _tied_weights_keys = ['output.weight']
982
+
983
+ def __init__(self, config):
984
+ super().__init__(config)
985
+ self.model = SkyworkLM2Model(config)
986
+ self.vocab_size = config.vocab_size
987
+ self.output = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
988
+
989
+ # Initialize weights and apply final processing
990
+ self.post_init()
991
+
992
+ def get_input_embeddings(self):
993
+ return self.model.tok_embeddings
994
+
995
+ def set_input_embeddings(self, value):
996
+ self.model.tok_embeddings = value
997
+
998
+ def get_output_embeddings(self):
999
+ return self.output
1000
+
1001
+ def set_output_embeddings(self, new_embeddings):
1002
+ self.output = new_embeddings
1003
+
1004
+ def set_decoder(self, decoder):
1005
+ self.model = decoder
1006
+
1007
+ def get_decoder(self):
1008
+ return self.model
1009
+
1010
+ @add_start_docstrings_to_model_forward(SkyworkLM2_INPUTS_DOCSTRING)
1011
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1012
+ def forward(
1013
+ self,
1014
+ input_ids: torch.LongTensor = None,
1015
+ attention_mask: Optional[torch.Tensor] = None,
1016
+ position_ids: Optional[torch.LongTensor] = None,
1017
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1018
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1019
+ labels: Optional[torch.LongTensor] = None,
1020
+ use_cache: Optional[bool] = None,
1021
+ output_attentions: Optional[bool] = None,
1022
+ output_hidden_states: Optional[bool] = None,
1023
+ return_dict: Optional[bool] = None,
1024
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1025
+ r"""
1026
+ Args:
1027
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1028
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1029
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1030
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1031
+
1032
+ Returns:
1033
+
1034
+ Example:
1035
+
1036
+ ```python
1037
+ >>> from transformers import AutoTokenizer, SkyworkLM2ForCausalLM
1038
+
1039
+ >>> model = SkyworkLM2ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1040
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1041
+
1042
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1043
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1044
+
1045
+ >>> # Generate
1046
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1047
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1048
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1049
+ ```"""
1050
+
1051
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1052
+ output_hidden_states = (
1053
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1054
+ )
1055
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1056
+
1057
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1058
+ outputs = self.model(
1059
+ input_ids=input_ids,
1060
+ attention_mask=attention_mask,
1061
+ position_ids=position_ids,
1062
+ past_key_values=past_key_values,
1063
+ inputs_embeds=inputs_embeds,
1064
+ use_cache=use_cache,
1065
+ output_attentions=output_attentions,
1066
+ output_hidden_states=output_hidden_states,
1067
+ return_dict=return_dict,
1068
+ )
1069
+
1070
+ hidden_states = outputs[0]
1071
+ logits = self.output(hidden_states)
1072
+ logits = logits.float()
1073
+
1074
+ loss = None
1075
+ if labels is not None:
1076
+ # Shift so that tokens < n predict n
1077
+ shift_logits = logits[..., :-1, :].contiguous()
1078
+ shift_labels = labels[..., 1:].contiguous()
1079
+ # Flatten the tokens
1080
+ loss_fct = CrossEntropyLoss()
1081
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1082
+ shift_labels = shift_labels.view(-1)
1083
+ # Enable model parallelism
1084
+ shift_labels = shift_labels.to(shift_logits.device)
1085
+ loss = loss_fct(shift_logits, shift_labels)
1086
+
1087
+ if not return_dict:
1088
+ output = (logits,) + outputs[1:]
1089
+ return (loss,) + output if loss is not None else output
1090
+
1091
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1092
+ output = CausalLMOutputWithPast(
1093
+ loss=loss,
1094
+ logits=logits,
1095
+ past_key_values=outputs.past_key_values,
1096
+ hidden_states=outputs.hidden_states,
1097
+ attentions=outputs.attentions,
1098
+ )
1099
+ output['logits'] = output['logits'].to(device)
1100
+ return output
1101
+
1102
+ def prepare_inputs_for_generation(
1103
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1104
+ ):
1105
+ if past_key_values is not None:
1106
+ past_length = past_key_values[0][0].shape[2]
1107
+
1108
+ # Some generation methods already pass only the last input ID
1109
+ if input_ids.shape[1] > past_length:
1110
+ remove_prefix_length = past_length
1111
+ else:
1112
+ # Default to old behavior: keep only final ID
1113
+ remove_prefix_length = input_ids.shape[1] - 1
1114
+
1115
+ input_ids = input_ids[:, remove_prefix_length:]
1116
+
1117
+ position_ids = kwargs.get('position_ids', None)
1118
+ if attention_mask is not None and position_ids is None:
1119
+ # create position_ids on the fly for batch generation
1120
+ position_ids = attention_mask.long().cumsum(-1) - 1
1121
+ position_ids.masked_fill_(attention_mask == 0, 1)
1122
+ if past_key_values:
1123
+ position_ids = position_ids[:, -input_ids.shape[1] :]
1124
+
1125
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1126
+ if inputs_embeds is not None and past_key_values is None:
1127
+ model_inputs = {'inputs_embeds': inputs_embeds}
1128
+ else:
1129
+ model_inputs = {'input_ids': input_ids}
1130
+
1131
+ model_inputs.update(
1132
+ {
1133
+ 'position_ids': position_ids,
1134
+ 'past_key_values': past_key_values,
1135
+ 'use_cache': kwargs.get('use_cache'),
1136
+ 'attention_mask': attention_mask,
1137
+ }
1138
+ )
1139
+ return model_inputs
1140
+
1141
+ @staticmethod
1142
+ def _reorder_cache(past_key_values, beam_idx):
1143
+ reordered_past = ()
1144
+ for layer_past in past_key_values:
1145
+ reordered_past += (
1146
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1147
+ )
1148
+ return reordered_past
1149
+
1150
+ def build_inputs(self, tokenizer, query: str, history: List[Tuple[str, str]] = [], meta_instruction=''): #TODO
1151
+ if tokenizer.add_bos_token:
1152
+ prompt = ''
1153
+ else:
1154
+ prompt = tokenizer.bos_token
1155
+ if meta_instruction:
1156
+ prompt += f"""<|begin▁of▁sentence|>system\n{meta_instruction}<|end▁of▁sentence|>\n"""
1157
+ for record in history:
1158
+ prompt += f"""<|begin▁of▁sentence��>user\n{record[0]}<|end▁of▁sentence|>\n<|begin▁of▁sentence|>assistant\n{record[1]}<|end▁of▁sentence|>\n"""
1159
+ prompt += f"""<|begin▁of▁sentence|>user\n{query}<|end▁of▁sentence|>\n<|begin▁of▁sentence|>assistant\n"""
1160
+ return tokenizer([prompt], return_tensors='pt')
1161
+
1162
+ @torch.no_grad()
1163
+ def chat(
1164
+ self,
1165
+ tokenizer,
1166
+ query: str,
1167
+ history: List[Tuple[str, str]] = [],
1168
+ streamer: Optional[BaseStreamer] = None,
1169
+ max_new_tokens: int = 1024,
1170
+ do_sample: bool = True,
1171
+ temperature: float = 0.8,
1172
+ top_p: float = 0.8,
1173
+ meta_instruction: str = '',
1174
+ **kwargs,
1175
+ ):
1176
+ inputs = self.build_inputs(tokenizer, query, history, meta_instruction)
1177
+ inputs = {k: v.to(self.device) for k, v in inputs.items() if torch.is_tensor(v)}
1178
+ # also add end-of-assistant token in eos token id to avoid unnecessary generation
1179
+ eos_token_id = [tokenizer.eos_token_id, tokenizer.convert_tokens_to_ids(['<|end▁of▁sentence|>'])[0]]
1180
+ outputs = self.generate(
1181
+ **inputs,
1182
+ streamer=streamer,
1183
+ max_new_tokens=max_new_tokens,
1184
+ do_sample=do_sample,
1185
+ temperature=temperature,
1186
+ top_p=top_p,
1187
+ eos_token_id=eos_token_id,
1188
+ **kwargs,
1189
+ )
1190
+ outputs = outputs[0].cpu().tolist()[len(inputs['input_ids'][0]) :]
1191
+ response = tokenizer.decode(outputs, skip_special_tokens=True)
1192
+ response = response.split('<|end▁of▁sentence|>')[0]
1193
+ history = history + [(query, response)]
1194
+ return response, history
1195
+
1196
+ @torch.no_grad()
1197
+ def stream_chat(
1198
+ self,
1199
+ tokenizer,
1200
+ query: str,
1201
+ history: List[Tuple[str, str]] = [],
1202
+ max_new_tokens: int = 1024,
1203
+ do_sample: bool = True,
1204
+ temperature: float = 0.8,
1205
+ top_p: float = 0.8,
1206
+ **kwargs,
1207
+ ):
1208
+ """
1209
+ Return a generator in format: (response, history)
1210
+ Eg.
1211
+ ('你好,有什么可以帮助您的吗', [('你好', '你好,有什么可以帮助您的吗')])
1212
+ ('你好,有什么可以帮助您的吗?', [('你好', '你好,有什么可以帮助您的吗?')])
1213
+ """
1214
+ if BaseStreamer is None:
1215
+ raise ModuleNotFoundError(
1216
+ 'The version of `transformers` is too low. Please make sure '
1217
+ 'that you have installed `transformers>=4.28.0`.'
1218
+ )
1219
+
1220
+ response_queue = queue.Queue(maxsize=20)
1221
+
1222
+ class ChatStreamer(BaseStreamer):
1223
+ def __init__(self, tokenizer) -> None:
1224
+ super().__init__()
1225
+ self.tokenizer = tokenizer
1226
+ self.queue = response_queue
1227
+ self.query = query
1228
+ self.history = history
1229
+ self.response = ''
1230
+ self.cache = []
1231
+ self.received_inputs = False
1232
+ self.queue.put((self.response, history + [(self.query, self.response)]))
1233
+
1234
+ def put(self, value):
1235
+ if len(value.shape) > 1 and value.shape[0] > 1:
1236
+ raise ValueError('ChatStreamer only supports batch size 1')
1237
+ elif len(value.shape) > 1:
1238
+ value = value[0]
1239
+
1240
+ if not self.received_inputs:
1241
+ # The first received value is input_ids, ignore here
1242
+ self.received_inputs = True
1243
+ return
1244
+
1245
+ self.cache.extend(value.tolist())
1246
+ token = self.tokenizer.decode(self.cache, skip_special_tokens=True)
1247
+ if token.strip() != '<|end▁of▁sentence|>':
1248
+ self.response = self.response + token
1249
+ history = self.history + [(self.query, self.response)]
1250
+ self.queue.put((self.response, history))
1251
+ self.cache = []
1252
+ else:
1253
+ self.end()
1254
+
1255
+ def end(self):
1256
+ self.queue.put(None)
1257
+
1258
+ def stream_producer():
1259
+ return self.chat(
1260
+ tokenizer=tokenizer,
1261
+ query=query,
1262
+ streamer=ChatStreamer(tokenizer=tokenizer),
1263
+ history=history,
1264
+ max_new_tokens=max_new_tokens,
1265
+ do_sample=do_sample,
1266
+ temperature=temperature,
1267
+ top_p=top_p,
1268
+ **kwargs,
1269
+ )
1270
+
1271
+ def consumer():
1272
+ producer = threading.Thread(target=stream_producer)
1273
+ producer.start()
1274
+ while True:
1275
+ res = response_queue.get()
1276
+ if res is None:
1277
+ return
1278
+ yield res
1279
+
1280
+ return consumer()
1281
+
1282
+
1283
+ # Copied from transformers.model.llama.modeling_llama.LlamaForSequenceClassification with Llama->SkyworkLM2
1284
+ @add_start_docstrings(
1285
+ """
1286
+ The SkyworkLM2 Model transformer with a sequence classification head on top (linear layer).
1287
+
1288
+ [`SkyworkLM2ForSequenceClassification`] uses the last token in order to do the classification,
1289
+ as other causal models (e.g. GPT-2) do.
1290
+
1291
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1292
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1293
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1294
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1295
+ each row of the batch).
1296
+ """,
1297
+ SkyworkLM2_START_DOCSTRING,
1298
+ )
1299
+ class SkyworkLM2ForSequenceClassification(SkyworkLM2PreTrainedModel):
1300
+ def __init__(self, config):
1301
+ super().__init__(config)
1302
+ self.num_labels = config.num_labels
1303
+ self.model = SkyworkLM2Model(config)
1304
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1305
+
1306
+ # Initialize weights and apply final processing
1307
+ self.post_init()
1308
+
1309
+ def get_input_embeddings(self):
1310
+ return self.model.tok_embeddings
1311
+
1312
+ def set_input_embeddings(self, value):
1313
+ self.model.tok_embeddings = value
1314
+
1315
+ @add_start_docstrings_to_model_forward(SkyworkLM2_INPUTS_DOCSTRING)
1316
+ def forward(
1317
+ self,
1318
+ input_ids: torch.LongTensor = None,
1319
+ attention_mask: Optional[torch.Tensor] = None,
1320
+ position_ids: Optional[torch.LongTensor] = None,
1321
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1322
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1323
+ labels: Optional[torch.LongTensor] = None,
1324
+ use_cache: Optional[bool] = None,
1325
+ output_attentions: Optional[bool] = None,
1326
+ output_hidden_states: Optional[bool] = None,
1327
+ return_dict: Optional[bool] = None,
1328
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1329
+ r"""
1330
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1331
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1332
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1333
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1334
+ """
1335
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1336
+
1337
+ transformer_outputs = self.model(
1338
+ input_ids,
1339
+ attention_mask=attention_mask,
1340
+ position_ids=position_ids,
1341
+ past_key_values=past_key_values,
1342
+ inputs_embeds=inputs_embeds,
1343
+ use_cache=use_cache,
1344
+ output_attentions=output_attentions,
1345
+ output_hidden_states=output_hidden_states,
1346
+ return_dict=return_dict,
1347
+ )
1348
+ hidden_states = transformer_outputs[0]
1349
+ logits = self.score(hidden_states)
1350
+
1351
+ if input_ids is not None:
1352
+ batch_size = input_ids.shape[0]
1353
+ else:
1354
+ batch_size = inputs_embeds.shape[0]
1355
+
1356
+ if self.config.pad_token_id is None and batch_size != 1:
1357
+ raise ValueError('Cannot handle batch sizes > 1 if no padding token is defined.')
1358
+ if self.config.pad_token_id is None:
1359
+ sequence_lengths = -1
1360
+ else:
1361
+ if input_ids is not None:
1362
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1363
+ logits.device
1364
+ )
1365
+ else:
1366
+ sequence_lengths = -1
1367
+
1368
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1369
+
1370
+ loss = None
1371
+ if labels is not None:
1372
+ labels = labels.to(logits.device)
1373
+ if self.config.problem_type is None:
1374
+ if self.num_labels == 1:
1375
+ self.config.problem_type = 'regression'
1376
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1377
+ self.config.problem_type = 'single_label_classification'
1378
+ else:
1379
+ self.config.problem_type = 'multi_label_classification'
1380
+
1381
+ if self.config.problem_type == 'regression':
1382
+ loss_fct = MSELoss()
1383
+ if self.num_labels == 1:
1384
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1385
+ else:
1386
+ loss = loss_fct(pooled_logits, labels)
1387
+ elif self.config.problem_type == 'single_label_classification':
1388
+ loss_fct = CrossEntropyLoss()
1389
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1390
+ elif self.config.problem_type == 'multi_label_classification':
1391
+ loss_fct = BCEWithLogitsLoss()
1392
+ loss = loss_fct(pooled_logits, labels)
1393
+ if not return_dict:
1394
+ output = (pooled_logits,) + transformer_outputs[1:]
1395
+ return ((loss,) + output) if loss is not None else output
1396
+
1397
+ return SequenceClassifierOutputWithPast(
1398
+ loss=loss,
1399
+ logits=pooled_logits,
1400
+ past_key_values=transformer_outputs.past_key_values,
1401
+ hidden_states=transformer_outputs.hidden_states,
1402
+ attentions=transformer_outputs.attentions,
1403
+ )