dwzhu commited on
Commit
3876182
1 Parent(s): daa4934

Upload pose_modeling_llama.py with huggingface_hub

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