qhduan commited on
Commit
900807d
1 Parent(s): 65c43a0

Upload modeling_aquila.py

Browse files
Files changed (1) hide show
  1. modeling_aquila.py +971 -0
modeling_aquila.py ADDED
@@ -0,0 +1,971 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from transformers.models.llama.configuration_llama import LlamaConfig
34
+
35
+
36
+ ## cis x = cos x + i sin x
37
+ def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
38
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
39
+ t = torch.arange(end, device=freqs.device)
40
+ freqs = torch.outer(t, freqs).float()
41
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
42
+ return freqs_cis
43
+
44
+
45
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
46
+ ndim = x.ndim
47
+ assert 0 <= 1 < ndim
48
+ assert freqs_cis.shape == (x.shape[1], x.shape[-1])
49
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
50
+ return freqs_cis.view(*shape)
51
+
52
+
53
+ def apply_rotary_pos_emb(
54
+ xq: torch.Tensor,
55
+ xk: torch.Tensor,
56
+ freqs_cis: torch.Tensor,
57
+ ) :
58
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
59
+ xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
60
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
61
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
62
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
63
+ return xq_out.type_as(xq), xk_out.type_as(xk)
64
+
65
+
66
+ logger = logging.get_logger(__name__)
67
+
68
+ _CONFIG_FOR_DOC = "LlamaConfig"
69
+
70
+
71
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
72
+ def _make_causal_mask(
73
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
74
+ ):
75
+ """
76
+ Make causal mask used for bi-directional self-attention.
77
+ """
78
+ bsz, tgt_len = input_ids_shape
79
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
80
+ mask_cond = torch.arange(mask.size(-1), device=device)
81
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
82
+ mask = mask.to(dtype)
83
+
84
+ if past_key_values_length > 0:
85
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
86
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
87
+
88
+
89
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
90
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
91
+ """
92
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
93
+ """
94
+ bsz, src_len = mask.size()
95
+ tgt_len = tgt_len if tgt_len is not None else src_len
96
+
97
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
98
+
99
+ inverted_mask = 1.0 - expanded_mask
100
+
101
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
102
+
103
+
104
+ # class LlamaRMSNorm(nn.Module):
105
+ # def __init__(self, hidden_size, eps=1e-6):
106
+ # """
107
+ # LlamaRMSNorm is equivalent to T5LayerNorm
108
+ # """
109
+ # super().__init__()
110
+ # self.weight = nn.Parameter(torch.ones(hidden_size))
111
+ # self.variance_epsilon = eps
112
+
113
+ # def forward(self, hidden_states):
114
+ # input_dtype = hidden_states.dtype
115
+ # variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
116
+ # hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
117
+
118
+ # return (self.weight * hidden_states).to(input_dtype)
119
+
120
+
121
+ class LlamaRMSNorm(nn.Module):
122
+ def __init__(self, hidden_size, eps=1e-6):
123
+ """
124
+ RMSNorm is equivalent to T5LayerNorm
125
+ """
126
+ super().__init__()
127
+ self.weight = nn.Parameter(torch.ones(hidden_size))
128
+ self.variance_epsilon = eps
129
+
130
+ def forward(self, hidden_states):
131
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
132
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
133
+
134
+ # convert into half-precision if necessary
135
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
136
+ hidden_states = hidden_states.to(self.weight.dtype)
137
+
138
+ return self.weight * hidden_states
139
+
140
+
141
+
142
+ # class LlamaRotaryEmbedding(torch.nn.Module):
143
+ # def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
144
+ # super().__init__()
145
+ # inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
146
+ # self.register_buffer("inv_freq", inv_freq)
147
+
148
+ # # Build here to make `torch.jit.trace` work.
149
+ # self.max_seq_len_cached = max_position_embeddings
150
+ # t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
151
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
152
+ # # Different from paper, but it uses a different permutation in order to obtain the same calculation
153
+ # emb = torch.cat((freqs, freqs), dim=-1)
154
+ # dtype = torch.get_default_dtype()
155
+ # self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
156
+ # self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
157
+
158
+ # def forward(self, x, seq_len=None):
159
+ # # x: [bs, num_attention_heads, seq_len, head_size]
160
+ # # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
161
+ # if seq_len > self.max_seq_len_cached:
162
+ # self.max_seq_len_cached = seq_len
163
+ # t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
164
+ # freqs = torch.einsum("i,j->ij", t, self.inv_freq)
165
+ # # Different from paper, but it uses a different permutation in order to obtain the same calculation
166
+ # emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
167
+ # self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(x.dtype), persistent=False)
168
+ # self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(x.dtype), persistent=False)
169
+ # return (
170
+ # self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
171
+ # self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
172
+ # )
173
+
174
+
175
+ # def rotate_half(x):
176
+ # """Rotates half the hidden dims of the input."""
177
+ # x1 = x[..., : x.shape[-1] // 2]
178
+ # x2 = x[..., x.shape[-1] // 2 :]
179
+ # return torch.cat((-x2, x1), dim=-1)
180
+
181
+
182
+ # def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
183
+ # # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
184
+ # cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
185
+ # sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
186
+ # cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
187
+ # sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
188
+ # q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ # k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ # return q_embed, k_embed
191
+
192
+
193
+ class LlamaMLP(nn.Module):
194
+ def __init__(
195
+ self,
196
+ hidden_size: int,
197
+ intermediate_size: int,
198
+ hidden_act: str,
199
+ ):
200
+ super().__init__()
201
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
202
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
203
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
204
+ self.act_fn = ACT2FN[hidden_act]
205
+
206
+ def forward(self, x):
207
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
208
+
209
+
210
+ class LlamaAttention(nn.Module):
211
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
212
+
213
+ def __init__(self, config: LlamaConfig):
214
+ super().__init__()
215
+ self.config = config
216
+ self.hidden_size = config.hidden_size
217
+ self.num_heads = config.num_attention_heads
218
+ self.head_dim = self.hidden_size // self.num_heads
219
+ self.max_position_embeddings = config.max_position_embeddings
220
+
221
+ if (self.head_dim * self.num_heads) != self.hidden_size:
222
+ raise ValueError(
223
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
224
+ f" and `num_heads`: {self.num_heads})."
225
+ )
226
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
227
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
228
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
229
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
230
+ # self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
231
+ self.freqs_cis = precompute_freqs_cis(
232
+ self.hidden_size // self.num_heads, self.max_position_embeddings * 2
233
+ )
234
+
235
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
236
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
237
+
238
+ def forward(
239
+ self,
240
+ hidden_states: torch.Tensor,
241
+ attention_mask: Optional[torch.Tensor] = None,
242
+ position_ids: Optional[torch.LongTensor] = None,
243
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
244
+ output_attentions: bool = False,
245
+ use_cache: bool = False,
246
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
247
+ bsz, q_len, _ = hidden_states.size()
248
+
249
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
250
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim)
251
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
252
+ self.freqs_cis = self.freqs_cis.to(hidden_states.device)
253
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, freqs_cis=self.freqs_cis[:query_states.shape[1]])
254
+ query_states = query_states.transpose(1, 2)
255
+ key_states = key_states.transpose(1, 2)
256
+ kv_seq_len = key_states.shape[-2]
257
+ if past_key_value is not None:
258
+ kv_seq_len += past_key_value[0].shape[-2]
259
+
260
+ # query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
261
+ # key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
262
+ # value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
263
+
264
+ # kv_seq_len = key_states.shape[-2]
265
+ # if past_key_value is not None:
266
+ # kv_seq_len += past_key_value[0].shape[-2]
267
+ # cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
268
+ # query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
269
+ # [bsz, nh, t, hd]
270
+
271
+ if past_key_value is not None:
272
+ # reuse k, v, self_attention
273
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
274
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
275
+
276
+ past_key_value = (key_states, value_states) if use_cache else None
277
+
278
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
279
+
280
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
281
+ raise ValueError(
282
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
283
+ f" {attn_weights.size()}"
284
+ )
285
+
286
+ if attention_mask is not None:
287
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
288
+ raise ValueError(
289
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
290
+ )
291
+ attention_mask = torch.where(attention_mask < 0, float('-inf'), float(0))
292
+ attn_weights = attn_weights + attention_mask
293
+ # attn_weights = torch.max(
294
+ # attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
295
+ # )
296
+
297
+ # xq = xq.transpose(1, 2)
298
+ # keys = keys.transpose(1, 2)
299
+ # values = values.transpose(1, 2)
300
+ # scores = torch.matmul(xq, keys.transpose(2, 3)) / math.sqrt(self.head_dim)
301
+ # if mask is not None:
302
+ # scores = scores + mask # (bs, n_local_heads, slen, cache_len + slen)
303
+ # scores = F.softmax(scores.float(), dim=-1).type_as(xq)
304
+ # output = torch.matmul(scores, values) # (bs, n_local_heads, slen, head_dim)
305
+ # output = output.transpose(
306
+ # 1, 2
307
+ # ).contiguous().view(bsz, seqlen, -1)
308
+
309
+
310
+ # print('ddddd')
311
+ # breakpoint()
312
+ # import pdb; pdb.set_trace()
313
+ # upcast attention to fp32
314
+ attn_weights = nn.functional.softmax(attn_weights.float(), dim=-1).to(query_states.dtype)
315
+ attn_output = torch.matmul(attn_weights, value_states)
316
+
317
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
318
+ raise ValueError(
319
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
320
+ f" {attn_output.size()}"
321
+ )
322
+
323
+ attn_output = attn_output.transpose(1, 2)
324
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
325
+
326
+ attn_output = self.o_proj(attn_output)
327
+
328
+ if not output_attentions:
329
+ attn_weights = None
330
+
331
+ return attn_output, attn_weights, past_key_value
332
+
333
+
334
+ class LlamaDecoderLayer(nn.Module):
335
+ def __init__(self, config: LlamaConfig):
336
+ super().__init__()
337
+ self.hidden_size = config.hidden_size
338
+ self.self_attn = LlamaAttention(config=config)
339
+ self.mlp = LlamaMLP(
340
+ hidden_size=self.hidden_size,
341
+ intermediate_size=config.intermediate_size,
342
+ hidden_act=config.hidden_act,
343
+ )
344
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
345
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
346
+
347
+ def forward(
348
+ self,
349
+ hidden_states: torch.Tensor,
350
+ attention_mask: Optional[torch.Tensor] = None,
351
+ position_ids: Optional[torch.LongTensor] = None,
352
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
353
+ output_attentions: Optional[bool] = False,
354
+ use_cache: Optional[bool] = False,
355
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
356
+ """
357
+ Args:
358
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
359
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
360
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
361
+ output_attentions (`bool`, *optional*):
362
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
363
+ returned tensors for more detail.
364
+ use_cache (`bool`, *optional*):
365
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
366
+ (see `past_key_values`).
367
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
368
+ """
369
+
370
+ residual = hidden_states
371
+ hidden_states = self.input_layernorm(hidden_states)
372
+ # Self Attention
373
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
374
+ hidden_states=hidden_states,
375
+ attention_mask=attention_mask,
376
+ position_ids=position_ids,
377
+ past_key_value=past_key_value,
378
+ output_attentions=output_attentions,
379
+ use_cache=use_cache,
380
+ )
381
+ hidden_states = residual + hidden_states
382
+ # Fully Connected
383
+ residual = hidden_states
384
+ hidden_states = self.post_attention_layernorm(hidden_states)
385
+ hidden_states = self.mlp(hidden_states)
386
+ hidden_states = residual + hidden_states
387
+ outputs = (hidden_states,)
388
+
389
+ # def forward(self, x,
390
+ # freqs_cis,
391
+ # mask ):
392
+ # h = x + self.attention.forward(self.attention_norm(x), self.start_pos, freqs_cis, mask, self.use_cache)
393
+ # out = h + self.feed_forward.forward(self.ffn_norm(h))
394
+ # return out
395
+
396
+ if output_attentions:
397
+ outputs += (self_attn_weights,)
398
+
399
+ if use_cache:
400
+ outputs += (present_key_value,)
401
+
402
+ return outputs
403
+
404
+
405
+ LLAMA_START_DOCSTRING = r"""
406
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
407
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
408
+ etc.)
409
+
410
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
411
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
412
+ and behavior.
413
+
414
+ Parameters:
415
+ config ([`LlamaConfig`]):
416
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
417
+ load the weights associated with the model, only the configuration. Check out the
418
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
419
+ """
420
+
421
+
422
+ @add_start_docstrings(
423
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
424
+ LLAMA_START_DOCSTRING,
425
+ )
426
+ class LlamaPreTrainedModel(PreTrainedModel):
427
+ config_class = LlamaConfig
428
+ base_model_prefix = "model"
429
+ supports_gradient_checkpointing = True
430
+ _no_split_modules = ["LlamaDecoderLayer"]
431
+ _skip_keys_device_placement = "past_key_values"
432
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
433
+
434
+ def _init_weights(self, module):
435
+ std = self.config.initializer_range
436
+ if isinstance(module, nn.Linear):
437
+ module.weight.data.normal_(mean=0.0, std=std)
438
+ if module.bias is not None:
439
+ module.bias.data.zero_()
440
+ elif isinstance(module, nn.Embedding):
441
+ module.weight.data.normal_(mean=0.0, std=std)
442
+ if module.padding_idx is not None:
443
+ module.weight.data[module.padding_idx].zero_()
444
+
445
+ def _set_gradient_checkpointing(self, module, value=False):
446
+ if isinstance(module, LlamaModel):
447
+ module.gradient_checkpointing = value
448
+
449
+
450
+ LLAMA_INPUTS_DOCSTRING = r"""
451
+ Args:
452
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
453
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
454
+ it.
455
+
456
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
457
+ [`PreTrainedTokenizer.__call__`] for details.
458
+
459
+ [What are input IDs?](../glossary#input-ids)
460
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
461
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
462
+
463
+ - 1 for tokens that are **not masked**,
464
+ - 0 for tokens that are **masked**.
465
+
466
+ [What are attention masks?](../glossary#attention-mask)
467
+
468
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
469
+ [`PreTrainedTokenizer.__call__`] for details.
470
+
471
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
472
+ `past_key_values`).
473
+
474
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
475
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
476
+ information on the default strategy.
477
+
478
+ - 1 indicates the head is **not masked**,
479
+ - 0 indicates the head is **masked**.
480
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
481
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
482
+ config.n_positions - 1]`.
483
+
484
+ [What are position IDs?](../glossary#position-ids)
485
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
486
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
487
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
488
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
489
+
490
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
491
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
492
+
493
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
494
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
495
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
496
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
497
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
498
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
499
+ model's internal embedding lookup matrix.
500
+ use_cache (`bool`, *optional*):
501
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
502
+ `past_key_values`).
503
+ output_attentions (`bool`, *optional*):
504
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
505
+ tensors for more detail.
506
+ output_hidden_states (`bool`, *optional*):
507
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
508
+ more detail.
509
+ return_dict (`bool`, *optional*):
510
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
511
+ """
512
+
513
+
514
+ @add_start_docstrings(
515
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
516
+ LLAMA_START_DOCSTRING,
517
+ )
518
+ class LlamaModel(LlamaPreTrainedModel):
519
+ """
520
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
521
+
522
+ Args:
523
+ config: LlamaConfig
524
+ """
525
+
526
+ def __init__(self, config: LlamaConfig):
527
+ super().__init__(config)
528
+ self.padding_idx = config.pad_token_id
529
+ self.vocab_size = config.vocab_size
530
+
531
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
532
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
533
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
534
+
535
+ self.gradient_checkpointing = False
536
+ # Initialize weights and apply final processing
537
+ self.post_init()
538
+
539
+ def get_input_embeddings(self):
540
+ return self.embed_tokens
541
+
542
+ def set_input_embeddings(self, value):
543
+ self.embed_tokens = value
544
+
545
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
546
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
547
+ # create causal mask
548
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
549
+ combined_attention_mask = None
550
+ if input_shape[-1] > 1:
551
+ combined_attention_mask = _make_causal_mask(
552
+ input_shape,
553
+ inputs_embeds.dtype,
554
+ device=inputs_embeds.device,
555
+ past_key_values_length=past_key_values_length,
556
+ )
557
+
558
+ if attention_mask is not None:
559
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
560
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
561
+ inputs_embeds.device
562
+ )
563
+ combined_attention_mask = (
564
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
565
+ )
566
+
567
+ return combined_attention_mask
568
+
569
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
570
+ def forward(
571
+ self,
572
+ input_ids: torch.LongTensor = None,
573
+ attention_mask: Optional[torch.Tensor] = None,
574
+ position_ids: Optional[torch.LongTensor] = None,
575
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
576
+ inputs_embeds: Optional[torch.FloatTensor] = None,
577
+ use_cache: Optional[bool] = None,
578
+ output_attentions: Optional[bool] = None,
579
+ output_hidden_states: Optional[bool] = None,
580
+ return_dict: Optional[bool] = None,
581
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
582
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
583
+ output_hidden_states = (
584
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
585
+ )
586
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
587
+
588
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
589
+
590
+ # retrieve input_ids and inputs_embeds
591
+ if input_ids is not None and inputs_embeds is not None:
592
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
593
+ elif input_ids is not None:
594
+ batch_size, seq_length = input_ids.shape
595
+ elif inputs_embeds is not None:
596
+ batch_size, seq_length, _ = inputs_embeds.shape
597
+ else:
598
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
599
+
600
+ seq_length_with_past = seq_length
601
+ past_key_values_length = 0
602
+
603
+ if past_key_values is not None:
604
+ past_key_values_length = past_key_values[0][0].shape[2]
605
+ seq_length_with_past = seq_length_with_past + past_key_values_length
606
+
607
+ if position_ids is None:
608
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
609
+ position_ids = torch.arange(
610
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
611
+ )
612
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
613
+ else:
614
+ position_ids = position_ids.view(-1, seq_length).long()
615
+
616
+ if inputs_embeds is None:
617
+ inputs_embeds = self.embed_tokens(input_ids)
618
+ # embed positions
619
+ if attention_mask is None:
620
+ attention_mask = torch.ones(
621
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
622
+ )
623
+ attention_mask = self._prepare_decoder_attention_mask(
624
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
625
+ )
626
+
627
+ hidden_states = inputs_embeds
628
+
629
+ if self.gradient_checkpointing and self.training:
630
+ if use_cache:
631
+ logger.warning_once(
632
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
633
+ )
634
+ use_cache = False
635
+
636
+ # decoder layers
637
+ all_hidden_states = () if output_hidden_states else None
638
+ all_self_attns = () if output_attentions else None
639
+ next_decoder_cache = () if use_cache else None
640
+
641
+ for idx, decoder_layer in enumerate(self.layers):
642
+ if output_hidden_states:
643
+ all_hidden_states += (hidden_states,)
644
+
645
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
646
+
647
+ if self.gradient_checkpointing and self.training:
648
+
649
+ def create_custom_forward(module):
650
+ def custom_forward(*inputs):
651
+ # None for past_key_value
652
+ return module(*inputs, output_attentions, None)
653
+
654
+ return custom_forward
655
+
656
+ layer_outputs = torch.utils.checkpoint.checkpoint(
657
+ create_custom_forward(decoder_layer),
658
+ hidden_states,
659
+ attention_mask,
660
+ position_ids,
661
+ None,
662
+ )
663
+ else:
664
+ layer_outputs = decoder_layer(
665
+ hidden_states,
666
+ attention_mask=attention_mask,
667
+ position_ids=position_ids,
668
+ past_key_value=past_key_value,
669
+ output_attentions=output_attentions,
670
+ use_cache=use_cache,
671
+ )
672
+
673
+ hidden_states = layer_outputs[0]
674
+
675
+ if use_cache:
676
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
677
+
678
+ if output_attentions:
679
+ all_self_attns += (layer_outputs[1],)
680
+
681
+ hidden_states = self.norm(hidden_states)
682
+
683
+ # add hidden states from the last decoder layer
684
+ if output_hidden_states:
685
+ all_hidden_states += (hidden_states,)
686
+
687
+ next_cache = next_decoder_cache if use_cache else None
688
+ if not return_dict:
689
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
690
+ return BaseModelOutputWithPast(
691
+ last_hidden_state=hidden_states,
692
+ past_key_values=next_cache,
693
+ hidden_states=all_hidden_states,
694
+ attentions=all_self_attns,
695
+ )
696
+
697
+
698
+ class LlamaForCausalLM(LlamaPreTrainedModel):
699
+ def __init__(self, config):
700
+ super().__init__(config)
701
+ self.model = LlamaModel(config)
702
+
703
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
704
+
705
+ # Initialize weights and apply final processing
706
+ self.post_init()
707
+
708
+ def get_input_embeddings(self):
709
+ return self.model.embed_tokens
710
+
711
+ def set_input_embeddings(self, value):
712
+ self.model.embed_tokens = value
713
+
714
+ def get_output_embeddings(self):
715
+ return self.lm_head
716
+
717
+ def set_output_embeddings(self, new_embeddings):
718
+ self.lm_head = new_embeddings
719
+
720
+ def set_decoder(self, decoder):
721
+ self.model = decoder
722
+
723
+ def get_decoder(self):
724
+ return self.model
725
+
726
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
727
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
728
+ def forward(
729
+ self,
730
+ input_ids: torch.LongTensor = None,
731
+ attention_mask: Optional[torch.Tensor] = None,
732
+ position_ids: Optional[torch.LongTensor] = None,
733
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
734
+ inputs_embeds: Optional[torch.FloatTensor] = None,
735
+ labels: Optional[torch.LongTensor] = None,
736
+ use_cache: Optional[bool] = None,
737
+ output_attentions: Optional[bool] = None,
738
+ output_hidden_states: Optional[bool] = None,
739
+ return_dict: Optional[bool] = None,
740
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
741
+ r"""
742
+ Args:
743
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
744
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
745
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
746
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
747
+
748
+ Returns:
749
+
750
+ Example:
751
+
752
+ ```python
753
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
754
+
755
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
756
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
757
+
758
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
759
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
760
+
761
+ >>> # Generate
762
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
763
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
764
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
765
+ ```"""
766
+
767
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
768
+ output_hidden_states = (
769
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
770
+ )
771
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
772
+
773
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
774
+ outputs = self.model(
775
+ input_ids=input_ids,
776
+ attention_mask=attention_mask,
777
+ position_ids=position_ids,
778
+ past_key_values=past_key_values,
779
+ inputs_embeds=inputs_embeds,
780
+ use_cache=use_cache,
781
+ output_attentions=output_attentions,
782
+ output_hidden_states=output_hidden_states,
783
+ return_dict=return_dict,
784
+ )
785
+
786
+ hidden_states = outputs[0]
787
+ logits = self.lm_head(hidden_states)
788
+
789
+ loss = None
790
+ if labels is not None:
791
+ # Shift so that tokens < n predict n
792
+ shift_logits = logits[..., :-1, :].contiguous()
793
+ shift_labels = labels[..., 1:].contiguous()
794
+ # Flatten the tokens
795
+ loss_fct = CrossEntropyLoss()
796
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
797
+ shift_labels = shift_labels.view(-1)
798
+ # Enable model parallelism
799
+ shift_labels = shift_labels.to(shift_logits.device)
800
+ loss = loss_fct(shift_logits, shift_labels)
801
+
802
+ if not return_dict:
803
+ output = (logits,) + outputs[1:]
804
+ return (loss,) + output if loss is not None else output
805
+
806
+ return CausalLMOutputWithPast(
807
+ loss=loss,
808
+ logits=logits,
809
+ past_key_values=outputs.past_key_values,
810
+ hidden_states=outputs.hidden_states,
811
+ attentions=outputs.attentions,
812
+ )
813
+
814
+ def prepare_inputs_for_generation(
815
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
816
+ ):
817
+ if past_key_values:
818
+ input_ids = input_ids[:, -1:]
819
+
820
+ position_ids = kwargs.get("position_ids", None)
821
+ if attention_mask is not None and position_ids is None:
822
+ # create position_ids on the fly for batch generation
823
+ position_ids = attention_mask.long().cumsum(-1) - 1
824
+ position_ids.masked_fill_(attention_mask == 0, 1)
825
+ if past_key_values:
826
+ position_ids = position_ids[:, -1].unsqueeze(-1)
827
+
828
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
829
+ if inputs_embeds is not None and past_key_values is None:
830
+ model_inputs = {"inputs_embeds": inputs_embeds}
831
+ else:
832
+ model_inputs = {"input_ids": input_ids}
833
+
834
+ model_inputs.update(
835
+ {
836
+ "position_ids": position_ids,
837
+ "past_key_values": past_key_values,
838
+ "use_cache": kwargs.get("use_cache"),
839
+ "attention_mask": attention_mask,
840
+ }
841
+ )
842
+ return model_inputs
843
+
844
+ @staticmethod
845
+ def _reorder_cache(past_key_values, beam_idx):
846
+ reordered_past = ()
847
+ for layer_past in past_key_values:
848
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
849
+ return reordered_past
850
+
851
+
852
+ @add_start_docstrings(
853
+ """
854
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
855
+
856
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
857
+ (e.g. GPT-2) do.
858
+
859
+ Since it does classification on the last token, it requires to know the position of the last token. If a
860
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
861
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
862
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
863
+ each row of the batch).
864
+ """,
865
+ LLAMA_START_DOCSTRING,
866
+ )
867
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
868
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
869
+
870
+ def __init__(self, config):
871
+ super().__init__(config)
872
+ self.num_labels = config.num_labels
873
+ self.model = LlamaModel(config)
874
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
875
+
876
+ # Initialize weights and apply final processing
877
+ self.post_init()
878
+
879
+ def get_input_embeddings(self):
880
+ return self.model.embed_tokens
881
+
882
+ def set_input_embeddings(self, value):
883
+ self.model.embed_tokens = value
884
+
885
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
886
+ def forward(
887
+ self,
888
+ input_ids: torch.LongTensor = None,
889
+ attention_mask: Optional[torch.Tensor] = None,
890
+ position_ids: Optional[torch.LongTensor] = None,
891
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
892
+ inputs_embeds: Optional[torch.FloatTensor] = None,
893
+ labels: Optional[torch.LongTensor] = None,
894
+ use_cache: Optional[bool] = None,
895
+ output_attentions: Optional[bool] = None,
896
+ output_hidden_states: Optional[bool] = None,
897
+ return_dict: Optional[bool] = None,
898
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
899
+ r"""
900
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
901
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
902
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
903
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
904
+ """
905
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
906
+
907
+ transformer_outputs = self.model(
908
+ input_ids,
909
+ attention_mask=attention_mask,
910
+ position_ids=position_ids,
911
+ past_key_values=past_key_values,
912
+ inputs_embeds=inputs_embeds,
913
+ use_cache=use_cache,
914
+ output_attentions=output_attentions,
915
+ output_hidden_states=output_hidden_states,
916
+ return_dict=return_dict,
917
+ )
918
+ hidden_states = transformer_outputs[0]
919
+ logits = self.score(hidden_states)
920
+
921
+ if input_ids is not None:
922
+ batch_size = input_ids.shape[0]
923
+ else:
924
+ batch_size = inputs_embeds.shape[0]
925
+
926
+ if self.config.pad_token_id is None and batch_size != 1:
927
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
928
+ if self.config.pad_token_id is None:
929
+ sequence_lengths = -1
930
+ else:
931
+ if input_ids is not None:
932
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
933
+ else:
934
+ sequence_lengths = -1
935
+
936
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
937
+
938
+ loss = None
939
+ if labels is not None:
940
+ labels = labels.to(logits.device)
941
+ if self.config.problem_type is None:
942
+ if self.num_labels == 1:
943
+ self.config.problem_type = "regression"
944
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
945
+ self.config.problem_type = "single_label_classification"
946
+ else:
947
+ self.config.problem_type = "multi_label_classification"
948
+
949
+ if self.config.problem_type == "regression":
950
+ loss_fct = MSELoss()
951
+ if self.num_labels == 1:
952
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
953
+ else:
954
+ loss = loss_fct(pooled_logits, labels)
955
+ elif self.config.problem_type == "single_label_classification":
956
+ loss_fct = CrossEntropyLoss()
957
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
958
+ elif self.config.problem_type == "multi_label_classification":
959
+ loss_fct = BCEWithLogitsLoss()
960
+ loss = loss_fct(pooled_logits, labels)
961
+ if not return_dict:
962
+ output = (pooled_logits,) + transformer_outputs[1:]
963
+ return ((loss,) + output) if loss is not None else output
964
+
965
+ return SequenceClassifierOutputWithPast(
966
+ loss=loss,
967
+ logits=pooled_logits,
968
+ past_key_values=transformer_outputs.past_key_values,
969
+ hidden_states=transformer_outputs.hidden_states,
970
+ attentions=transformer_outputs.attentions,
971
+ )