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