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