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