emozilla commited on
Commit
39956c6
1 Parent(s): 44b2926

Upload modeling_llama_yarn.py

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