appleeji commited on
Commit
160dbc8
·
verified ·
1 Parent(s): a7e1569

Upload modeling_llama_kv.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_llama_kv.py +1524 -0
modeling_llama_kv.py ADDED
@@ -0,0 +1,1524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source: https://github.com/huggingface/transformers/blob/v4.31-release/src/transformers/models/llama/modeling_llama.py
2
+ # Modifications are denoted by the symbol: [MODIFIED]
3
+
4
+
5
+ """ PyTorch LLaMA model."""
6
+ import math
7
+ from typing import List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+ import torch.utils.checkpoint
12
+ from torch import nn
13
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
14
+
15
+ # [MODIFIED] Import from transformer library
16
+ from transformers.activations import ACT2FN
17
+ from transformers.modeling_outputs import (
18
+ BaseModelOutputWithPast,
19
+ CausalLMOutputWithPast,
20
+ SequenceClassifierOutputWithPast,
21
+ )
22
+ from transformers.modeling_utils import PreTrainedModel
23
+ from transformers.utils import (
24
+ add_start_docstrings,
25
+ add_start_docstrings_to_model_forward,
26
+ logging,
27
+ replace_return_docstrings,
28
+ )
29
+ try:
30
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
31
+ except ImportError:
32
+ ROPE_INIT_FUNCTIONS = None # Fallback for older transformers versions
33
+ from transformers import LlamaConfig
34
+
35
+ logger = logging.get_logger(__name__)
36
+
37
+ _CONFIG_FOR_DOC = "LlamaConfig"
38
+
39
+
40
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
41
+ def _make_causal_mask(
42
+ input_ids_shape: torch.Size,
43
+ dtype: torch.dtype,
44
+ device: torch.device,
45
+ past_key_values_length: int = 0,
46
+ ):
47
+ """
48
+ Create a causal mask for bi-directional self-attention.
49
+
50
+ Args:
51
+ input_ids_shape (torch.Size): The shape of input_ids tensor, typically (batch_size, tgt_len).
52
+ dtype (torch.dtype): The data type of the mask.
53
+ device (torch.device): The device on which the mask will be placed.
54
+ past_key_values_length (int, optional): The length of past key values. Default is 0.
55
+
56
+ Returns:
57
+ torch.Tensor: The causal mask tensor.
58
+ """
59
+ bsz, tgt_len = input_ids_shape
60
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
61
+ mask_cond = torch.arange(mask.size(-1), device=device)
62
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
63
+ mask = mask.to(dtype)
64
+
65
+ if past_key_values_length > 0:
66
+ mask = torch.cat(
67
+ [
68
+ torch.zeros(
69
+ tgt_len, past_key_values_length, dtype=dtype, device=device
70
+ ),
71
+ mask,
72
+ ],
73
+ dim=-1,
74
+ )
75
+ return mask[None, None, :, :].expand(
76
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
77
+ )
78
+
79
+
80
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
81
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
82
+ """
83
+ Expand attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
84
+
85
+ Args:
86
+ mask (torch.Tensor): The attention mask tensor of shape `[bsz, seq_len]`.
87
+ dtype (torch.dtype): The data type of the mask.
88
+ tgt_len (Optional[int], optional): The target sequence length. If None, it defaults to the source sequence length.
89
+
90
+ Returns:
91
+ torch.Tensor: The expanded mask tensor.
92
+ """
93
+ bsz, src_len = mask.size()
94
+ tgt_len = tgt_len if tgt_len is not None else src_len
95
+
96
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
97
+
98
+ inverted_mask = 1.0 - expanded_mask
99
+
100
+ return inverted_mask.masked_fill(
101
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
102
+ )
103
+
104
+
105
+
106
+
107
+ class LlamaRMSNorm(nn.Module):
108
+ """
109
+ LlamaRMSNorm is equivalent to T5LayerNorm.
110
+
111
+ Args:
112
+ hidden_size (int): The size of the hidden states.
113
+ eps (float, optional): A small value to prevent division by zero. Default is 1e-6.
114
+ """
115
+
116
+ def __init__(self, hidden_size, eps=1e-6):
117
+ super().__init__()
118
+ self.weight = nn.Parameter(torch.ones(hidden_size))
119
+ self.variance_epsilon = eps
120
+
121
+ def forward(self, hidden_states):
122
+ """
123
+ Apply LlamaRMSNorm to the input hidden states.
124
+
125
+ Args:
126
+ hidden_states (torch.Tensor): Input hidden states.
127
+
128
+ Returns:
129
+ torch.Tensor: The normalized and scaled hidden states.
130
+ """
131
+ input_dtype = hidden_states.dtype
132
+ hidden_states = hidden_states.to(torch.float32)
133
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
134
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
135
+ return self.weight * hidden_states.to(input_dtype)
136
+
137
+
138
+ class LlamaRotaryEmbedding(nn.Module):
139
+ """
140
+ Llama Rotary Positional Embedding Module.
141
+
142
+ Args:
143
+ dim (int): The dimension of the embedding.
144
+ max_position_embeddings (int, optional): The maximum position for embeddings. Default is 2048.
145
+ base (int, optional): The base value for rotational encoding. Default is 10000.
146
+ device (str, optional): The device on which the computation will be performed. Default is None.
147
+ """
148
+
149
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
150
+ super().__init__()
151
+
152
+ self.dim = dim
153
+ self.max_position_embeddings = max_position_embeddings
154
+ self.base = base
155
+ inv_freq = 1.0 / (
156
+ self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
157
+ )
158
+ self.register_buffer("inv_freq", inv_freq)
159
+
160
+ # Build here to make `torch.jit.trace` work.
161
+ self._set_cos_sin_cache(
162
+ seq_len=max_position_embeddings,
163
+ device=self.inv_freq.device,
164
+ dtype=torch.get_default_dtype(),
165
+ )
166
+
167
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
168
+ """
169
+ Set the cosine and sine cache for positional embeddings.
170
+
171
+ Args:
172
+ seq_len (int): The sequence length.
173
+ device (str): The device on which the cache tensors will be stored.
174
+ dtype: The data type of the cache tensors.
175
+ """
176
+ self.max_seq_len_cached = seq_len
177
+ t = torch.arange(
178
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
179
+ )
180
+
181
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
182
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
183
+ emb = torch.cat((freqs, freqs), dim=-1)
184
+ self.register_buffer(
185
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
186
+ )
187
+ self.register_buffer(
188
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
189
+ )
190
+
191
+ def forward(self, x, seq_len=None):
192
+ """
193
+ Forward pass of the LlamaRotaryEmbedding module.
194
+
195
+ Args:
196
+ x (torch.Tensor): Input tensor of shape [bs, num_attention_heads, seq_len, head_size].
197
+ seq_len (int): The sequence length. If greater than the cached length, the cache will be updated.
198
+
199
+ Returns:
200
+ tuple: A tuple containing two tensors, the cosine and sine embeddings, both of shape [1, 1, seq_len, dim].
201
+ """
202
+ if seq_len > self.max_seq_len_cached:
203
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
204
+
205
+ return (
206
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
207
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
208
+ )
209
+
210
+
211
+ class LlamaRotaryEmbedding_L31(nn.Module):
212
+ def __init__(
213
+ self,
214
+ dim=None,
215
+ max_position_embeddings=2048,
216
+ base=10000,
217
+ device=None,
218
+ scaling_factor=1.0,
219
+ rope_type="default",
220
+ config: Optional[LlamaConfig] = None,
221
+ ):
222
+ super().__init__()
223
+ # TODO (joao): remove the `if` below, only used for BC
224
+ self.rope_kwargs = {}
225
+ if config is None:
226
+ logger.warning_once(
227
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
228
+ "`config` argument. All other arguments will be removed in v4.46"
229
+ )
230
+ self.rope_kwargs = {
231
+ "rope_type": rope_type,
232
+ "factor": scaling_factor,
233
+ "dim": dim,
234
+ "base": base,
235
+ "max_position_embeddings": max_position_embeddings,
236
+ }
237
+ self.rope_type = rope_type
238
+ self.max_seq_len_cached = max_position_embeddings
239
+ self.original_max_seq_len = max_position_embeddings
240
+ else:
241
+ # BC: "rope_type" was originally "type"
242
+ if config.rope_scaling is not None:
243
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
244
+ else:
245
+ self.rope_type = "default"
246
+ self.max_seq_len_cached = config.max_position_embeddings
247
+ self.original_max_seq_len = config.max_position_embeddings
248
+
249
+ self.config = config
250
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
251
+
252
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
253
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
254
+ self.original_inv_freq = self.inv_freq
255
+
256
+ def _dynamic_frequency_update(self, position_ids, device):
257
+ """
258
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
259
+ 1 - growing beyond the cached sequence length (allow scaling)
260
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
261
+ """
262
+ seq_len = torch.max(position_ids) + 1
263
+ if seq_len > self.max_seq_len_cached: # growth
264
+ inv_freq, self.attention_scaling = self.rope_init_fn(
265
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
266
+ )
267
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
268
+ self.max_seq_len_cached = seq_len
269
+
270
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
271
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
272
+ self.max_seq_len_cached = self.original_max_seq_len
273
+
274
+ @torch.no_grad()
275
+ def forward(self, x, position_ids):
276
+ if "dynamic" in self.rope_type:
277
+ self._dynamic_frequency_update(position_ids, device=x.device)
278
+
279
+ # Core RoPE block
280
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
281
+ position_ids_expanded = position_ids[:, None, :].float()
282
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
283
+ device_type = x.device.type
284
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
285
+ with torch.autocast(device_type=device_type, enabled=False):
286
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
287
+ emb = torch.cat((freqs, freqs), dim=-1)
288
+ cos = emb.cos()
289
+ sin = emb.sin()
290
+
291
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
292
+ cos = cos * self.attention_scaling
293
+ sin = sin * self.attention_scaling
294
+
295
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
296
+
297
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
298
+ """
299
+ LlamaRotaryEmbedding extended with linear scaling.
300
+
301
+ This class adds linear scaling to LlamaRotaryEmbedding. Credits to the Reddit user /u/kaiokendev.
302
+
303
+ Args:
304
+ dim (int): The dimension of the embedding.
305
+ max_position_embeddings (int, optional): The maximum number of position embeddings. Default is 2048.
306
+ base (int, optional): The base value for the rotational embeddings. Default is 10000.
307
+ device (str or torch.device, optional): The device where the embeddings should be stored. Default is None.
308
+ scaling_factor (float, optional): The scaling factor for the embeddings. Default is 1.0.
309
+ """
310
+
311
+ def __init__(
312
+ self,
313
+ dim,
314
+ max_position_embeddings=2048,
315
+ base=10000,
316
+ device=None,
317
+ scaling_factor=1.0,
318
+ ):
319
+ self.scaling_factor = scaling_factor
320
+ super().__init__(dim, max_position_embeddings, base, device)
321
+
322
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
323
+ """
324
+ Set the cosine and sine cache for the rotary embeddings.
325
+
326
+ Args:
327
+ seq_len (int): The sequence length.
328
+ device (str or torch.device): The device where the cache should be stored.
329
+ dtype: The data type for the cache.
330
+ """
331
+ self.max_seq_len_cached = seq_len
332
+ t = torch.arange(
333
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
334
+ )
335
+ t = t / self.scaling_factor
336
+
337
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
338
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
339
+ emb = torch.cat((freqs, freqs), dim=-1)
340
+ self.register_buffer(
341
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
342
+ )
343
+ self.register_buffer(
344
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
345
+ )
346
+
347
+
348
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
349
+ """
350
+ LlamaRotaryEmbedding extended with Dynamic NTK scaling.
351
+
352
+ Credits to the Reddit users /u/bloc97 and /u/emozilla.
353
+ """
354
+
355
+ def __init__(
356
+ self,
357
+ dim,
358
+ max_position_embeddings=2048,
359
+ base=10000,
360
+ device=None,
361
+ scaling_factor=1.0,
362
+ ):
363
+ """
364
+ Initialize the LlamaDynamicNTKScalingRotaryEmbedding.
365
+
366
+ Args:
367
+ dim (int): The dimensionality of the embedding.
368
+ max_position_embeddings (int, optional): Maximum number of position embeddings. Default is 2048.
369
+ base (int, optional): Base value for scaling calculations. Default is 10000.
370
+ device: The device to place tensors on. If None, uses the default device.
371
+ scaling_factor (float, optional): Scaling factor for NTK scaling. Default is 1.0.
372
+ """
373
+ self.scaling_factor = scaling_factor
374
+ super().__init__(dim, max_position_embeddings, base, device)
375
+
376
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
377
+ """
378
+ Set the cached values for cosine and sine.
379
+
380
+ Args:
381
+ seq_len (int): The sequence length.
382
+ device: The device to place tensors on.
383
+ dtype: The data type of tensors.
384
+ """
385
+ self.max_seq_len_cached = seq_len
386
+
387
+ if seq_len > self.max_position_embeddings:
388
+ base = self.base * (
389
+ (self.scaling_factor * seq_len / self.max_position_embeddings)
390
+ - (self.scaling_factor - 1)
391
+ ) ** (self.dim / (self.dim - 2))
392
+ inv_freq = 1.0 / (
393
+ base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)
394
+ )
395
+ self.register_buffer("inv_freq", inv_freq)
396
+
397
+ t = torch.arange(
398
+ self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype
399
+ )
400
+
401
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
402
+ emb = torch.cat((freqs, freqs), dim=-1)
403
+ self.register_buffer(
404
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
405
+ )
406
+ self.register_buffer(
407
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
408
+ )
409
+
410
+
411
+ def rotate_half(x):
412
+ """
413
+ Rotates half the hidden dimensions of the input.
414
+
415
+ Args:
416
+ x (torch.Tensor): Input tensor.
417
+
418
+ Returns:
419
+ torch.Tensor: Tensor with half of its hidden dimensions rotated.
420
+ """
421
+ x1 = x[..., : x.shape[-1] // 2]
422
+ x2 = x[..., x.shape[-1] // 2:]
423
+ return torch.cat((-x2, x1), dim=-1)
424
+
425
+
426
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
427
+ """
428
+ Apply rotary position embeddings to query and key tensors.
429
+
430
+ Args:
431
+ q (torch.Tensor): Query tensor.
432
+ k (torch.Tensor): Key tensor.
433
+ cos (torch.Tensor): Cosine values.
434
+ sin (torch.Tensor): Sine values.
435
+ position_ids (torch.Tensor): Position IDs.
436
+
437
+ Returns:
438
+ torch.Tensor: Query and key tensors with rotary position embeddings applied.
439
+ """
440
+ cos = cos.squeeze(1).squeeze(0)
441
+ sin = sin.squeeze(1).squeeze(0)
442
+ cos = cos[position_ids].unsqueeze(1)
443
+ sin = sin[position_ids].unsqueeze(1)
444
+ q_embed = (q * cos) + (rotate_half(q) * sin)
445
+ k_embed = (k * cos) + (rotate_half(k) * sin)
446
+ return q_embed, k_embed
447
+
448
+
449
+ def apply_rotary_pos_emb_L31(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
450
+ """Applies Rotary Position Embedding to the query and key tensors.
451
+
452
+ Args:
453
+ q (`torch.Tensor`): The query tensor.
454
+ k (`torch.Tensor`): The key tensor.
455
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
456
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
457
+ position_ids (`torch.Tensor`, *optional*):
458
+ Deprecated and unused.
459
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
460
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
461
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
462
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
463
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
464
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
465
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
466
+ Returns:
467
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
468
+ """
469
+ cos = cos.unsqueeze(unsqueeze_dim)
470
+ sin = sin.unsqueeze(unsqueeze_dim)
471
+ q_embed = (q * cos) + (rotate_half(q) * sin)
472
+ k_embed = (k * cos) + (rotate_half(k) * sin)
473
+ return q_embed, k_embed
474
+
475
+
476
+ class LlamaMLP(nn.Module):
477
+ """
478
+ LlamaMLP is a multi-layer perceptron module used in the Llama model.
479
+
480
+ Args:
481
+ config: The configuration for the MLP.
482
+
483
+ Attributes:
484
+ pretraining_tp (int): The pretraining time periods.
485
+ hidden_size (int): The size of the hidden layer.
486
+ intermediate_size (int): The size of the intermediate layer.
487
+ gate_proj (nn.Linear): The linear projection for gating.
488
+ up_proj (nn.Linear): The linear projection for the up projection.
489
+ down_proj (nn.Linear): The linear projection for the down projection.
490
+ act_fn: The activation function.
491
+
492
+ """
493
+
494
+ def __init__(self, config):
495
+ super().__init__()
496
+ self.pretraining_tp = config.pretraining_tp
497
+ self.hidden_size = config.hidden_size
498
+ self.intermediate_size = config.intermediate_size
499
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
500
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
501
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
502
+ self.act_fn = ACT2FN[config.hidden_act]
503
+
504
+ def forward(self, x):
505
+ """
506
+ Forward pass of the MLP.
507
+
508
+ Args:
509
+ x: Input tensor.
510
+
511
+ Returns:
512
+ torch.Tensor: Output tensor.
513
+ """
514
+ if self.pretraining_tp > 1:
515
+ slice = self.intermediate_size // self.pretraining_tp
516
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
517
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
518
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
519
+
520
+ gate_proj = torch.cat(
521
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.pretraining_tp)],
522
+ dim=-1,
523
+ )
524
+ up_proj = torch.cat(
525
+ [F.linear(x, up_proj_slices[i]) for i in range(self.pretraining_tp)],
526
+ dim=-1,
527
+ )
528
+
529
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
530
+ down_proj = [
531
+ F.linear(intermediate_states[i], down_proj_slices[i])
532
+ for i in range(self.pretraining_tp)
533
+ ]
534
+ down_proj = sum(down_proj)
535
+ else:
536
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
537
+
538
+ return down_proj
539
+
540
+
541
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
542
+ """
543
+ Repeat key and value tensors n times along the specified dimension.
544
+
545
+ Args:
546
+ hidden_states (torch.Tensor): Input tensor with shape (batch, num_key_value_heads, seqlen, head_dim).
547
+ n_rep (int): Number of times to repeat.
548
+
549
+ Returns:
550
+ torch.Tensor: Repeated tensor with shape (batch, num_key_value_heads * n_rep, seqlen, head_dim).
551
+ """
552
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
553
+ if n_rep == 1:
554
+ return hidden_states
555
+ hidden_states = hidden_states[:, :, None, :, :].expand(
556
+ batch, num_key_value_heads, n_rep, slen, head_dim
557
+ )
558
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
559
+
560
+
561
+ class LlamaAttention(nn.Module):
562
+ """
563
+ LlamaAttention is a multi-headed attention module based on the 'Attention Is All You Need' paper.
564
+
565
+ Args:
566
+ config (LlamaConfig): Configuration for the attention module.
567
+
568
+ Attributes:
569
+ config (LlamaConfig): Configuration for the attention module.
570
+ hidden_size (int): The size of the hidden layer.
571
+ num_heads (int): The number of attention heads.
572
+ head_dim (int): The dimension of each attention head.
573
+ num_key_value_heads (int): The number of key-value attention heads.
574
+ num_key_value_groups (int): The number of key-value groups.
575
+ pretraining_tp (int): The pretraining time periods.
576
+ max_position_embeddings (int): The maximum position embeddings.
577
+
578
+ """
579
+
580
+ def __init__(self, config: LlamaConfig):
581
+ super().__init__()
582
+ self.config = config
583
+ self.hidden_size = config.hidden_size
584
+ self.num_heads = config.num_attention_heads
585
+ self.head_dim = self.hidden_size // self.num_heads
586
+ self.num_key_value_heads = config.num_key_value_heads
587
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
588
+ self.pretraining_tp = config.pretraining_tp
589
+ self.max_position_embeddings = config.max_position_embeddings
590
+
591
+ if (self.head_dim * self.num_heads) != self.hidden_size:
592
+ raise ValueError(
593
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
594
+ f" and `num_heads`: {self.num_heads})."
595
+ )
596
+ self.q_proj = nn.Linear(
597
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
598
+ )
599
+ self.k_proj = nn.Linear(
600
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
601
+ )
602
+ self.v_proj = nn.Linear(
603
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False
604
+ )
605
+ self.o_proj = nn.Linear(
606
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
607
+ )
608
+ self._init_rope()
609
+
610
+ def _init_rope(self):
611
+ if self.config.rope_scaling is None:
612
+ self.rotary_emb = LlamaRotaryEmbedding(
613
+ self.head_dim, max_position_embeddings=self.max_position_embeddings, base=self.config.rope_theta
614
+ )
615
+ else:
616
+ try:
617
+ scaling_type = self.config.rope_scaling["type"]
618
+ scaling_factor = self.config.rope_scaling["factor"]
619
+ if scaling_type == "linear":
620
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
621
+ self.head_dim,
622
+ max_position_embeddings=self.max_position_embeddings,
623
+ scaling_factor=scaling_factor,
624
+ base=self.config.rope_theta,
625
+ )
626
+ elif scaling_type == "dynamic":
627
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
628
+ self.head_dim,
629
+ max_position_embeddings=self.max_position_embeddings,
630
+ scaling_factor=scaling_factor,
631
+ base=self.config.rope_theta,
632
+ )
633
+ else:
634
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
635
+ except:
636
+ print("For LLaMA 31")
637
+ self.rotary_emb = LlamaRotaryEmbedding_L31(config=self.config)
638
+
639
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
640
+ return (
641
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
642
+ .transpose(1, 2)
643
+ .contiguous()
644
+ )
645
+
646
+ def forward(
647
+ self,
648
+ hidden_states: torch.Tensor,
649
+ attention_mask: Optional[torch.Tensor] = None,
650
+ position_ids: Optional[torch.LongTensor] = None,
651
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
652
+ output_attentions: bool = False,
653
+ use_cache: bool = False,
654
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
655
+ bsz, q_len, _ = hidden_states.size()
656
+
657
+ if self.pretraining_tp > 1:
658
+ key_value_slicing = (
659
+ self.num_key_value_heads * self.head_dim
660
+ ) // self.pretraining_tp
661
+ query_slices = self.q_proj.weight.split(
662
+ (self.num_heads * self.head_dim) // self.pretraining_tp, dim=0
663
+ )
664
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
665
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
666
+
667
+ query_states = [
668
+ F.linear(hidden_states, query_slices[i])
669
+ for i in range(self.pretraining_tp)
670
+ ]
671
+ query_states = torch.cat(query_states, dim=-1)
672
+
673
+ key_states = [
674
+ F.linear(hidden_states, key_slices[i])
675
+ for i in range(self.pretraining_tp)
676
+ ]
677
+ key_states = torch.cat(key_states, dim=-1)
678
+
679
+ value_states = [
680
+ F.linear(hidden_states, value_slices[i])
681
+ for i in range(self.pretraining_tp)
682
+ ]
683
+ value_states = torch.cat(value_states, dim=-1)
684
+
685
+ else:
686
+ query_states = self.q_proj(hidden_states)
687
+ key_states = self.k_proj(hidden_states)
688
+ value_states = self.v_proj(hidden_states)
689
+
690
+ query_states = query_states.view(
691
+ bsz, q_len, self.num_heads, self.head_dim
692
+ ).transpose(1, 2)
693
+ key_states = key_states.view(
694
+ bsz, q_len, self.num_key_value_heads, self.head_dim
695
+ ).transpose(1, 2)
696
+ value_states = value_states.view(
697
+ bsz, q_len, self.num_key_value_heads, self.head_dim
698
+ ).transpose(1, 2)
699
+
700
+ kv_seq_len = key_states.shape[-2]
701
+ if past_key_value is not None:
702
+ kv_seq_len += past_key_value[0].shape[-2]
703
+ if isinstance(self.rotary_emb, LlamaRotaryEmbedding_L31):
704
+ cos, sin = self.rotary_emb(query_states,position_ids)
705
+ query_states, key_states = apply_rotary_pos_emb_L31(query_states, key_states, cos, sin)
706
+ else:
707
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
708
+ query_states, key_states = apply_rotary_pos_emb(
709
+ query_states, key_states, cos, sin, position_ids
710
+ )
711
+
712
+ # [MODIFIED] Using KVCache mechanism for preallocated GPU memory optimization
713
+ # past_key_value is utilized to leverage previously computed key and value states.
714
+ # If past_key_value is available, reuse the states for k, v, and self_attention.
715
+ if past_key_value is not None:
716
+ key_states = past_key_value[0].cat(key_states, dim=2)
717
+ value_states = past_key_value[1].cat(value_states, dim=2)
718
+ # Reset past_key_value to avoid return past_key_value.
719
+ past_key_value = None
720
+
721
+ # repeat k/v heads if n_kv_heads < n_heads
722
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
723
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
724
+
725
+ attn_weights = torch.matmul(
726
+ query_states, key_states.transpose(2, 3)
727
+ ) / math.sqrt(self.head_dim)
728
+
729
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
730
+ raise ValueError(
731
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
732
+ f" {attn_weights.size()}"
733
+ )
734
+
735
+ if attention_mask is not None:
736
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
737
+ raise ValueError(
738
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
739
+ )
740
+ attn_weights = attn_weights + attention_mask
741
+
742
+ # upcast attention to fp32
743
+ attn_weights = nn.functional.softmax(
744
+ attn_weights, dim=-1, dtype=torch.float32
745
+ ).to(query_states.dtype)
746
+ attn_output = torch.matmul(attn_weights, value_states)
747
+
748
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
749
+ raise ValueError(
750
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
751
+ f" {attn_output.size()}"
752
+ )
753
+
754
+ attn_output = attn_output.transpose(1, 2).contiguous()
755
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
756
+
757
+ if self.pretraining_tp > 1:
758
+ attn_output = attn_output.split(
759
+ self.hidden_size // self.pretraining_tp, dim=2
760
+ )
761
+ o_proj_slices = self.o_proj.weight.split(
762
+ self.hidden_size // self.pretraining_tp, dim=1
763
+ )
764
+ attn_output = sum(
765
+ [
766
+ F.linear(attn_output[i], o_proj_slices[i])
767
+ for i in range(self.pretraining_tp)
768
+ ]
769
+ )
770
+ else:
771
+ attn_output = self.o_proj(attn_output)
772
+
773
+ if not output_attentions:
774
+ attn_weights = None
775
+
776
+ return attn_output, attn_weights, past_key_value
777
+
778
+
779
+ class LlamaDecoderLayer(nn.Module):
780
+ """
781
+ LlamaDecoderLayer represents a single layer of the Llama decoder.
782
+
783
+ Args:
784
+ config (LlamaConfig): Configuration for the decoder layer.
785
+
786
+ Attributes:
787
+ hidden_size (int): The size of the hidden layer.
788
+ self_attn (LlamaAttention): Multi-headed self-attention module.
789
+ mlp (LlamaMLP): Multi-layer perceptron module.
790
+ input_layernorm (LlamaRMSNorm): Layer normalization for input.
791
+ post_attention_layernorm (LlamaRMSNorm): Layer normalization after self-attention.
792
+ """
793
+
794
+ def __init__(self, config: LlamaConfig):
795
+ super().__init__()
796
+ self.hidden_size = config.hidden_size
797
+ self.self_attn = LlamaAttention(config=config)
798
+ self.mlp = LlamaMLP(config)
799
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
800
+ self.post_attention_layernorm = LlamaRMSNorm(
801
+ config.hidden_size, eps=config.rms_norm_eps
802
+ )
803
+
804
+ def forward(
805
+ self,
806
+ hidden_states: torch.Tensor,
807
+ attention_mask: Optional[torch.Tensor] = None,
808
+ position_ids: Optional[torch.LongTensor] = None,
809
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
810
+ output_attentions: Optional[bool] = False,
811
+ use_cache: Optional[bool] = False,
812
+ ) -> Tuple[
813
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
814
+ ]:
815
+ """
816
+ Forward pass for the LlamaDecoderLayer.
817
+
818
+ Args:
819
+ hidden_states (torch.FloatTensor): Input tensor of shape `(batch, seq_len, embed_dim)`.
820
+ attention_mask (torch.FloatTensor, optional): Attention mask of size
821
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
822
+ position_ids (torch.LongTensor, optional): Positional IDs tensor.
823
+ past_key_value (Tuple[torch.FloatTensor], optional): Cached past key and value projection states.
824
+ output_attentions (bool, optional): Whether or not to return the attentions tensors of all attention layers.
825
+ use_cache (bool, optional): If set to `True`, `past_key_values` key-value states are returned and can be
826
+ used to speed up decoding.
827
+
828
+ Returns:
829
+ Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: Tuple containing:
830
+ - hidden_states (torch.FloatTensor): Output tensor.
831
+ - self_attn_weights (Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]): Self-attention weights if
832
+ `output_attentions` is `True`.
833
+ - present_key_value (Optional[Tuple[torch.FloatTensor]]): Cached key and value projection states if
834
+ `use_cache` is `True`.
835
+ """
836
+
837
+ residual = hidden_states
838
+
839
+ hidden_states = self.input_layernorm(hidden_states)
840
+
841
+ # Self Attention
842
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
843
+ hidden_states=hidden_states,
844
+ attention_mask=attention_mask,
845
+ position_ids=position_ids,
846
+ past_key_value=past_key_value,
847
+ output_attentions=output_attentions,
848
+ use_cache=use_cache,
849
+ )
850
+ hidden_states = residual + hidden_states
851
+
852
+ # Fully Connected
853
+ residual = hidden_states
854
+ hidden_states = self.post_attention_layernorm(hidden_states)
855
+ hidden_states = self.mlp(hidden_states)
856
+ hidden_states = residual + hidden_states
857
+
858
+ outputs = (hidden_states,)
859
+
860
+ if output_attentions:
861
+ outputs += (self_attn_weights,)
862
+
863
+ if use_cache:
864
+ outputs += (present_key_value,)
865
+
866
+ return outputs
867
+
868
+
869
+ LLAMA_START_DOCSTRING = r"""
870
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
871
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
872
+ etc.)
873
+
874
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
875
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
876
+ and behavior.
877
+
878
+ Parameters:
879
+ config ([`LlamaConfig`]):
880
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
881
+ load the weights associated with the model, only the configuration. Check out the
882
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
883
+ """
884
+
885
+
886
+ @add_start_docstrings(
887
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
888
+ LLAMA_START_DOCSTRING,
889
+ )
890
+ class LlamaPreTrainedModel(PreTrainedModel):
891
+ config_class = LlamaConfig
892
+ base_model_prefix = "model"
893
+ supports_gradient_checkpointing = True
894
+ _no_split_modules = ["LlamaDecoderLayer"]
895
+ _skip_keys_device_placement = "past_key_values"
896
+
897
+ def _init_weights(self, module):
898
+ std = self.config.initializer_range
899
+ if isinstance(module, nn.Linear):
900
+ module.weight.data.normal_(mean=0.0, std=std)
901
+ if module.bias is not None:
902
+ module.bias.data.zero_()
903
+ elif isinstance(module, nn.Embedding):
904
+ module.weight.data.normal_(mean=0.0, std=std)
905
+ if module.padding_idx is not None:
906
+ module.weight.data[module.padding_idx].zero_()
907
+
908
+ def _set_gradient_checkpointing(self, module, value=False):
909
+ if isinstance(module, LlamaModel):
910
+ module.gradient_checkpointing = value
911
+
912
+
913
+ LLAMA_INPUTS_DOCSTRING = r"""
914
+ Args:
915
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
916
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
917
+ it.
918
+
919
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
920
+ [`PreTrainedTokenizer.__call__`] for details.
921
+
922
+ [What are input IDs?](../glossary#input-ids)
923
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
924
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
925
+
926
+ - 1 for tokens that are **not masked**,
927
+ - 0 for tokens that are **masked**.
928
+
929
+ [What are attention masks?](../glossary#attention-mask)
930
+
931
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
932
+ [`PreTrainedTokenizer.__call__`] for details.
933
+
934
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
935
+ `past_key_values`).
936
+
937
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
938
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
939
+ information on the default strategy.
940
+
941
+ - 1 indicates the head is **not masked**,
942
+ - 0 indicates the head is **masked**.
943
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
944
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
945
+ config.n_positions - 1]`.
946
+
947
+ [What are position IDs?](../glossary#position-ids)
948
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
949
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
950
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
951
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
952
+
953
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
954
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
955
+
956
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
957
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
958
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
959
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
960
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
961
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
962
+ model's internal embedding lookup matrix.
963
+ use_cache (`bool`, *optional*):
964
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
965
+ `past_key_values`).
966
+ output_attentions (`bool`, *optional*):
967
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
968
+ tensors for more detail.
969
+ output_hidden_states (`bool`, *optional*):
970
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
971
+ more detail.
972
+ return_dict (`bool`, *optional*):
973
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
974
+ """
975
+
976
+
977
+ @add_start_docstrings(
978
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
979
+ LLAMA_START_DOCSTRING,
980
+ )
981
+ class LlamaModel(LlamaPreTrainedModel):
982
+ """
983
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
984
+
985
+ Args:
986
+ config: LlamaConfig
987
+ """
988
+
989
+ def __init__(self, config: LlamaConfig):
990
+ super().__init__(config)
991
+ self.padding_idx = config.pad_token_id
992
+ self.vocab_size = config.vocab_size
993
+
994
+ self.embed_tokens = nn.Embedding(
995
+ config.vocab_size, config.hidden_size, self.padding_idx
996
+ )
997
+ self.layers = nn.ModuleList(
998
+ [LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]
999
+ )
1000
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
1001
+
1002
+ self.gradient_checkpointing = False
1003
+ # Initialize weights and apply final processing
1004
+ self.post_init()
1005
+
1006
+ def get_input_embeddings(self):
1007
+ return self.embed_tokens
1008
+
1009
+ def set_input_embeddings(self, value):
1010
+ self.embed_tokens = value
1011
+
1012
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
1013
+ def _prepare_decoder_attention_mask(
1014
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
1015
+ ):
1016
+ # create causal mask
1017
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1018
+ combined_attention_mask = None
1019
+ if input_shape[-1] > 1:
1020
+ combined_attention_mask = _make_causal_mask(
1021
+ input_shape,
1022
+ # inputs_embeds.dtype,
1023
+ torch.float32, # [MODIFIED] force to cast to float32
1024
+ device=inputs_embeds.device,
1025
+ past_key_values_length=past_key_values_length,
1026
+ )
1027
+
1028
+ if attention_mask is not None:
1029
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1030
+ expanded_attn_mask = _expand_mask(
1031
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1032
+ ).to(inputs_embeds.device)
1033
+ combined_attention_mask = (
1034
+ expanded_attn_mask
1035
+ if combined_attention_mask is None
1036
+ else expanded_attn_mask + combined_attention_mask
1037
+ )
1038
+
1039
+ if hasattr(self, "tree_mask") and self.tree_mask is not None:
1040
+ tree_mask = self.tree_mask
1041
+ tree_len = tree_mask.size(-1)
1042
+ combined_attention_mask[:, :, -tree_len:, -tree_len:][
1043
+ tree_mask == 0
1044
+ ] = combined_attention_mask.min()
1045
+
1046
+ return combined_attention_mask
1047
+
1048
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1049
+ def forward(
1050
+ self,
1051
+ input_ids: torch.LongTensor = None,
1052
+ attention_mask: Optional[torch.Tensor] = None,
1053
+ position_ids: Optional[torch.LongTensor] = None,
1054
+ past_key_values=None, # [MODIFIED] past_key_value is KVCache class
1055
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1056
+ use_cache: Optional[bool] = None,
1057
+ output_attentions: Optional[bool] = None,
1058
+ output_hidden_states: Optional[bool] = None,
1059
+ return_dict: Optional[bool] = None,
1060
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
1061
+ output_attentions = (
1062
+ output_attentions
1063
+ if output_attentions is not None
1064
+ else self.config.output_attentions
1065
+ )
1066
+ output_hidden_states = (
1067
+ output_hidden_states
1068
+ if output_hidden_states is not None
1069
+ else self.config.output_hidden_states
1070
+ )
1071
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1072
+
1073
+ return_dict = (
1074
+ return_dict if return_dict is not None else self.config.use_return_dict
1075
+ )
1076
+
1077
+ # retrieve input_ids and inputs_embeds
1078
+ if input_ids is not None and inputs_embeds is not None:
1079
+ raise ValueError(
1080
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
1081
+ )
1082
+ elif input_ids is not None:
1083
+ batch_size, seq_length = input_ids.shape
1084
+ elif inputs_embeds is not None:
1085
+ batch_size, seq_length, _ = inputs_embeds.shape
1086
+ else:
1087
+ raise ValueError(
1088
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
1089
+ )
1090
+
1091
+ seq_length_with_past = seq_length
1092
+ past_key_values_length = 0
1093
+
1094
+ if past_key_values is not None:
1095
+ past_key_values_length = past_key_values[0][0].shape[2]
1096
+ seq_length_with_past = seq_length_with_past + past_key_values_length
1097
+
1098
+ if position_ids is None:
1099
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1100
+ position_ids = torch.arange(
1101
+ past_key_values_length,
1102
+ seq_length + past_key_values_length,
1103
+ dtype=torch.long,
1104
+ device=device,
1105
+ )
1106
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1107
+ else:
1108
+ position_ids = position_ids.view(-1, seq_length).long()
1109
+
1110
+ if inputs_embeds is None:
1111
+ inputs_embeds = self.embed_tokens(input_ids)
1112
+ # embed positions
1113
+ if attention_mask is None:
1114
+ attention_mask = torch.ones(
1115
+ (batch_size, seq_length_with_past),
1116
+ dtype=torch.bool,
1117
+ device=inputs_embeds.device,
1118
+ )
1119
+ attention_mask = self._prepare_decoder_attention_mask(
1120
+ attention_mask,
1121
+ (batch_size, seq_length),
1122
+ inputs_embeds,
1123
+ past_key_values_length,
1124
+ )
1125
+
1126
+ hidden_states = inputs_embeds
1127
+
1128
+ if self.gradient_checkpointing and self.training:
1129
+ if use_cache:
1130
+ logger.warning_once(
1131
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1132
+ )
1133
+ use_cache = False
1134
+
1135
+ # decoder layers
1136
+ all_hidden_states = () if 1 else None
1137
+ all_self_attns = () if output_attentions else None
1138
+ next_decoder_cache = () if use_cache else None
1139
+
1140
+ for idx, decoder_layer in enumerate(self.layers):
1141
+
1142
+ if idx==len(self.layers)-3 or idx==len(self.layers)//2 or idx==2:
1143
+ all_hidden_states += (hidden_states,)
1144
+
1145
+ past_key_value = (
1146
+ past_key_values[idx] if past_key_values is not None else None
1147
+ )
1148
+
1149
+ if self.gradient_checkpointing and self.training:
1150
+
1151
+ def create_custom_forward(module):
1152
+ def custom_forward(*inputs):
1153
+ # None for past_key_value
1154
+ return module(*inputs, output_attentions, None)
1155
+
1156
+ return custom_forward
1157
+
1158
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1159
+ create_custom_forward(decoder_layer),
1160
+ hidden_states,
1161
+ attention_mask,
1162
+ position_ids,
1163
+ None,
1164
+ )
1165
+ else:
1166
+ layer_outputs = decoder_layer(
1167
+ hidden_states,
1168
+ attention_mask=attention_mask,
1169
+ position_ids=position_ids,
1170
+ past_key_value=past_key_value,
1171
+ output_attentions=output_attentions,
1172
+ use_cache=use_cache,
1173
+ )
1174
+
1175
+ hidden_states = layer_outputs[0]
1176
+
1177
+ if use_cache:
1178
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1179
+
1180
+ if output_attentions:
1181
+ all_self_attns += (layer_outputs[1],)
1182
+
1183
+ hidden_states = self.norm(hidden_states)
1184
+
1185
+ # add hidden states from the last decoder layer
1186
+ if output_hidden_states:
1187
+ all_hidden_states += (hidden_states,)
1188
+
1189
+ # !!!
1190
+ # all_hidden_states += (hidden_states,)
1191
+
1192
+ next_cache = next_decoder_cache if use_cache else None
1193
+ if not return_dict:
1194
+ return tuple(
1195
+ v
1196
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1197
+ if v is not None
1198
+ )
1199
+ return BaseModelOutputWithPast(
1200
+ last_hidden_state=hidden_states,
1201
+ past_key_values=next_cache,
1202
+ hidden_states=all_hidden_states,
1203
+ attentions=all_self_attns,
1204
+ )
1205
+
1206
+
1207
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1208
+ _tied_weights_keys = ["lm_head.weight"]
1209
+
1210
+ def __init__(self, config):
1211
+ super().__init__(config)
1212
+ self.model = LlamaModel(config)
1213
+ self.pretraining_tp = config.pretraining_tp
1214
+ self.vocab_size = config.vocab_size
1215
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1216
+
1217
+ # Initialize weights and apply final processing
1218
+ self.post_init()
1219
+
1220
+ def get_input_embeddings(self):
1221
+ return self.model.embed_tokens
1222
+
1223
+ def set_input_embeddings(self, value):
1224
+ self.model.embed_tokens = value
1225
+
1226
+ def get_output_embeddings(self):
1227
+ return self.lm_head
1228
+
1229
+ def set_output_embeddings(self, new_embeddings):
1230
+ self.lm_head = new_embeddings
1231
+
1232
+ def set_decoder(self, decoder):
1233
+ self.model = decoder
1234
+
1235
+ def get_decoder(self):
1236
+ return self.model
1237
+
1238
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1239
+ @replace_return_docstrings(
1240
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1241
+ )
1242
+ def forward(
1243
+ self,
1244
+ input_ids: torch.LongTensor = None,
1245
+ attention_mask: Optional[torch.Tensor] = None,
1246
+ position_ids: Optional[torch.LongTensor] = None,
1247
+ past_key_values=None, # [MODIFIED] past_key_value is KVCache class
1248
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1249
+ labels: Optional[torch.LongTensor] = None,
1250
+ use_cache: Optional[bool] = None,
1251
+ output_attentions: Optional[bool] = None,
1252
+ output_hidden_states: Optional[bool] = None,
1253
+ return_dict: Optional[bool] = None,
1254
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1255
+ r"""
1256
+ Args:
1257
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1258
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1259
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1260
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1261
+
1262
+ Returns:
1263
+
1264
+ Example:
1265
+
1266
+ ```python
1267
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1268
+
1269
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1270
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1271
+
1272
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1273
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1274
+
1275
+ >>> # Generate
1276
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1277
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1278
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1279
+ ```"""
1280
+
1281
+ output_attentions = (
1282
+ output_attentions
1283
+ if output_attentions is not None
1284
+ else self.config.output_attentions
1285
+ )
1286
+ output_hidden_states = (
1287
+ output_hidden_states
1288
+ if output_hidden_states is not None
1289
+ else self.config.output_hidden_states
1290
+ )
1291
+ return_dict = (
1292
+ return_dict if return_dict is not None else self.config.use_return_dict
1293
+ )
1294
+
1295
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1296
+ outputs = self.model(
1297
+ input_ids=input_ids,
1298
+ attention_mask=attention_mask,
1299
+ position_ids=position_ids,
1300
+ past_key_values=past_key_values,
1301
+ inputs_embeds=inputs_embeds,
1302
+ use_cache=use_cache,
1303
+ output_attentions=output_attentions,
1304
+ output_hidden_states=output_hidden_states,
1305
+ return_dict=return_dict,
1306
+ )
1307
+
1308
+ hidden_states = outputs[0]
1309
+ if self.pretraining_tp > 1:
1310
+ lm_head_slices = self.lm_head.weight.split(
1311
+ self.vocab_size // self.pretraining_tp, dim=0
1312
+ )
1313
+ logits = [
1314
+ F.linear(hidden_states, lm_head_slices[i])
1315
+ for i in range(self.pretraining_tp)
1316
+ ]
1317
+ logits = torch.cat(logits, dim=-1)
1318
+ else:
1319
+ logits = self.lm_head(hidden_states)
1320
+ logits = logits.float()
1321
+
1322
+ loss = None
1323
+ if labels is not None:
1324
+ # Shift so that tokens < n predict n
1325
+ shift_logits = logits[..., :-1, :].contiguous()
1326
+ shift_labels = labels[..., 1:].contiguous()
1327
+ # Flatten the tokens
1328
+ loss_fct = CrossEntropyLoss()
1329
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1330
+ shift_labels = shift_labels.view(-1)
1331
+ # Enable model parallelism
1332
+ shift_labels = shift_labels.to(shift_logits.device)
1333
+ loss = loss_fct(shift_logits, shift_labels)
1334
+
1335
+ if not return_dict:
1336
+ output = (logits,) + outputs[1:]
1337
+ return (loss,) + output if loss is not None else output
1338
+
1339
+ return CausalLMOutputWithPast(
1340
+ loss=loss,
1341
+ logits=logits,
1342
+ past_key_values=outputs.past_key_values,
1343
+ hidden_states=outputs.hidden_states,
1344
+ attentions=outputs.attentions,
1345
+ )
1346
+
1347
+ def prepare_inputs_for_generation(
1348
+ self,
1349
+ input_ids,
1350
+ past_key_values=None,
1351
+ attention_mask=None,
1352
+ inputs_embeds=None,
1353
+ **kwargs,
1354
+ ):
1355
+ if past_key_values:
1356
+ input_ids = input_ids[:, -1:]
1357
+
1358
+ position_ids = kwargs.get("position_ids", None)
1359
+ if attention_mask is not None and position_ids is None:
1360
+ # create position_ids on the fly for batch generation
1361
+ position_ids = attention_mask.long().cumsum(-1) - 1
1362
+ position_ids.masked_fill_(attention_mask == 0, 1)
1363
+ if past_key_values:
1364
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1365
+
1366
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1367
+ if inputs_embeds is not None and past_key_values is None:
1368
+ model_inputs = {"inputs_embeds": inputs_embeds}
1369
+ else:
1370
+ model_inputs = {"input_ids": input_ids}
1371
+
1372
+ model_inputs.update(
1373
+ {
1374
+ "position_ids": position_ids,
1375
+ "past_key_values": past_key_values,
1376
+ "use_cache": kwargs.get("use_cache"),
1377
+ "attention_mask": attention_mask,
1378
+ }
1379
+ )
1380
+ return model_inputs
1381
+
1382
+ @staticmethod
1383
+ def _reorder_cache(past_key_values, beam_idx):
1384
+ reordered_past = ()
1385
+ for layer_past in past_key_values:
1386
+ reordered_past += (
1387
+ tuple(
1388
+ past_state.index_select(0, beam_idx.to(past_state.device))
1389
+ for past_state in layer_past
1390
+ ),
1391
+ )
1392
+ return reordered_past
1393
+
1394
+
1395
+ @add_start_docstrings(
1396
+ """
1397
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1398
+
1399
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1400
+ (e.g. GPT-2) do.
1401
+
1402
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1403
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1404
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1405
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1406
+ each row of the batch).
1407
+ """,
1408
+ LLAMA_START_DOCSTRING,
1409
+ )
1410
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1411
+ def __init__(self, config):
1412
+ super().__init__(config)
1413
+ self.num_labels = config.num_labels
1414
+ self.model = LlamaModel(config)
1415
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1416
+
1417
+ # Initialize weights and apply final processing
1418
+ self.post_init()
1419
+
1420
+ def get_input_embeddings(self):
1421
+ return self.model.embed_tokens
1422
+
1423
+ def set_input_embeddings(self, value):
1424
+ self.model.embed_tokens = value
1425
+
1426
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1427
+ def forward(
1428
+ self,
1429
+ input_ids: torch.LongTensor = None,
1430
+ attention_mask: Optional[torch.Tensor] = None,
1431
+ position_ids: Optional[torch.LongTensor] = None,
1432
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1433
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1434
+ labels: Optional[torch.LongTensor] = None,
1435
+ use_cache: Optional[bool] = None,
1436
+ output_attentions: Optional[bool] = None,
1437
+ output_hidden_states: Optional[bool] = None,
1438
+ return_dict: Optional[bool] = None,
1439
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1440
+ r"""
1441
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1442
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1443
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1444
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1445
+ """
1446
+ return_dict = (
1447
+ return_dict if return_dict is not None else self.config.use_return_dict
1448
+ )
1449
+
1450
+ transformer_outputs = self.model(
1451
+ input_ids,
1452
+ attention_mask=attention_mask,
1453
+ position_ids=position_ids,
1454
+ past_key_values=past_key_values,
1455
+ inputs_embeds=inputs_embeds,
1456
+ use_cache=use_cache,
1457
+ output_attentions=output_attentions,
1458
+ output_hidden_states=output_hidden_states,
1459
+ return_dict=return_dict,
1460
+ )
1461
+ hidden_states = transformer_outputs[0]
1462
+ logits = self.score(hidden_states)
1463
+
1464
+ if input_ids is not None:
1465
+ batch_size = input_ids.shape[0]
1466
+ else:
1467
+ batch_size = inputs_embeds.shape[0]
1468
+
1469
+ if self.config.pad_token_id is None and batch_size != 1:
1470
+ raise ValueError(
1471
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1472
+ )
1473
+ if self.config.pad_token_id is None:
1474
+ sequence_lengths = -1
1475
+ else:
1476
+ if input_ids is not None:
1477
+ sequence_lengths = (
1478
+ torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1479
+ ).to(logits.device)
1480
+ else:
1481
+ sequence_lengths = -1
1482
+
1483
+ pooled_logits = logits[
1484
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1485
+ ]
1486
+
1487
+ loss = None
1488
+ if labels is not None:
1489
+ labels = labels.to(logits.device)
1490
+ if self.config.problem_type is None:
1491
+ if self.num_labels == 1:
1492
+ self.config.problem_type = "regression"
1493
+ elif self.num_labels > 1 and (
1494
+ labels.dtype == torch.long or labels.dtype == torch.int
1495
+ ):
1496
+ self.config.problem_type = "single_label_classification"
1497
+ else:
1498
+ self.config.problem_type = "multi_label_classification"
1499
+
1500
+ if self.config.problem_type == "regression":
1501
+ loss_fct = MSELoss()
1502
+ if self.num_labels == 1:
1503
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1504
+ else:
1505
+ loss = loss_fct(pooled_logits, labels)
1506
+ elif self.config.problem_type == "single_label_classification":
1507
+ loss_fct = CrossEntropyLoss()
1508
+ loss = loss_fct(
1509
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1510
+ )
1511
+ elif self.config.problem_type == "multi_label_classification":
1512
+ loss_fct = BCEWithLogitsLoss()
1513
+ loss = loss_fct(pooled_logits, labels)
1514
+ if not return_dict:
1515
+ output = (pooled_logits,) + transformer_outputs[1:]
1516
+ return ((loss,) + output) if loss is not None else output
1517
+
1518
+ return SequenceClassifierOutputWithPast(
1519
+ loss=loss,
1520
+ logits=pooled_logits,
1521
+ past_key_values=transformer_outputs.past_key_values,
1522
+ hidden_states=transformer_outputs.hidden_states,
1523
+ attentions=transformer_outputs.attentions,
1524
+ )