Vily1998
commited on
Commit
•
2485ec4
1
Parent(s):
986fa9c
init
Browse files- ._tokenizer.json +0 -0
- config.json +33 -0
- configuration_llama.py +191 -0
- generation_config.json +10 -0
- modeling_llama.py +1517 -0
- pytorch_model-00001-of-00002.bin +3 -0
- pytorch_model-00002-of-00002.bin +3 -0
- pytorch_model.bin.index.json +330 -0
- special_tokens_map.json +23 -0
- tokenization_llama.py +472 -0
- tokenizer.json +0 -0
- tokenizer.model +3 -0
- tokenizer_config.json +35 -0
- truthx.py +332 -0
- truthx_model.pt +3 -0
._tokenizer.json
ADDED
Binary file (4.1 kB). View file
|
|
config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "ICTNLP/Llama-2-7b-chat-TruthX",
|
3 |
+
"architectures": [
|
4 |
+
"LlamaForCausalLM"
|
5 |
+
],
|
6 |
+
"auto_map": {
|
7 |
+
"AutoConfig": "configuration_llama.LlamaConfig",
|
8 |
+
"AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM",
|
9 |
+
"AutoModel": "modeling_llama.LlamaModel"
|
10 |
+
},
|
11 |
+
"bos_token_id": 1,
|
12 |
+
"eos_token_id": 2,
|
13 |
+
"hidden_act": "silu",
|
14 |
+
"hidden_size": 4096,
|
15 |
+
"initializer_range": 0.02,
|
16 |
+
"intermediate_size": 11008,
|
17 |
+
"max_position_embeddings": 4096,
|
18 |
+
"model_type": "llama",
|
19 |
+
"num_attention_heads": 32,
|
20 |
+
"num_hidden_layers": 32,
|
21 |
+
"num_key_value_heads": 32,
|
22 |
+
"pretraining_tp": 1,
|
23 |
+
"rms_norm_eps": 1e-06,
|
24 |
+
"rope_scaling": null,
|
25 |
+
"tie_word_embeddings": false,
|
26 |
+
"torch_dtype": "float16",
|
27 |
+
"transformers_version": "4.32.0.dev0",
|
28 |
+
"use_cache": true,
|
29 |
+
"vocab_size": 32000,
|
30 |
+
"truthx_config": {
|
31 |
+
"path":"truthx_model.pt"
|
32 |
+
}
|
33 |
+
}
|
configuration_llama.py
ADDED
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
25 |
+
|
26 |
+
logger = logging.get_logger(__name__)
|
27 |
+
|
28 |
+
LLAMA_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
|
29 |
+
|
30 |
+
|
31 |
+
class LlamaConfig(PretrainedConfig):
|
32 |
+
r"""
|
33 |
+
This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA
|
34 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
35 |
+
defaults will yield a similar configuration to that of the LLaMA-7B.
|
36 |
+
|
37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
38 |
+
documentation from [`PretrainedConfig`] for more information.
|
39 |
+
|
40 |
+
|
41 |
+
Args:
|
42 |
+
vocab_size (`int`, *optional*, defaults to 32000):
|
43 |
+
Vocabulary size of the LLaMA model. Defines the number of different tokens that can be represented by the
|
44 |
+
`inputs_ids` passed when calling [`LlamaModel`]
|
45 |
+
hidden_size (`int`, *optional*, defaults to 4096):
|
46 |
+
Dimension of the hidden representations.
|
47 |
+
intermediate_size (`int`, *optional*, defaults to 11008):
|
48 |
+
Dimension of the MLP representations.
|
49 |
+
num_hidden_layers (`int`, *optional*, defaults to 32):
|
50 |
+
Number of hidden layers in the Transformer decoder.
|
51 |
+
num_attention_heads (`int`, *optional*, defaults to 32):
|
52 |
+
Number of attention heads for each attention layer in the Transformer decoder.
|
53 |
+
num_key_value_heads (`int`, *optional*):
|
54 |
+
This is the number of key_value heads that should be used to implement Grouped Query Attention. If
|
55 |
+
`num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
|
56 |
+
`num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
|
57 |
+
converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
|
58 |
+
by meanpooling all the original heads within that group. For more details checkout [this
|
59 |
+
paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to
|
60 |
+
`num_attention_heads`.
|
61 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
|
62 |
+
The non-linear activation function (function or string) in the decoder.
|
63 |
+
max_position_embeddings (`int`, *optional*, defaults to 2048):
|
64 |
+
The maximum sequence length that this model might ever be used with. Llama 1 supports up to 2048 tokens,
|
65 |
+
Llama 2 up to 4096, CodeLlama up to 16384.
|
66 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
67 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
68 |
+
rms_norm_eps (`float`, *optional*, defaults to 1e-06):
|
69 |
+
The epsilon used by the rms normalization layers.
|
70 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
71 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
72 |
+
relevant if `config.is_decoder=True`.
|
73 |
+
pad_token_id (`int`, *optional*):
|
74 |
+
Padding token id.
|
75 |
+
bos_token_id (`int`, *optional*, defaults to 1):
|
76 |
+
Beginning of stream token id.
|
77 |
+
eos_token_id (`int`, *optional*, defaults to 2):
|
78 |
+
End of stream token id.
|
79 |
+
pretraining_tp (`int`, *optional*, defaults to 1):
|
80 |
+
Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
|
81 |
+
document](https://huggingface.co/docs/transformers/parallelism) to understand more about it. This value is
|
82 |
+
necessary to ensure exact reproducibility of the pretraining results. Please refer to [this
|
83 |
+
issue](https://github.com/pytorch/pytorch/issues/76232).
|
84 |
+
tie_word_embeddings (`bool`, *optional*, defaults to `False`):
|
85 |
+
Whether to tie weight embeddings
|
86 |
+
rope_theta (`float`, *optional*, defaults to 10000.0):
|
87 |
+
The base period of the RoPE embeddings.
|
88 |
+
rope_scaling (`Dict`, *optional*):
|
89 |
+
Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
|
90 |
+
strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
|
91 |
+
`{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
|
92 |
+
`max_position_embeddings` to the expected new maximum. See the following thread for more information on how
|
93 |
+
these scaling strategies behave:
|
94 |
+
https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
|
95 |
+
experimental feature, subject to breaking API changes in future versions.
|
96 |
+
attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`):
|
97 |
+
Whether to use a bias in the query, key, value and output projection layers during self-attention.
|
98 |
+
attention_dropout (`float`, *optional*, defaults to 0.0):
|
99 |
+
The dropout ratio for the attention probabilities.
|
100 |
+
|
101 |
+
```python
|
102 |
+
>>> from transformers import LlamaModel, LlamaConfig
|
103 |
+
|
104 |
+
>>> # Initializing a LLaMA llama-7b style configuration
|
105 |
+
>>> configuration = LlamaConfig()
|
106 |
+
|
107 |
+
>>> # Initializing a model from the llama-7b style configuration
|
108 |
+
>>> model = LlamaModel(configuration)
|
109 |
+
|
110 |
+
>>> # Accessing the model configuration
|
111 |
+
>>> configuration = model.config
|
112 |
+
```"""
|
113 |
+
|
114 |
+
model_type = "llama"
|
115 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
116 |
+
|
117 |
+
def __init__(
|
118 |
+
self,
|
119 |
+
vocab_size=32000,
|
120 |
+
hidden_size=4096,
|
121 |
+
intermediate_size=11008,
|
122 |
+
num_hidden_layers=32,
|
123 |
+
num_attention_heads=32,
|
124 |
+
num_key_value_heads=None,
|
125 |
+
hidden_act="silu",
|
126 |
+
max_position_embeddings=2048,
|
127 |
+
initializer_range=0.02,
|
128 |
+
rms_norm_eps=1e-6,
|
129 |
+
use_cache=True,
|
130 |
+
pad_token_id=None,
|
131 |
+
bos_token_id=1,
|
132 |
+
eos_token_id=2,
|
133 |
+
pretraining_tp=1,
|
134 |
+
tie_word_embeddings=False,
|
135 |
+
rope_theta=10000.0,
|
136 |
+
rope_scaling=None,
|
137 |
+
attention_bias=False,
|
138 |
+
attention_dropout=0.0,
|
139 |
+
**kwargs,
|
140 |
+
):
|
141 |
+
self.vocab_size = vocab_size
|
142 |
+
self.max_position_embeddings = max_position_embeddings
|
143 |
+
self.hidden_size = hidden_size
|
144 |
+
self.intermediate_size = intermediate_size
|
145 |
+
self.num_hidden_layers = num_hidden_layers
|
146 |
+
self.num_attention_heads = num_attention_heads
|
147 |
+
|
148 |
+
# for backward compatibility
|
149 |
+
if num_key_value_heads is None:
|
150 |
+
num_key_value_heads = num_attention_heads
|
151 |
+
|
152 |
+
self.num_key_value_heads = num_key_value_heads
|
153 |
+
self.hidden_act = hidden_act
|
154 |
+
self.initializer_range = initializer_range
|
155 |
+
self.rms_norm_eps = rms_norm_eps
|
156 |
+
self.pretraining_tp = pretraining_tp
|
157 |
+
self.use_cache = use_cache
|
158 |
+
self.rope_theta = rope_theta
|
159 |
+
self.rope_scaling = rope_scaling
|
160 |
+
self._rope_scaling_validation()
|
161 |
+
self.attention_bias = attention_bias
|
162 |
+
self.attention_dropout = attention_dropout
|
163 |
+
|
164 |
+
super().__init__(
|
165 |
+
pad_token_id=pad_token_id,
|
166 |
+
bos_token_id=bos_token_id,
|
167 |
+
eos_token_id=eos_token_id,
|
168 |
+
tie_word_embeddings=tie_word_embeddings,
|
169 |
+
**kwargs,
|
170 |
+
)
|
171 |
+
|
172 |
+
def _rope_scaling_validation(self):
|
173 |
+
"""
|
174 |
+
Validate the `rope_scaling` configuration.
|
175 |
+
"""
|
176 |
+
if self.rope_scaling is None:
|
177 |
+
return
|
178 |
+
|
179 |
+
if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
|
180 |
+
raise ValueError(
|
181 |
+
"`rope_scaling` must be a dictionary with with two fields, `type` and `factor`, "
|
182 |
+
f"got {self.rope_scaling}"
|
183 |
+
)
|
184 |
+
rope_scaling_type = self.rope_scaling.get("type", None)
|
185 |
+
rope_scaling_factor = self.rope_scaling.get("factor", None)
|
186 |
+
if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
|
187 |
+
raise ValueError(
|
188 |
+
f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
|
189 |
+
)
|
190 |
+
if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
|
191 |
+
raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
|
generation_config.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token_id": 1,
|
3 |
+
"do_sample": true,
|
4 |
+
"eos_token_id": 2,
|
5 |
+
"max_length": 4096,
|
6 |
+
"pad_token_id": 0,
|
7 |
+
"temperature": 0.6,
|
8 |
+
"top_p": 0.9,
|
9 |
+
"transformers_version": "4.32.0.dev0"
|
10 |
+
}
|
modeling_llama.py
ADDED
@@ -0,0 +1,1517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
import warnings
|
23 |
+
from typing import List, Optional, Tuple, Union
|
24 |
+
|
25 |
+
import torch
|
26 |
+
import torch.nn.functional as F
|
27 |
+
import torch.utils.checkpoint
|
28 |
+
from torch import nn
|
29 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
30 |
+
|
31 |
+
from transformers.activations import ACT2FN
|
32 |
+
from transformers.cache_utils import Cache, DynamicCache
|
33 |
+
from transformers.modeling_attn_mask_utils import (
|
34 |
+
AttentionMaskConverter,
|
35 |
+
_prepare_4d_attention_mask,
|
36 |
+
_prepare_4d_causal_attention_mask,
|
37 |
+
_prepare_4d_causal_attention_mask_for_sdpa,
|
38 |
+
)
|
39 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
|
40 |
+
from transformers.modeling_utils import PreTrainedModel
|
41 |
+
from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
|
42 |
+
from transformers.utils import (
|
43 |
+
add_start_docstrings,
|
44 |
+
add_start_docstrings_to_model_forward,
|
45 |
+
# is_flash_attn_2_available,
|
46 |
+
# is_flash_attn_greater_or_equal_2_10,
|
47 |
+
logging,
|
48 |
+
replace_return_docstrings,
|
49 |
+
)
|
50 |
+
from transformers.utils.import_utils import is_torch_fx_available
|
51 |
+
from .configuration_llama import LlamaConfig
|
52 |
+
|
53 |
+
from .truthx import TruthX,MLPAE
|
54 |
+
|
55 |
+
|
56 |
+
# if is_flash_attn_2_available():
|
57 |
+
# from flash_attn import flash_attn_func, flash_attn_varlen_func
|
58 |
+
# from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
|
59 |
+
|
60 |
+
|
61 |
+
# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
|
62 |
+
# It means that the function will not be traced through and simply appear as a node in the graph.
|
63 |
+
if is_torch_fx_available():
|
64 |
+
if not is_torch_greater_or_equal_than_1_13:
|
65 |
+
import torch.fx
|
66 |
+
|
67 |
+
_prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
|
68 |
+
|
69 |
+
|
70 |
+
logger = logging.get_logger(__name__)
|
71 |
+
|
72 |
+
_CONFIG_FOR_DOC = "LlamaConfig"
|
73 |
+
|
74 |
+
|
75 |
+
def _get_unpad_data(attention_mask):
|
76 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
77 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
78 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
79 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
80 |
+
return (
|
81 |
+
indices,
|
82 |
+
cu_seqlens,
|
83 |
+
max_seqlen_in_batch,
|
84 |
+
)
|
85 |
+
|
86 |
+
|
87 |
+
def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
|
88 |
+
warnings.warn(
|
89 |
+
"Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
|
90 |
+
)
|
91 |
+
return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
|
92 |
+
|
93 |
+
|
94 |
+
def _make_causal_mask(
|
95 |
+
input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
|
96 |
+
):
|
97 |
+
warnings.warn(
|
98 |
+
"Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
|
99 |
+
)
|
100 |
+
return AttentionMaskConverter._make_causal_mask(
|
101 |
+
input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
|
102 |
+
)
|
103 |
+
|
104 |
+
class LlamaRMSNorm(nn.Module):
|
105 |
+
def __init__(self, hidden_size, eps=1e-6):
|
106 |
+
"""
|
107 |
+
LlamaRMSNorm is equivalent to T5LayerNorm
|
108 |
+
"""
|
109 |
+
super().__init__()
|
110 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
111 |
+
self.variance_epsilon = eps
|
112 |
+
|
113 |
+
def forward(self, hidden_states):
|
114 |
+
input_dtype = hidden_states.dtype
|
115 |
+
hidden_states = hidden_states.to(torch.float32)
|
116 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
117 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
118 |
+
return self.weight * hidden_states.to(input_dtype)
|
119 |
+
|
120 |
+
|
121 |
+
ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
|
122 |
+
|
123 |
+
|
124 |
+
class LlamaRotaryEmbedding(nn.Module):
|
125 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
|
126 |
+
super().__init__()
|
127 |
+
|
128 |
+
self.dim = dim
|
129 |
+
self.max_position_embeddings = max_position_embeddings
|
130 |
+
self.base = base
|
131 |
+
inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
132 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
133 |
+
|
134 |
+
# Build here to make `torch.jit.trace` work.
|
135 |
+
self._set_cos_sin_cache(
|
136 |
+
seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
|
137 |
+
)
|
138 |
+
|
139 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
140 |
+
self.max_seq_len_cached = seq_len
|
141 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
142 |
+
|
143 |
+
freqs = torch.outer(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().to(dtype), persistent=False)
|
147 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
148 |
+
|
149 |
+
def forward(self, x, seq_len=None):
|
150 |
+
# x: [bs, num_attention_heads, seq_len, head_size]
|
151 |
+
if seq_len > self.max_seq_len_cached:
|
152 |
+
self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
|
153 |
+
|
154 |
+
return (
|
155 |
+
self.cos_cached[:seq_len].to(dtype=x.dtype),
|
156 |
+
self.sin_cached[:seq_len].to(dtype=x.dtype),
|
157 |
+
)
|
158 |
+
|
159 |
+
|
160 |
+
class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
161 |
+
"""LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
|
162 |
+
|
163 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
164 |
+
self.scaling_factor = scaling_factor
|
165 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
166 |
+
|
167 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
168 |
+
self.max_seq_len_cached = seq_len
|
169 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
170 |
+
t = t / self.scaling_factor
|
171 |
+
|
172 |
+
freqs = torch.outer(t, self.inv_freq)
|
173 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
174 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
175 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
176 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
177 |
+
|
178 |
+
|
179 |
+
class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
|
180 |
+
"""LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
|
181 |
+
|
182 |
+
def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
|
183 |
+
self.scaling_factor = scaling_factor
|
184 |
+
super().__init__(dim, max_position_embeddings, base, device)
|
185 |
+
|
186 |
+
def _set_cos_sin_cache(self, seq_len, device, dtype):
|
187 |
+
self.max_seq_len_cached = seq_len
|
188 |
+
|
189 |
+
if seq_len > self.max_position_embeddings:
|
190 |
+
base = self.base * (
|
191 |
+
(self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
|
192 |
+
) ** (self.dim / (self.dim - 2))
|
193 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
|
194 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
195 |
+
|
196 |
+
t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
|
197 |
+
|
198 |
+
freqs = torch.outer(t, self.inv_freq)
|
199 |
+
# Different from paper, but it uses a different permutation in order to obtain the same calculation
|
200 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
201 |
+
self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
|
202 |
+
self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
|
203 |
+
|
204 |
+
|
205 |
+
def rotate_half(x):
|
206 |
+
"""Rotates half the hidden dims of the input."""
|
207 |
+
x1 = x[..., : x.shape[-1] // 2]
|
208 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
209 |
+
return torch.cat((-x2, x1), dim=-1)
|
210 |
+
|
211 |
+
|
212 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
|
213 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
214 |
+
|
215 |
+
Args:
|
216 |
+
q (`torch.Tensor`): The query tensor.
|
217 |
+
k (`torch.Tensor`): The key tensor.
|
218 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
219 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
220 |
+
position_ids (`torch.Tensor`):
|
221 |
+
The position indices of the tokens corresponding to the query and key tensors. For example, this can be
|
222 |
+
used to pass offsetted position ids when working with a KV-cache.
|
223 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
224 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
225 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
226 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
227 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
228 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
229 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
230 |
+
Returns:
|
231 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
232 |
+
"""
|
233 |
+
cos = cos[position_ids].unsqueeze(unsqueeze_dim)
|
234 |
+
sin = sin[position_ids].unsqueeze(unsqueeze_dim)
|
235 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
236 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
237 |
+
return q_embed, k_embed
|
238 |
+
|
239 |
+
|
240 |
+
class LlamaMLP(nn.Module):
|
241 |
+
def __init__(self, config):
|
242 |
+
super().__init__()
|
243 |
+
self.config = config
|
244 |
+
self.hidden_size = config.hidden_size
|
245 |
+
self.intermediate_size = config.intermediate_size
|
246 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
247 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
248 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
249 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
250 |
+
|
251 |
+
def forward(self, x):
|
252 |
+
if self.config.pretraining_tp > 1:
|
253 |
+
slice = self.intermediate_size // self.config.pretraining_tp
|
254 |
+
gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
|
255 |
+
up_proj_slices = self.up_proj.weight.split(slice, dim=0)
|
256 |
+
down_proj_slices = self.down_proj.weight.split(slice, dim=1)
|
257 |
+
|
258 |
+
gate_proj = torch.cat(
|
259 |
+
[F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
|
260 |
+
)
|
261 |
+
up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
|
262 |
+
|
263 |
+
intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
|
264 |
+
down_proj = [
|
265 |
+
F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
|
266 |
+
]
|
267 |
+
down_proj = sum(down_proj)
|
268 |
+
else:
|
269 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
270 |
+
|
271 |
+
return down_proj
|
272 |
+
|
273 |
+
|
274 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
275 |
+
"""
|
276 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
277 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
278 |
+
"""
|
279 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
280 |
+
if n_rep == 1:
|
281 |
+
return hidden_states
|
282 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
283 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
284 |
+
|
285 |
+
|
286 |
+
class LlamaAttention(nn.Module):
|
287 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
288 |
+
|
289 |
+
def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
|
290 |
+
super().__init__()
|
291 |
+
self.config = config
|
292 |
+
self.layer_idx = layer_idx
|
293 |
+
if layer_idx is None:
|
294 |
+
logger.warning_once(
|
295 |
+
f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
|
296 |
+
"lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
|
297 |
+
"when creating this class."
|
298 |
+
)
|
299 |
+
|
300 |
+
self.attention_dropout = config.attention_dropout
|
301 |
+
self.hidden_size = config.hidden_size
|
302 |
+
self.num_heads = config.num_attention_heads
|
303 |
+
self.head_dim = self.hidden_size // self.num_heads
|
304 |
+
self.num_key_value_heads = config.num_key_value_heads
|
305 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
306 |
+
self.max_position_embeddings = config.max_position_embeddings
|
307 |
+
self.rope_theta = config.rope_theta
|
308 |
+
self.is_causal = True
|
309 |
+
|
310 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
311 |
+
raise ValueError(
|
312 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
313 |
+
f" and `num_heads`: {self.num_heads})."
|
314 |
+
)
|
315 |
+
|
316 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
317 |
+
self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
318 |
+
self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
319 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
320 |
+
self._init_rope()
|
321 |
+
|
322 |
+
def _init_rope(self):
|
323 |
+
if self.config.rope_scaling is None:
|
324 |
+
self.rotary_emb = LlamaRotaryEmbedding(
|
325 |
+
self.head_dim,
|
326 |
+
max_position_embeddings=self.max_position_embeddings,
|
327 |
+
base=self.rope_theta,
|
328 |
+
)
|
329 |
+
else:
|
330 |
+
scaling_type = self.config.rope_scaling["type"]
|
331 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
332 |
+
if scaling_type == "linear":
|
333 |
+
self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
|
334 |
+
self.head_dim,
|
335 |
+
max_position_embeddings=self.max_position_embeddings,
|
336 |
+
scaling_factor=scaling_factor,
|
337 |
+
base=self.rope_theta,
|
338 |
+
)
|
339 |
+
elif scaling_type == "dynamic":
|
340 |
+
self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
|
341 |
+
self.head_dim,
|
342 |
+
max_position_embeddings=self.max_position_embeddings,
|
343 |
+
scaling_factor=scaling_factor,
|
344 |
+
base=self.rope_theta,
|
345 |
+
)
|
346 |
+
else:
|
347 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
348 |
+
|
349 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
350 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
351 |
+
|
352 |
+
def forward(
|
353 |
+
self,
|
354 |
+
hidden_states: torch.Tensor,
|
355 |
+
attention_mask: Optional[torch.Tensor] = None,
|
356 |
+
position_ids: Optional[torch.LongTensor] = None,
|
357 |
+
past_key_value: Optional[Cache] = None,
|
358 |
+
output_attentions: bool = False,
|
359 |
+
use_cache: bool = False,
|
360 |
+
truthx_model=None,
|
361 |
+
**kwargs,
|
362 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
363 |
+
if "padding_mask" in kwargs:
|
364 |
+
warnings.warn(
|
365 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
366 |
+
)
|
367 |
+
|
368 |
+
bsz, q_len, _ = hidden_states.size()
|
369 |
+
|
370 |
+
if self.config.pretraining_tp > 1:
|
371 |
+
key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
|
372 |
+
query_slices = self.q_proj.weight.split(
|
373 |
+
(self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
|
374 |
+
)
|
375 |
+
key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
|
376 |
+
value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
|
377 |
+
|
378 |
+
query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
|
379 |
+
query_states = torch.cat(query_states, dim=-1)
|
380 |
+
|
381 |
+
key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
|
382 |
+
key_states = torch.cat(key_states, dim=-1)
|
383 |
+
|
384 |
+
value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
|
385 |
+
value_states = torch.cat(value_states, dim=-1)
|
386 |
+
|
387 |
+
else:
|
388 |
+
query_states = self.q_proj(hidden_states)
|
389 |
+
key_states = self.k_proj(hidden_states)
|
390 |
+
value_states = self.v_proj(hidden_states)
|
391 |
+
|
392 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
393 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
394 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
395 |
+
|
396 |
+
kv_seq_len = key_states.shape[-2]
|
397 |
+
if past_key_value is not None:
|
398 |
+
if self.layer_idx is None:
|
399 |
+
raise ValueError(
|
400 |
+
f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
|
401 |
+
"for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
|
402 |
+
"with a layer index."
|
403 |
+
)
|
404 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
405 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
406 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
407 |
+
|
408 |
+
if past_key_value is not None:
|
409 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
410 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
411 |
+
|
412 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
413 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
414 |
+
|
415 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
416 |
+
|
417 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
418 |
+
raise ValueError(
|
419 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
420 |
+
f" {attn_weights.size()}"
|
421 |
+
)
|
422 |
+
|
423 |
+
if attention_mask is not None:
|
424 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
425 |
+
raise ValueError(
|
426 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
427 |
+
)
|
428 |
+
attn_weights = attn_weights + attention_mask
|
429 |
+
|
430 |
+
# upcast attention to fp32
|
431 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
432 |
+
attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
|
433 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
434 |
+
|
435 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
436 |
+
raise ValueError(
|
437 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
438 |
+
f" {attn_output.size()}"
|
439 |
+
)
|
440 |
+
|
441 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
442 |
+
|
443 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
444 |
+
|
445 |
+
#################
|
446 |
+
## TruthX Code ##
|
447 |
+
#################
|
448 |
+
_attn_output=attn_output.contiguous()
|
449 |
+
# truthx
|
450 |
+
if truthx_model is not None:
|
451 |
+
attn_output=truthx_model.edit(attn_output)
|
452 |
+
|
453 |
+
|
454 |
+
if self.config.pretraining_tp > 1:
|
455 |
+
attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
|
456 |
+
o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
|
457 |
+
attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
|
458 |
+
else:
|
459 |
+
attn_output = self.o_proj(attn_output)
|
460 |
+
|
461 |
+
if not output_attentions:
|
462 |
+
attn_weights = None
|
463 |
+
|
464 |
+
return attn_output, attn_weights, past_key_value,_attn_output
|
465 |
+
|
466 |
+
|
467 |
+
class LlamaFlashAttention2(LlamaAttention):
|
468 |
+
"""
|
469 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
470 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
471 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
472 |
+
"""
|
473 |
+
|
474 |
+
def __init__(self, *args, **kwargs):
|
475 |
+
super().__init__(*args, **kwargs)
|
476 |
+
|
477 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
478 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
479 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
480 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
481 |
+
|
482 |
+
def forward(
|
483 |
+
self,
|
484 |
+
hidden_states: torch.Tensor,
|
485 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
486 |
+
position_ids: Optional[torch.LongTensor] = None,
|
487 |
+
past_key_value: Optional[Cache] = None,
|
488 |
+
output_attentions: bool = False,
|
489 |
+
use_cache: bool = False,
|
490 |
+
**kwargs,
|
491 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
492 |
+
# LlamaFlashAttention2 attention does not support output_attentions
|
493 |
+
if "padding_mask" in kwargs:
|
494 |
+
warnings.warn(
|
495 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
496 |
+
)
|
497 |
+
|
498 |
+
# overwrite attention_mask with padding_mask
|
499 |
+
attention_mask = kwargs.pop("padding_mask")
|
500 |
+
|
501 |
+
output_attentions = False
|
502 |
+
|
503 |
+
bsz, q_len, _ = hidden_states.size()
|
504 |
+
|
505 |
+
query_states = self.q_proj(hidden_states)
|
506 |
+
key_states = self.k_proj(hidden_states)
|
507 |
+
value_states = self.v_proj(hidden_states)
|
508 |
+
|
509 |
+
# Flash attention requires the input to have the shape
|
510 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
511 |
+
# therefore we just need to keep the original shape
|
512 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
513 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
514 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
515 |
+
|
516 |
+
kv_seq_len = key_states.shape[-2]
|
517 |
+
if past_key_value is not None:
|
518 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
519 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
520 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
521 |
+
|
522 |
+
if past_key_value is not None:
|
523 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
524 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
525 |
+
|
526 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
527 |
+
# to be able to avoid many of these transpose/reshape/view.
|
528 |
+
query_states = query_states.transpose(1, 2)
|
529 |
+
key_states = key_states.transpose(1, 2)
|
530 |
+
value_states = value_states.transpose(1, 2)
|
531 |
+
|
532 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
533 |
+
|
534 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
535 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
536 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
537 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
538 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
539 |
+
|
540 |
+
input_dtype = query_states.dtype
|
541 |
+
if input_dtype == torch.float32:
|
542 |
+
if torch.is_autocast_enabled():
|
543 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
544 |
+
# Handle the case where the model is quantized
|
545 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
546 |
+
target_dtype = self.config._pre_quantization_dtype
|
547 |
+
else:
|
548 |
+
target_dtype = self.q_proj.weight.dtype
|
549 |
+
|
550 |
+
logger.warning_once(
|
551 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
552 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
553 |
+
f" {target_dtype}."
|
554 |
+
)
|
555 |
+
|
556 |
+
query_states = query_states.to(target_dtype)
|
557 |
+
key_states = key_states.to(target_dtype)
|
558 |
+
value_states = value_states.to(target_dtype)
|
559 |
+
|
560 |
+
attn_output = self._flash_attention_forward(
|
561 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
562 |
+
)
|
563 |
+
|
564 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
565 |
+
attn_output = self.o_proj(attn_output)
|
566 |
+
|
567 |
+
if not output_attentions:
|
568 |
+
attn_weights = None
|
569 |
+
|
570 |
+
return attn_output, attn_weights, past_key_value
|
571 |
+
|
572 |
+
def _flash_attention_forward(
|
573 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
574 |
+
):
|
575 |
+
"""
|
576 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
577 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
578 |
+
|
579 |
+
Args:
|
580 |
+
query_states (`torch.Tensor`):
|
581 |
+
Input query states to be passed to Flash Attention API
|
582 |
+
key_states (`torch.Tensor`):
|
583 |
+
Input key states to be passed to Flash Attention API
|
584 |
+
value_states (`torch.Tensor`):
|
585 |
+
Input value states to be passed to Flash Attention API
|
586 |
+
attention_mask (`torch.Tensor`):
|
587 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
588 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
589 |
+
dropout (`int`, *optional*):
|
590 |
+
Attention dropout
|
591 |
+
softmax_scale (`float`, *optional*):
|
592 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
593 |
+
"""
|
594 |
+
if not self._flash_attn_uses_top_left_mask:
|
595 |
+
causal = self.is_causal
|
596 |
+
else:
|
597 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
598 |
+
causal = self.is_causal and query_length != 1
|
599 |
+
|
600 |
+
# Contains at least one padding token in the sequence
|
601 |
+
if attention_mask is not None:
|
602 |
+
batch_size = query_states.shape[0]
|
603 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
604 |
+
query_states, key_states, value_states, attention_mask, query_length
|
605 |
+
)
|
606 |
+
|
607 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
608 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
609 |
+
|
610 |
+
attn_output_unpad = flash_attn_varlen_func(
|
611 |
+
query_states,
|
612 |
+
key_states,
|
613 |
+
value_states,
|
614 |
+
cu_seqlens_q=cu_seqlens_q,
|
615 |
+
cu_seqlens_k=cu_seqlens_k,
|
616 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
617 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
618 |
+
dropout_p=dropout,
|
619 |
+
softmax_scale=softmax_scale,
|
620 |
+
causal=causal,
|
621 |
+
)
|
622 |
+
|
623 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
624 |
+
else:
|
625 |
+
attn_output = flash_attn_func(
|
626 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
627 |
+
)
|
628 |
+
|
629 |
+
return attn_output
|
630 |
+
|
631 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
632 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
633 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
634 |
+
|
635 |
+
key_layer = index_first_axis(
|
636 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
637 |
+
)
|
638 |
+
value_layer = index_first_axis(
|
639 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
640 |
+
)
|
641 |
+
if query_length == kv_seq_len:
|
642 |
+
query_layer = index_first_axis(
|
643 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
644 |
+
)
|
645 |
+
cu_seqlens_q = cu_seqlens_k
|
646 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
647 |
+
indices_q = indices_k
|
648 |
+
elif query_length == 1:
|
649 |
+
max_seqlen_in_batch_q = 1
|
650 |
+
cu_seqlens_q = torch.arange(
|
651 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
652 |
+
) # There is a memcpy here, that is very bad.
|
653 |
+
indices_q = cu_seqlens_q[:-1]
|
654 |
+
query_layer = query_layer.squeeze(1)
|
655 |
+
else:
|
656 |
+
# The -q_len: slice assumes left padding.
|
657 |
+
attention_mask = attention_mask[:, -query_length:]
|
658 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
659 |
+
|
660 |
+
return (
|
661 |
+
query_layer,
|
662 |
+
key_layer,
|
663 |
+
value_layer,
|
664 |
+
indices_q,
|
665 |
+
(cu_seqlens_q, cu_seqlens_k),
|
666 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
667 |
+
)
|
668 |
+
|
669 |
+
|
670 |
+
class LlamaSdpaAttention(LlamaAttention):
|
671 |
+
"""
|
672 |
+
Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
673 |
+
`LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
674 |
+
SDPA API.
|
675 |
+
"""
|
676 |
+
|
677 |
+
# Adapted from LlamaAttention.forward
|
678 |
+
def forward(
|
679 |
+
self,
|
680 |
+
hidden_states: torch.Tensor,
|
681 |
+
attention_mask: Optional[torch.Tensor] = None,
|
682 |
+
position_ids: Optional[torch.LongTensor] = None,
|
683 |
+
past_key_value: Optional[Cache] = None,
|
684 |
+
output_attentions: bool = False,
|
685 |
+
use_cache: bool = False,
|
686 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
687 |
+
if output_attentions:
|
688 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
689 |
+
logger.warning_once(
|
690 |
+
"LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
691 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
692 |
+
)
|
693 |
+
return super().forward(
|
694 |
+
hidden_states=hidden_states,
|
695 |
+
attention_mask=attention_mask,
|
696 |
+
position_ids=position_ids,
|
697 |
+
past_key_value=past_key_value,
|
698 |
+
output_attentions=output_attentions,
|
699 |
+
use_cache=use_cache,
|
700 |
+
)
|
701 |
+
|
702 |
+
bsz, q_len, _ = hidden_states.size()
|
703 |
+
|
704 |
+
query_states = self.q_proj(hidden_states)
|
705 |
+
key_states = self.k_proj(hidden_states)
|
706 |
+
value_states = self.v_proj(hidden_states)
|
707 |
+
|
708 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
709 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
710 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
711 |
+
|
712 |
+
kv_seq_len = key_states.shape[-2]
|
713 |
+
if past_key_value is not None:
|
714 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
715 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
716 |
+
|
717 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
718 |
+
|
719 |
+
if past_key_value is not None:
|
720 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
721 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
722 |
+
|
723 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
724 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
725 |
+
|
726 |
+
if attention_mask is not None:
|
727 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
728 |
+
raise ValueError(
|
729 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
730 |
+
)
|
731 |
+
|
732 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
733 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
734 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
735 |
+
query_states = query_states.contiguous()
|
736 |
+
key_states = key_states.contiguous()
|
737 |
+
value_states = value_states.contiguous()
|
738 |
+
|
739 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
740 |
+
query_states,
|
741 |
+
key_states,
|
742 |
+
value_states,
|
743 |
+
attn_mask=attention_mask,
|
744 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
745 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
746 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
747 |
+
)
|
748 |
+
|
749 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
750 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
751 |
+
|
752 |
+
attn_output = self.o_proj(attn_output)
|
753 |
+
|
754 |
+
return attn_output, None, past_key_value
|
755 |
+
|
756 |
+
|
757 |
+
LLAMA_ATTENTION_CLASSES = {
|
758 |
+
"eager": LlamaAttention,
|
759 |
+
"flash_attention_2": LlamaFlashAttention2,
|
760 |
+
"sdpa": LlamaSdpaAttention,
|
761 |
+
}
|
762 |
+
|
763 |
+
|
764 |
+
class LlamaDecoderLayer(nn.Module):
|
765 |
+
def __init__(self, config: LlamaConfig, layer_idx: int):
|
766 |
+
super().__init__()
|
767 |
+
self.hidden_size = config.hidden_size
|
768 |
+
|
769 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
770 |
+
|
771 |
+
self.mlp = LlamaMLP(config)
|
772 |
+
self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
773 |
+
self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
774 |
+
|
775 |
+
#################
|
776 |
+
## TruthX Code ##
|
777 |
+
#################
|
778 |
+
self.inner={}
|
779 |
+
|
780 |
+
def forward(
|
781 |
+
self,
|
782 |
+
hidden_states: torch.Tensor,
|
783 |
+
attention_mask: Optional[torch.Tensor] = None,
|
784 |
+
position_ids: Optional[torch.LongTensor] = None,
|
785 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
786 |
+
output_attentions: Optional[bool] = False,
|
787 |
+
use_cache: Optional[bool] = False,
|
788 |
+
truthx_model=None,
|
789 |
+
idx=None,
|
790 |
+
**kwargs,
|
791 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
792 |
+
"""
|
793 |
+
Args:
|
794 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
795 |
+
attention_mask (`torch.FloatTensor`, *optional*):
|
796 |
+
attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
|
797 |
+
query_sequence_length, key_sequence_length)` if default attention is used.
|
798 |
+
output_attentions (`bool`, *optional*):
|
799 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
800 |
+
returned tensors for more detail.
|
801 |
+
use_cache (`bool`, *optional*):
|
802 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
803 |
+
(see `past_key_values`).
|
804 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
805 |
+
"""
|
806 |
+
if "padding_mask" in kwargs:
|
807 |
+
warnings.warn(
|
808 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
809 |
+
)
|
810 |
+
|
811 |
+
residual = hidden_states
|
812 |
+
|
813 |
+
hidden_states = self.input_layernorm(hidden_states)
|
814 |
+
|
815 |
+
#################
|
816 |
+
## TruthX Code ##
|
817 |
+
#################
|
818 |
+
if truthx_model is not None:
|
819 |
+
truthx_model.cur_layer_id=f"{idx}.attn"
|
820 |
+
|
821 |
+
# Self Attention
|
822 |
+
hidden_states, self_attn_weights, present_key_value ,_attn_output= self.self_attn(
|
823 |
+
hidden_states=hidden_states,
|
824 |
+
attention_mask=attention_mask,
|
825 |
+
position_ids=position_ids,
|
826 |
+
past_key_value=past_key_value,
|
827 |
+
output_attentions=output_attentions,
|
828 |
+
use_cache=use_cache,
|
829 |
+
truthx_model=truthx_model,
|
830 |
+
**kwargs,
|
831 |
+
)
|
832 |
+
hidden_states = residual + hidden_states
|
833 |
+
|
834 |
+
|
835 |
+
#################
|
836 |
+
## TruthX Code ##
|
837 |
+
#################
|
838 |
+
self.inner['attn']=hidden_states
|
839 |
+
self.inner['_attn']=_attn_output
|
840 |
+
|
841 |
+
# Fully Connected
|
842 |
+
residual = hidden_states
|
843 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
844 |
+
hidden_states = self.mlp(hidden_states)
|
845 |
+
|
846 |
+
|
847 |
+
|
848 |
+
#################
|
849 |
+
## TruthX Code ##
|
850 |
+
#################
|
851 |
+
_hidden_states=hidden_states.contiguous()
|
852 |
+
hidden_states = residual + hidden_states
|
853 |
+
|
854 |
+
if truthx_model is not None:
|
855 |
+
truthx_model.cur_layer_id=f"{idx}.ffn"
|
856 |
+
hidden_states=residual+truthx_model.edit(_hidden_states)
|
857 |
+
|
858 |
+
self.inner['ffn']=hidden_states
|
859 |
+
self.inner['_ffn']=_hidden_states
|
860 |
+
|
861 |
+
outputs = (hidden_states,)
|
862 |
+
|
863 |
+
if output_attentions:
|
864 |
+
outputs += (self_attn_weights,)
|
865 |
+
|
866 |
+
if use_cache:
|
867 |
+
outputs += (present_key_value,)
|
868 |
+
|
869 |
+
return outputs
|
870 |
+
|
871 |
+
|
872 |
+
LLAMA_START_DOCSTRING = r"""
|
873 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
874 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
875 |
+
etc.)
|
876 |
+
|
877 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
878 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
879 |
+
and behavior.
|
880 |
+
|
881 |
+
Parameters:
|
882 |
+
config ([`LlamaConfig`]):
|
883 |
+
Model configuration class with all the parameters of the model. Initializing with a config file does not
|
884 |
+
load the weights associated with the model, only the configuration. Check out the
|
885 |
+
[`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
886 |
+
"""
|
887 |
+
|
888 |
+
|
889 |
+
@add_start_docstrings(
|
890 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
891 |
+
LLAMA_START_DOCSTRING,
|
892 |
+
)
|
893 |
+
class LlamaPreTrainedModel(PreTrainedModel):
|
894 |
+
config_class = LlamaConfig
|
895 |
+
base_model_prefix = "model"
|
896 |
+
supports_gradient_checkpointing = True
|
897 |
+
_no_split_modules = ["LlamaDecoderLayer"]
|
898 |
+
_skip_keys_device_placement = "past_key_values"
|
899 |
+
_supports_flash_attn_2 = True
|
900 |
+
_supports_sdpa = True
|
901 |
+
_supports_cache_class = True
|
902 |
+
|
903 |
+
def _init_weights(self, module):
|
904 |
+
std = self.config.initializer_range
|
905 |
+
if isinstance(module, nn.Linear):
|
906 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
907 |
+
if module.bias is not None:
|
908 |
+
module.bias.data.zero_()
|
909 |
+
elif isinstance(module, nn.Embedding):
|
910 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
911 |
+
if module.padding_idx is not None:
|
912 |
+
module.weight.data[module.padding_idx].zero_()
|
913 |
+
|
914 |
+
|
915 |
+
LLAMA_INPUTS_DOCSTRING = r"""
|
916 |
+
Args:
|
917 |
+
input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
|
918 |
+
Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
|
919 |
+
it.
|
920 |
+
|
921 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
922 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
923 |
+
|
924 |
+
[What are input IDs?](../glossary#input-ids)
|
925 |
+
attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
|
926 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
927 |
+
|
928 |
+
- 1 for tokens that are **not masked**,
|
929 |
+
- 0 for tokens that are **masked**.
|
930 |
+
|
931 |
+
[What are attention masks?](../glossary#attention-mask)
|
932 |
+
|
933 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
934 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
935 |
+
|
936 |
+
If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
|
937 |
+
`past_key_values`).
|
938 |
+
|
939 |
+
If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
|
940 |
+
and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
|
941 |
+
information on the default strategy.
|
942 |
+
|
943 |
+
- 1 indicates the head is **not masked**,
|
944 |
+
- 0 indicates the head is **masked**.
|
945 |
+
position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
946 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
947 |
+
config.n_positions - 1]`.
|
948 |
+
|
949 |
+
[What are position IDs?](../glossary#position-ids)
|
950 |
+
past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
|
951 |
+
Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
|
952 |
+
blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
|
953 |
+
returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
|
954 |
+
|
955 |
+
Two formats are allowed:
|
956 |
+
- a [`~cache_utils.Cache`] instance;
|
957 |
+
- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
|
958 |
+
shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
|
959 |
+
cache format.
|
960 |
+
|
961 |
+
The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
|
962 |
+
legacy cache format will be returned.
|
963 |
+
|
964 |
+
If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
|
965 |
+
have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
|
966 |
+
of shape `(batch_size, sequence_length)`.
|
967 |
+
inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
968 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
969 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
970 |
+
model's internal embedding lookup matrix.
|
971 |
+
use_cache (`bool`, *optional*):
|
972 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
973 |
+
`past_key_values`).
|
974 |
+
output_attentions (`bool`, *optional*):
|
975 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
976 |
+
tensors for more detail.
|
977 |
+
output_hidden_states (`bool`, *optional*):
|
978 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
979 |
+
more detail.
|
980 |
+
return_dict (`bool`, *optional*):
|
981 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
982 |
+
"""
|
983 |
+
|
984 |
+
|
985 |
+
@add_start_docstrings(
|
986 |
+
"The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
|
987 |
+
LLAMA_START_DOCSTRING,
|
988 |
+
)
|
989 |
+
class LlamaModel(LlamaPreTrainedModel):
|
990 |
+
"""
|
991 |
+
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
|
992 |
+
|
993 |
+
Args:
|
994 |
+
config: LlamaConfig
|
995 |
+
"""
|
996 |
+
|
997 |
+
def __init__(self, config: LlamaConfig):
|
998 |
+
super().__init__(config)
|
999 |
+
self.padding_idx = config.pad_token_id
|
1000 |
+
self.vocab_size = config.vocab_size
|
1001 |
+
|
1002 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
1003 |
+
self.layers = nn.ModuleList(
|
1004 |
+
[LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
1005 |
+
)
|
1006 |
+
self._use_sdpa = config._attn_implementation == "sdpa"
|
1007 |
+
self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
|
1008 |
+
self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
1009 |
+
|
1010 |
+
self.gradient_checkpointing = False
|
1011 |
+
# Initialize weights and apply final processing
|
1012 |
+
self.post_init()
|
1013 |
+
|
1014 |
+
def get_input_embeddings(self):
|
1015 |
+
return self.embed_tokens
|
1016 |
+
|
1017 |
+
def set_input_embeddings(self, value):
|
1018 |
+
self.embed_tokens = value
|
1019 |
+
|
1020 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1021 |
+
def forward(
|
1022 |
+
self,
|
1023 |
+
input_ids: torch.LongTensor = None,
|
1024 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1025 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1026 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1027 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1028 |
+
use_cache: Optional[bool] = None,
|
1029 |
+
output_attentions: Optional[bool] = None,
|
1030 |
+
output_hidden_states: Optional[bool] = None,
|
1031 |
+
return_dict: Optional[bool] = None,
|
1032 |
+
truthx_model=None,
|
1033 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
1034 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1035 |
+
output_hidden_states = (
|
1036 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1037 |
+
)
|
1038 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1039 |
+
|
1040 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1041 |
+
|
1042 |
+
# retrieve input_ids and inputs_embeds
|
1043 |
+
if input_ids is not None and inputs_embeds is not None:
|
1044 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
1045 |
+
elif input_ids is not None:
|
1046 |
+
batch_size, seq_length = input_ids.shape[:2]
|
1047 |
+
elif inputs_embeds is not None:
|
1048 |
+
batch_size, seq_length = inputs_embeds.shape[:2]
|
1049 |
+
else:
|
1050 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1051 |
+
|
1052 |
+
if self.gradient_checkpointing and self.training:
|
1053 |
+
if use_cache:
|
1054 |
+
logger.warning_once(
|
1055 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
1056 |
+
)
|
1057 |
+
use_cache = False
|
1058 |
+
|
1059 |
+
past_key_values_length = 0
|
1060 |
+
if use_cache:
|
1061 |
+
use_legacy_cache = not isinstance(past_key_values, Cache)
|
1062 |
+
if use_legacy_cache:
|
1063 |
+
past_key_values = DynamicCache.from_legacy_cache(past_key_values)
|
1064 |
+
past_key_values_length = past_key_values.get_usable_length(seq_length)
|
1065 |
+
|
1066 |
+
if position_ids is None:
|
1067 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1068 |
+
position_ids = torch.arange(
|
1069 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
1070 |
+
)
|
1071 |
+
position_ids = position_ids.unsqueeze(0)
|
1072 |
+
|
1073 |
+
if inputs_embeds is None:
|
1074 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
1075 |
+
|
1076 |
+
if self._use_flash_attention_2:
|
1077 |
+
# 2d mask is passed through the layers
|
1078 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
1079 |
+
elif self._use_sdpa and not output_attentions:
|
1080 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
1081 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
1082 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
1083 |
+
attention_mask,
|
1084 |
+
(batch_size, seq_length),
|
1085 |
+
inputs_embeds,
|
1086 |
+
past_key_values_length,
|
1087 |
+
)
|
1088 |
+
else:
|
1089 |
+
# 4d mask is passed through the layers
|
1090 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
1091 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
1092 |
+
)
|
1093 |
+
|
1094 |
+
# embed positions
|
1095 |
+
hidden_states = inputs_embeds
|
1096 |
+
|
1097 |
+
# decoder layers
|
1098 |
+
all_hidden_states = () if output_hidden_states else None
|
1099 |
+
all_self_attns = () if output_attentions else None
|
1100 |
+
next_decoder_cache = None
|
1101 |
+
|
1102 |
+
#################
|
1103 |
+
## TruthX Code ##
|
1104 |
+
#################
|
1105 |
+
idx=0
|
1106 |
+
for decoder_layer in self.layers:
|
1107 |
+
if output_hidden_states:
|
1108 |
+
all_hidden_states += (hidden_states,)
|
1109 |
+
|
1110 |
+
if self.gradient_checkpointing and self.training:
|
1111 |
+
layer_outputs = self._gradient_checkpointing_func(
|
1112 |
+
decoder_layer.__call__,
|
1113 |
+
hidden_states,
|
1114 |
+
attention_mask,
|
1115 |
+
position_ids,
|
1116 |
+
past_key_values,
|
1117 |
+
output_attentions,
|
1118 |
+
use_cache,
|
1119 |
+
)
|
1120 |
+
else:
|
1121 |
+
#################
|
1122 |
+
## TruthX Code ##
|
1123 |
+
#################
|
1124 |
+
layer_outputs = decoder_layer(
|
1125 |
+
hidden_states,
|
1126 |
+
attention_mask=attention_mask,
|
1127 |
+
position_ids=position_ids,
|
1128 |
+
past_key_value=past_key_values,
|
1129 |
+
output_attentions=output_attentions,
|
1130 |
+
use_cache=use_cache,
|
1131 |
+
truthx_model=truthx_model,
|
1132 |
+
idx=idx,
|
1133 |
+
)
|
1134 |
+
|
1135 |
+
hidden_states = layer_outputs[0]
|
1136 |
+
|
1137 |
+
if use_cache:
|
1138 |
+
next_decoder_cache = layer_outputs[2 if output_attentions else 1]
|
1139 |
+
|
1140 |
+
if output_attentions:
|
1141 |
+
all_self_attns += (layer_outputs[1],)
|
1142 |
+
|
1143 |
+
idx+=1
|
1144 |
+
|
1145 |
+
hidden_states = self.norm(hidden_states)
|
1146 |
+
|
1147 |
+
# add hidden states from the last decoder layer
|
1148 |
+
if output_hidden_states:
|
1149 |
+
all_hidden_states += (hidden_states,)
|
1150 |
+
|
1151 |
+
next_cache = None
|
1152 |
+
if use_cache:
|
1153 |
+
next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
|
1154 |
+
if not return_dict:
|
1155 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
1156 |
+
return BaseModelOutputWithPast(
|
1157 |
+
last_hidden_state=hidden_states,
|
1158 |
+
past_key_values=next_cache,
|
1159 |
+
hidden_states=all_hidden_states,
|
1160 |
+
attentions=all_self_attns,
|
1161 |
+
)
|
1162 |
+
|
1163 |
+
|
1164 |
+
class LlamaForCausalLM(LlamaPreTrainedModel):
|
1165 |
+
_tied_weights_keys = ["lm_head.weight"]
|
1166 |
+
|
1167 |
+
|
1168 |
+
def __init__(self, config):
|
1169 |
+
super().__init__(config)
|
1170 |
+
self.model = LlamaModel(config)
|
1171 |
+
self.vocab_size = config.vocab_size
|
1172 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
1173 |
+
|
1174 |
+
|
1175 |
+
self.truthx_model=None
|
1176 |
+
# from pathlib import Path
|
1177 |
+
self.config=config
|
1178 |
+
# Initialize weights and apply final processing
|
1179 |
+
self.post_init()
|
1180 |
+
|
1181 |
+
|
1182 |
+
def set_truthx_params(self, params):
|
1183 |
+
if self.truthx_model is None:
|
1184 |
+
from pathlib import Path
|
1185 |
+
truthx_model_path=Path(self.config._name_or_path)/self.config.truthx_config["path"]
|
1186 |
+
|
1187 |
+
self.truthx_model=TruthX(truthx_model_path,self.config.hidden_size)
|
1188 |
+
print(self.truthx_model)
|
1189 |
+
if 'top_layers' in params.keys():
|
1190 |
+
self.truthx_model.top_layers=params['top_layers']
|
1191 |
+
if 'edit_strength' in params.keys():
|
1192 |
+
self.truthx_model.edit_strength=params['edit_strength']
|
1193 |
+
if 'mc' in params.keys():
|
1194 |
+
self.truthx_model.mc=params['mc']
|
1195 |
+
if 'prompt_length' in params.keys():
|
1196 |
+
self.truthx_model.prompt_length=params['prompt_length']
|
1197 |
+
|
1198 |
+
# print("Set truthx param:",self.truthx_model.top_layers,self.truthx_model.edit_strength)
|
1199 |
+
|
1200 |
+
def get_input_embeddings(self):
|
1201 |
+
return self.model.embed_tokens
|
1202 |
+
|
1203 |
+
def set_input_embeddings(self, value):
|
1204 |
+
self.model.embed_tokens = value
|
1205 |
+
|
1206 |
+
def get_output_embeddings(self):
|
1207 |
+
return self.lm_head
|
1208 |
+
|
1209 |
+
def set_output_embeddings(self, new_embeddings):
|
1210 |
+
self.lm_head = new_embeddings
|
1211 |
+
|
1212 |
+
def set_decoder(self, decoder):
|
1213 |
+
self.model = decoder
|
1214 |
+
|
1215 |
+
def get_decoder(self):
|
1216 |
+
return self.model
|
1217 |
+
|
1218 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1219 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
|
1220 |
+
def forward(
|
1221 |
+
self,
|
1222 |
+
input_ids: torch.LongTensor = None,
|
1223 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1224 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1225 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1226 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1227 |
+
labels: Optional[torch.LongTensor] = None,
|
1228 |
+
use_cache: Optional[bool] = None,
|
1229 |
+
output_attentions: Optional[bool] = None,
|
1230 |
+
output_hidden_states: Optional[bool] = None,
|
1231 |
+
return_dict: Optional[bool] = None,
|
1232 |
+
truthx_model=None,
|
1233 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
1234 |
+
r"""
|
1235 |
+
Args:
|
1236 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1237 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
1238 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
1239 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
1240 |
+
|
1241 |
+
Returns:
|
1242 |
+
|
1243 |
+
Example:
|
1244 |
+
|
1245 |
+
```python
|
1246 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
1247 |
+
|
1248 |
+
>>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
|
1249 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
|
1250 |
+
|
1251 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
1252 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
1253 |
+
|
1254 |
+
>>> # Generate
|
1255 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
1256 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
1257 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
1258 |
+
```"""
|
1259 |
+
|
1260 |
+
if self.truthx_model is None:
|
1261 |
+
from pathlib import Path
|
1262 |
+
truthx_model_path=Path(self.config._name_or_path)/self.config.truthx_config["path"]
|
1263 |
+
self.truthx_model=TruthX(truthx_model_path,self.config.hidden_size)
|
1264 |
+
# print(self.truthx_model)
|
1265 |
+
|
1266 |
+
|
1267 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
1268 |
+
output_hidden_states = (
|
1269 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
1270 |
+
)
|
1271 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1272 |
+
|
1273 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
1274 |
+
outputs = self.model(
|
1275 |
+
input_ids=input_ids,
|
1276 |
+
attention_mask=attention_mask,
|
1277 |
+
position_ids=position_ids,
|
1278 |
+
past_key_values=past_key_values,
|
1279 |
+
inputs_embeds=inputs_embeds,
|
1280 |
+
use_cache=use_cache,
|
1281 |
+
output_attentions=output_attentions,
|
1282 |
+
output_hidden_states=output_hidden_states,
|
1283 |
+
return_dict=return_dict,
|
1284 |
+
truthx_model=self.truthx_model if truthx_model is None else truthx_model,
|
1285 |
+
)
|
1286 |
+
|
1287 |
+
hidden_states = outputs[0]
|
1288 |
+
if self.config.pretraining_tp > 1:
|
1289 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
1290 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
1291 |
+
logits = torch.cat(logits, dim=-1)
|
1292 |
+
else:
|
1293 |
+
logits = self.lm_head(hidden_states)
|
1294 |
+
logits = logits.float()
|
1295 |
+
|
1296 |
+
loss = None
|
1297 |
+
if labels is not None:
|
1298 |
+
# Shift so that tokens < n predict n
|
1299 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
1300 |
+
shift_labels = labels[..., 1:].contiguous()
|
1301 |
+
# Flatten the tokens
|
1302 |
+
loss_fct = CrossEntropyLoss()
|
1303 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
1304 |
+
shift_labels = shift_labels.view(-1)
|
1305 |
+
# Enable model parallelism
|
1306 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
1307 |
+
loss = loss_fct(shift_logits, shift_labels)
|
1308 |
+
|
1309 |
+
if not return_dict:
|
1310 |
+
output = (logits,) + outputs[1:]
|
1311 |
+
return (loss,) + output if loss is not None else output
|
1312 |
+
|
1313 |
+
return CausalLMOutputWithPast(
|
1314 |
+
loss=loss,
|
1315 |
+
logits=logits,
|
1316 |
+
past_key_values=outputs.past_key_values,
|
1317 |
+
hidden_states=outputs.hidden_states,
|
1318 |
+
attentions=outputs.attentions,
|
1319 |
+
)
|
1320 |
+
|
1321 |
+
def prepare_inputs_for_generation(
|
1322 |
+
self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
|
1323 |
+
):
|
1324 |
+
if past_key_values is not None:
|
1325 |
+
if isinstance(past_key_values, Cache):
|
1326 |
+
cache_length = past_key_values.get_seq_length()
|
1327 |
+
past_length = past_key_values.seen_tokens
|
1328 |
+
max_cache_length = past_key_values.get_max_length()
|
1329 |
+
else:
|
1330 |
+
cache_length = past_length = past_key_values[0][0].shape[2]
|
1331 |
+
max_cache_length = None
|
1332 |
+
|
1333 |
+
# Keep only the unprocessed tokens:
|
1334 |
+
# 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
|
1335 |
+
# some of the inputs are exclusively passed as part of the cache (e.g. when passing input_embeds as
|
1336 |
+
# input)
|
1337 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
1338 |
+
input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
|
1339 |
+
# 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
|
1340 |
+
# input_ids based on the past_length.
|
1341 |
+
elif past_length < input_ids.shape[1]:
|
1342 |
+
input_ids = input_ids[:, past_length:]
|
1343 |
+
# 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
|
1344 |
+
|
1345 |
+
# If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
|
1346 |
+
if (
|
1347 |
+
max_cache_length is not None
|
1348 |
+
and attention_mask is not None
|
1349 |
+
and cache_length + input_ids.shape[1] > max_cache_length
|
1350 |
+
):
|
1351 |
+
attention_mask = attention_mask[:, -max_cache_length:]
|
1352 |
+
|
1353 |
+
position_ids = kwargs.get("position_ids", None)
|
1354 |
+
if attention_mask is not None and position_ids is None:
|
1355 |
+
# create position_ids on the fly for batch generation
|
1356 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
1357 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
1358 |
+
if past_key_values:
|
1359 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
1360 |
+
|
1361 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
1362 |
+
if inputs_embeds is not None and past_key_values is None:
|
1363 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
1364 |
+
else:
|
1365 |
+
model_inputs = {"input_ids": input_ids}
|
1366 |
+
|
1367 |
+
model_inputs.update(
|
1368 |
+
{
|
1369 |
+
"position_ids": position_ids,
|
1370 |
+
"past_key_values": past_key_values,
|
1371 |
+
"use_cache": kwargs.get("use_cache"),
|
1372 |
+
"attention_mask": attention_mask,
|
1373 |
+
}
|
1374 |
+
)
|
1375 |
+
|
1376 |
+
#################
|
1377 |
+
## TruthX Code ##
|
1378 |
+
#################
|
1379 |
+
if 'truthx_model' in kwargs.keys():
|
1380 |
+
model_inputs.update(
|
1381 |
+
{
|
1382 |
+
"truthx_model": kwargs.get("truthx_model")
|
1383 |
+
}
|
1384 |
+
)
|
1385 |
+
return model_inputs
|
1386 |
+
|
1387 |
+
@staticmethod
|
1388 |
+
def _reorder_cache(past_key_values, beam_idx):
|
1389 |
+
reordered_past = ()
|
1390 |
+
for layer_past in past_key_values:
|
1391 |
+
reordered_past += (
|
1392 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
1393 |
+
)
|
1394 |
+
return reordered_past
|
1395 |
+
|
1396 |
+
|
1397 |
+
@add_start_docstrings(
|
1398 |
+
"""
|
1399 |
+
The LLaMa Model transformer with a sequence classification head on top (linear layer).
|
1400 |
+
|
1401 |
+
[`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
|
1402 |
+
(e.g. GPT-2) do.
|
1403 |
+
|
1404 |
+
Since it does classification on the last token, it requires to know the position of the last token. If a
|
1405 |
+
`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
|
1406 |
+
no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
|
1407 |
+
padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
|
1408 |
+
each row of the batch).
|
1409 |
+
""",
|
1410 |
+
LLAMA_START_DOCSTRING,
|
1411 |
+
)
|
1412 |
+
class LlamaForSequenceClassification(LlamaPreTrainedModel):
|
1413 |
+
def __init__(self, config):
|
1414 |
+
super().__init__(config)
|
1415 |
+
self.num_labels = config.num_labels
|
1416 |
+
self.model = LlamaModel(config)
|
1417 |
+
self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
|
1418 |
+
|
1419 |
+
# Initialize weights and apply final processing
|
1420 |
+
self.post_init()
|
1421 |
+
|
1422 |
+
def get_input_embeddings(self):
|
1423 |
+
return self.model.embed_tokens
|
1424 |
+
|
1425 |
+
def set_input_embeddings(self, value):
|
1426 |
+
self.model.embed_tokens = value
|
1427 |
+
|
1428 |
+
@add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
|
1429 |
+
def forward(
|
1430 |
+
self,
|
1431 |
+
input_ids: torch.LongTensor = None,
|
1432 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1433 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1434 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1435 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1436 |
+
labels: Optional[torch.LongTensor] = None,
|
1437 |
+
use_cache: Optional[bool] = None,
|
1438 |
+
output_attentions: Optional[bool] = None,
|
1439 |
+
output_hidden_states: Optional[bool] = None,
|
1440 |
+
return_dict: Optional[bool] = None,
|
1441 |
+
) -> Union[Tuple, SequenceClassifierOutputWithPast]:
|
1442 |
+
r"""
|
1443 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1444 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1445 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1446 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1447 |
+
"""
|
1448 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1449 |
+
|
1450 |
+
transformer_outputs = self.model(
|
1451 |
+
input_ids,
|
1452 |
+
attention_mask=attention_mask,
|
1453 |
+
position_ids=position_ids,
|
1454 |
+
past_key_values=past_key_values,
|
1455 |
+
inputs_embeds=inputs_embeds,
|
1456 |
+
use_cache=use_cache,
|
1457 |
+
output_attentions=output_attentions,
|
1458 |
+
output_hidden_states=output_hidden_states,
|
1459 |
+
return_dict=return_dict,
|
1460 |
+
)
|
1461 |
+
hidden_states = transformer_outputs[0]
|
1462 |
+
logits = self.score(hidden_states)
|
1463 |
+
|
1464 |
+
if input_ids is not None:
|
1465 |
+
batch_size = input_ids.shape[0]
|
1466 |
+
else:
|
1467 |
+
batch_size = inputs_embeds.shape[0]
|
1468 |
+
|
1469 |
+
if self.config.pad_token_id is None and batch_size != 1:
|
1470 |
+
raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
|
1471 |
+
if self.config.pad_token_id is None:
|
1472 |
+
sequence_lengths = -1
|
1473 |
+
else:
|
1474 |
+
if input_ids is not None:
|
1475 |
+
# if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
|
1476 |
+
sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
|
1477 |
+
sequence_lengths = sequence_lengths % input_ids.shape[-1]
|
1478 |
+
sequence_lengths = sequence_lengths.to(logits.device)
|
1479 |
+
else:
|
1480 |
+
sequence_lengths = -1
|
1481 |
+
|
1482 |
+
pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
|
1483 |
+
|
1484 |
+
loss = None
|
1485 |
+
if labels is not None:
|
1486 |
+
labels = labels.to(logits.device)
|
1487 |
+
if self.config.problem_type is None:
|
1488 |
+
if self.num_labels == 1:
|
1489 |
+
self.config.problem_type = "regression"
|
1490 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1491 |
+
self.config.problem_type = "single_label_classification"
|
1492 |
+
else:
|
1493 |
+
self.config.problem_type = "multi_label_classification"
|
1494 |
+
|
1495 |
+
if self.config.problem_type == "regression":
|
1496 |
+
loss_fct = MSELoss()
|
1497 |
+
if self.num_labels == 1:
|
1498 |
+
loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
|
1499 |
+
else:
|
1500 |
+
loss = loss_fct(pooled_logits, labels)
|
1501 |
+
elif self.config.problem_type == "single_label_classification":
|
1502 |
+
loss_fct = CrossEntropyLoss()
|
1503 |
+
loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
|
1504 |
+
elif self.config.problem_type == "multi_label_classification":
|
1505 |
+
loss_fct = BCEWithLogitsLoss()
|
1506 |
+
loss = loss_fct(pooled_logits, labels)
|
1507 |
+
if not return_dict:
|
1508 |
+
output = (pooled_logits,) + transformer_outputs[1:]
|
1509 |
+
return ((loss,) + output) if loss is not None else output
|
1510 |
+
|
1511 |
+
return SequenceClassifierOutputWithPast(
|
1512 |
+
loss=loss,
|
1513 |
+
logits=pooled_logits,
|
1514 |
+
past_key_values=transformer_outputs.past_key_values,
|
1515 |
+
hidden_states=transformer_outputs.hidden_states,
|
1516 |
+
attentions=transformer_outputs.attentions,
|
1517 |
+
)
|
pytorch_model-00001-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8f917a253ef631128743798d284a7e7a5a22ac1ad23ecd6a9da57550348317f5
|
3 |
+
size 9976634558
|
pytorch_model-00002-of-00002.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:8e8fc22b2c138439c6bafb7331ac139585e683005407e016feb18a4feea18417
|
3 |
+
size 3500315539
|
pytorch_model.bin.index.json
ADDED
@@ -0,0 +1,330 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"metadata": {
|
3 |
+
"total_size": 13476839424
|
4 |
+
},
|
5 |
+
"weight_map": {
|
6 |
+
"lm_head.weight": "pytorch_model-00002-of-00002.bin",
|
7 |
+
"model.embed_tokens.weight": "pytorch_model-00001-of-00002.bin",
|
8 |
+
"model.layers.0.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
9 |
+
"model.layers.0.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
10 |
+
"model.layers.0.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
11 |
+
"model.layers.0.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
12 |
+
"model.layers.0.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
13 |
+
"model.layers.0.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
14 |
+
"model.layers.0.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
15 |
+
"model.layers.0.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
16 |
+
"model.layers.0.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
17 |
+
"model.layers.0.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
18 |
+
"model.layers.1.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
19 |
+
"model.layers.1.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
20 |
+
"model.layers.1.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
21 |
+
"model.layers.1.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
22 |
+
"model.layers.1.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
23 |
+
"model.layers.1.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
24 |
+
"model.layers.1.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
25 |
+
"model.layers.1.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
26 |
+
"model.layers.1.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
27 |
+
"model.layers.1.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
28 |
+
"model.layers.10.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
29 |
+
"model.layers.10.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
30 |
+
"model.layers.10.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
31 |
+
"model.layers.10.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
32 |
+
"model.layers.10.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
33 |
+
"model.layers.10.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
34 |
+
"model.layers.10.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
35 |
+
"model.layers.10.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
36 |
+
"model.layers.10.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
37 |
+
"model.layers.10.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
38 |
+
"model.layers.11.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
39 |
+
"model.layers.11.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
40 |
+
"model.layers.11.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
41 |
+
"model.layers.11.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
42 |
+
"model.layers.11.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
43 |
+
"model.layers.11.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
44 |
+
"model.layers.11.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
45 |
+
"model.layers.11.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
46 |
+
"model.layers.11.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
47 |
+
"model.layers.11.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
48 |
+
"model.layers.12.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
49 |
+
"model.layers.12.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
50 |
+
"model.layers.12.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
51 |
+
"model.layers.12.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
52 |
+
"model.layers.12.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
53 |
+
"model.layers.12.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
54 |
+
"model.layers.12.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
55 |
+
"model.layers.12.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
56 |
+
"model.layers.12.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
57 |
+
"model.layers.12.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
58 |
+
"model.layers.13.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
59 |
+
"model.layers.13.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
60 |
+
"model.layers.13.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
61 |
+
"model.layers.13.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
62 |
+
"model.layers.13.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
63 |
+
"model.layers.13.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
64 |
+
"model.layers.13.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
65 |
+
"model.layers.13.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
66 |
+
"model.layers.13.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
67 |
+
"model.layers.13.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
68 |
+
"model.layers.14.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
69 |
+
"model.layers.14.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
70 |
+
"model.layers.14.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
71 |
+
"model.layers.14.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
72 |
+
"model.layers.14.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
73 |
+
"model.layers.14.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
74 |
+
"model.layers.14.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
75 |
+
"model.layers.14.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
76 |
+
"model.layers.14.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
77 |
+
"model.layers.14.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
78 |
+
"model.layers.15.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
79 |
+
"model.layers.15.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
80 |
+
"model.layers.15.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
81 |
+
"model.layers.15.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
82 |
+
"model.layers.15.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
83 |
+
"model.layers.15.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
84 |
+
"model.layers.15.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
85 |
+
"model.layers.15.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
86 |
+
"model.layers.15.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
87 |
+
"model.layers.15.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
88 |
+
"model.layers.16.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
89 |
+
"model.layers.16.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
90 |
+
"model.layers.16.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
91 |
+
"model.layers.16.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
92 |
+
"model.layers.16.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
93 |
+
"model.layers.16.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
94 |
+
"model.layers.16.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
95 |
+
"model.layers.16.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
96 |
+
"model.layers.16.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
97 |
+
"model.layers.16.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
98 |
+
"model.layers.17.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
99 |
+
"model.layers.17.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
100 |
+
"model.layers.17.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
101 |
+
"model.layers.17.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
102 |
+
"model.layers.17.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
103 |
+
"model.layers.17.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
104 |
+
"model.layers.17.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
105 |
+
"model.layers.17.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
106 |
+
"model.layers.17.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
107 |
+
"model.layers.17.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
108 |
+
"model.layers.18.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
109 |
+
"model.layers.18.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
110 |
+
"model.layers.18.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
111 |
+
"model.layers.18.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
112 |
+
"model.layers.18.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
113 |
+
"model.layers.18.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
114 |
+
"model.layers.18.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
115 |
+
"model.layers.18.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
116 |
+
"model.layers.18.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
117 |
+
"model.layers.18.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
118 |
+
"model.layers.19.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
119 |
+
"model.layers.19.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
120 |
+
"model.layers.19.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
121 |
+
"model.layers.19.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
122 |
+
"model.layers.19.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
123 |
+
"model.layers.19.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
124 |
+
"model.layers.19.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
125 |
+
"model.layers.19.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
126 |
+
"model.layers.19.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
127 |
+
"model.layers.19.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
128 |
+
"model.layers.2.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
129 |
+
"model.layers.2.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
130 |
+
"model.layers.2.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
131 |
+
"model.layers.2.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
132 |
+
"model.layers.2.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
133 |
+
"model.layers.2.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
134 |
+
"model.layers.2.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
135 |
+
"model.layers.2.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
136 |
+
"model.layers.2.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
137 |
+
"model.layers.2.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
138 |
+
"model.layers.20.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
139 |
+
"model.layers.20.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
140 |
+
"model.layers.20.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
141 |
+
"model.layers.20.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
142 |
+
"model.layers.20.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
143 |
+
"model.layers.20.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
144 |
+
"model.layers.20.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
145 |
+
"model.layers.20.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
146 |
+
"model.layers.20.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
147 |
+
"model.layers.20.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
148 |
+
"model.layers.21.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
149 |
+
"model.layers.21.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
150 |
+
"model.layers.21.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
151 |
+
"model.layers.21.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
152 |
+
"model.layers.21.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
153 |
+
"model.layers.21.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
154 |
+
"model.layers.21.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
155 |
+
"model.layers.21.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
156 |
+
"model.layers.21.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
157 |
+
"model.layers.21.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
158 |
+
"model.layers.22.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
159 |
+
"model.layers.22.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
160 |
+
"model.layers.22.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
161 |
+
"model.layers.22.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
162 |
+
"model.layers.22.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
163 |
+
"model.layers.22.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
164 |
+
"model.layers.22.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
165 |
+
"model.layers.22.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
166 |
+
"model.layers.22.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
167 |
+
"model.layers.22.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
168 |
+
"model.layers.23.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
169 |
+
"model.layers.23.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
170 |
+
"model.layers.23.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
171 |
+
"model.layers.23.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
172 |
+
"model.layers.23.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
173 |
+
"model.layers.23.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
174 |
+
"model.layers.23.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
175 |
+
"model.layers.23.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
176 |
+
"model.layers.23.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
177 |
+
"model.layers.23.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
178 |
+
"model.layers.24.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
179 |
+
"model.layers.24.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
180 |
+
"model.layers.24.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
181 |
+
"model.layers.24.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
182 |
+
"model.layers.24.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
183 |
+
"model.layers.24.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
184 |
+
"model.layers.24.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
185 |
+
"model.layers.24.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
186 |
+
"model.layers.24.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
187 |
+
"model.layers.24.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
188 |
+
"model.layers.25.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
189 |
+
"model.layers.25.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
190 |
+
"model.layers.25.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
191 |
+
"model.layers.25.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
192 |
+
"model.layers.25.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
193 |
+
"model.layers.25.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
194 |
+
"model.layers.25.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
195 |
+
"model.layers.25.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
196 |
+
"model.layers.25.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
197 |
+
"model.layers.25.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
198 |
+
"model.layers.26.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
199 |
+
"model.layers.26.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
200 |
+
"model.layers.26.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
201 |
+
"model.layers.26.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
202 |
+
"model.layers.26.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
203 |
+
"model.layers.26.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
204 |
+
"model.layers.26.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
205 |
+
"model.layers.26.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
206 |
+
"model.layers.26.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
207 |
+
"model.layers.26.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
208 |
+
"model.layers.27.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
209 |
+
"model.layers.27.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
210 |
+
"model.layers.27.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
211 |
+
"model.layers.27.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
212 |
+
"model.layers.27.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
213 |
+
"model.layers.27.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
214 |
+
"model.layers.27.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
215 |
+
"model.layers.27.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
216 |
+
"model.layers.27.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
217 |
+
"model.layers.27.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
218 |
+
"model.layers.28.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
219 |
+
"model.layers.28.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
220 |
+
"model.layers.28.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
221 |
+
"model.layers.28.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
222 |
+
"model.layers.28.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
223 |
+
"model.layers.28.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
224 |
+
"model.layers.28.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
225 |
+
"model.layers.28.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
226 |
+
"model.layers.28.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
227 |
+
"model.layers.28.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
228 |
+
"model.layers.29.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
229 |
+
"model.layers.29.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
230 |
+
"model.layers.29.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
231 |
+
"model.layers.29.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
232 |
+
"model.layers.29.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
233 |
+
"model.layers.29.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
234 |
+
"model.layers.29.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
235 |
+
"model.layers.29.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
236 |
+
"model.layers.29.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
237 |
+
"model.layers.29.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
238 |
+
"model.layers.3.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
239 |
+
"model.layers.3.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
240 |
+
"model.layers.3.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
241 |
+
"model.layers.3.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
242 |
+
"model.layers.3.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
243 |
+
"model.layers.3.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
244 |
+
"model.layers.3.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
245 |
+
"model.layers.3.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
246 |
+
"model.layers.3.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
247 |
+
"model.layers.3.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
248 |
+
"model.layers.30.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
249 |
+
"model.layers.30.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
250 |
+
"model.layers.30.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
251 |
+
"model.layers.30.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
252 |
+
"model.layers.30.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
253 |
+
"model.layers.30.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
254 |
+
"model.layers.30.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
255 |
+
"model.layers.30.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
256 |
+
"model.layers.30.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
257 |
+
"model.layers.30.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
258 |
+
"model.layers.31.input_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
259 |
+
"model.layers.31.mlp.down_proj.weight": "pytorch_model-00002-of-00002.bin",
|
260 |
+
"model.layers.31.mlp.gate_proj.weight": "pytorch_model-00002-of-00002.bin",
|
261 |
+
"model.layers.31.mlp.up_proj.weight": "pytorch_model-00002-of-00002.bin",
|
262 |
+
"model.layers.31.post_attention_layernorm.weight": "pytorch_model-00002-of-00002.bin",
|
263 |
+
"model.layers.31.self_attn.k_proj.weight": "pytorch_model-00002-of-00002.bin",
|
264 |
+
"model.layers.31.self_attn.o_proj.weight": "pytorch_model-00002-of-00002.bin",
|
265 |
+
"model.layers.31.self_attn.q_proj.weight": "pytorch_model-00002-of-00002.bin",
|
266 |
+
"model.layers.31.self_attn.rotary_emb.inv_freq": "pytorch_model-00002-of-00002.bin",
|
267 |
+
"model.layers.31.self_attn.v_proj.weight": "pytorch_model-00002-of-00002.bin",
|
268 |
+
"model.layers.4.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
269 |
+
"model.layers.4.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
270 |
+
"model.layers.4.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
271 |
+
"model.layers.4.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
272 |
+
"model.layers.4.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
273 |
+
"model.layers.4.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
274 |
+
"model.layers.4.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
275 |
+
"model.layers.4.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
276 |
+
"model.layers.4.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
277 |
+
"model.layers.4.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
278 |
+
"model.layers.5.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
279 |
+
"model.layers.5.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
280 |
+
"model.layers.5.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
281 |
+
"model.layers.5.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
282 |
+
"model.layers.5.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
283 |
+
"model.layers.5.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
284 |
+
"model.layers.5.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
285 |
+
"model.layers.5.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
286 |
+
"model.layers.5.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
287 |
+
"model.layers.5.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
288 |
+
"model.layers.6.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
289 |
+
"model.layers.6.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
290 |
+
"model.layers.6.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
291 |
+
"model.layers.6.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
292 |
+
"model.layers.6.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
293 |
+
"model.layers.6.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
294 |
+
"model.layers.6.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
295 |
+
"model.layers.6.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
296 |
+
"model.layers.6.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
297 |
+
"model.layers.6.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
298 |
+
"model.layers.7.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
299 |
+
"model.layers.7.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
300 |
+
"model.layers.7.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
301 |
+
"model.layers.7.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
302 |
+
"model.layers.7.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
303 |
+
"model.layers.7.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
304 |
+
"model.layers.7.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
305 |
+
"model.layers.7.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
306 |
+
"model.layers.7.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
307 |
+
"model.layers.7.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
308 |
+
"model.layers.8.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
309 |
+
"model.layers.8.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
310 |
+
"model.layers.8.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
311 |
+
"model.layers.8.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
312 |
+
"model.layers.8.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
313 |
+
"model.layers.8.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
314 |
+
"model.layers.8.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
315 |
+
"model.layers.8.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
316 |
+
"model.layers.8.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
317 |
+
"model.layers.8.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
318 |
+
"model.layers.9.input_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
319 |
+
"model.layers.9.mlp.down_proj.weight": "pytorch_model-00001-of-00002.bin",
|
320 |
+
"model.layers.9.mlp.gate_proj.weight": "pytorch_model-00001-of-00002.bin",
|
321 |
+
"model.layers.9.mlp.up_proj.weight": "pytorch_model-00001-of-00002.bin",
|
322 |
+
"model.layers.9.post_attention_layernorm.weight": "pytorch_model-00001-of-00002.bin",
|
323 |
+
"model.layers.9.self_attn.k_proj.weight": "pytorch_model-00001-of-00002.bin",
|
324 |
+
"model.layers.9.self_attn.o_proj.weight": "pytorch_model-00001-of-00002.bin",
|
325 |
+
"model.layers.9.self_attn.q_proj.weight": "pytorch_model-00001-of-00002.bin",
|
326 |
+
"model.layers.9.self_attn.rotary_emb.inv_freq": "pytorch_model-00001-of-00002.bin",
|
327 |
+
"model.layers.9.self_attn.v_proj.weight": "pytorch_model-00001-of-00002.bin",
|
328 |
+
"model.norm.weight": "pytorch_model-00002-of-00002.bin"
|
329 |
+
}
|
330 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"eos_token": {
|
10 |
+
"content": "</s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"unk_token": {
|
17 |
+
"content": "<unk>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
}
|
23 |
+
}
|
tokenization_llama.py
ADDED
@@ -0,0 +1,472 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
|
21 |
+
"""Tokenization classes for LLaMA."""
|
22 |
+
import os
|
23 |
+
from shutil import copyfile
|
24 |
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
|
25 |
+
|
26 |
+
import sentencepiece as spm
|
27 |
+
|
28 |
+
from ...convert_slow_tokenizer import import_protobuf
|
29 |
+
from ...tokenization_utils import AddedToken, PreTrainedTokenizer
|
30 |
+
from ...utils import logging
|
31 |
+
|
32 |
+
|
33 |
+
if TYPE_CHECKING:
|
34 |
+
from ...tokenization_utils_base import TextInput
|
35 |
+
|
36 |
+
logger = logging.get_logger(__name__)
|
37 |
+
|
38 |
+
VOCAB_FILES_NAMES = {"vocab_file": "tokenizer.model"}
|
39 |
+
|
40 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
41 |
+
"vocab_file": {
|
42 |
+
"hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model",
|
43 |
+
},
|
44 |
+
"tokenizer_file": {
|
45 |
+
"hf-internal-testing/llama-tokenizer": "https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json",
|
46 |
+
},
|
47 |
+
}
|
48 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
49 |
+
"hf-internal-testing/llama-tokenizer": 2048,
|
50 |
+
}
|
51 |
+
SPIECE_UNDERLINE = "▁"
|
52 |
+
|
53 |
+
B_INST, E_INST = "[INST]", "[/INST]"
|
54 |
+
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
|
55 |
+
|
56 |
+
# fmt: off
|
57 |
+
DEFAULT_SYSTEM_PROMPT = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your \
|
58 |
+
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
|
59 |
+
that your responses are socially unbiased and positive in nature.
|
60 |
+
|
61 |
+
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not \
|
62 |
+
correct. If you don't know the answer to a question, please don't share false information."""
|
63 |
+
# fmt: on
|
64 |
+
|
65 |
+
|
66 |
+
class LlamaTokenizer(PreTrainedTokenizer):
|
67 |
+
"""
|
68 |
+
Construct a Llama tokenizer. Based on byte-level Byte-Pair-Encoding. The default padding token is unset as there is
|
69 |
+
no padding token in the original model.
|
70 |
+
|
71 |
+
Args:
|
72 |
+
vocab_file (`str`):
|
73 |
+
Path to the vocabulary file.
|
74 |
+
unk_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<unk>"`):
|
75 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
76 |
+
token instead.
|
77 |
+
bos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"<s>"`):
|
78 |
+
The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
|
79 |
+
eos_token (`str` or `tokenizers.AddedToken`, *optional*, defaults to `"</s>"`):
|
80 |
+
The end of sequence token.
|
81 |
+
pad_token (`str` or `tokenizers.AddedToken`, *optional*):
|
82 |
+
A special token used to make arrays of tokens the same size for batching purpose. Will then be ignored by
|
83 |
+
attention mechanisms or loss computation.
|
84 |
+
sp_model_kwargs (`Dict[str, Any]`, `Optional`, *optional*):
|
85 |
+
Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
|
86 |
+
SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
|
87 |
+
to set:
|
88 |
+
|
89 |
+
- `enable_sampling`: Enable subword regularization.
|
90 |
+
- `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
|
91 |
+
|
92 |
+
- `nbest_size = {0,1}`: No sampling is performed.
|
93 |
+
- `nbest_size > 1`: samples from the nbest_size results.
|
94 |
+
- `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
|
95 |
+
using forward-filtering-and-backward-sampling algorithm.
|
96 |
+
|
97 |
+
- `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
|
98 |
+
BPE-dropout.
|
99 |
+
|
100 |
+
add_bos_token (`bool`, *optional*, defaults to `True`):
|
101 |
+
Whether or not to add an `bos_token` at the start of sequences.
|
102 |
+
add_eos_token (`bool`, *optional*, defaults to `False`):
|
103 |
+
Whether or not to add an `eos_token` at the end of sequences.
|
104 |
+
clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`):
|
105 |
+
Whether or not to cleanup spaces after decoding, cleanup consists in removing potential artifacts like
|
106 |
+
extra spaces.
|
107 |
+
use_default_system_prompt (`bool`, *optional*, defaults to `False`):
|
108 |
+
Whether or not the default system prompt for Llama should be used.
|
109 |
+
spaces_between_special_tokens (`bool`, *optional*, defaults to `False`):
|
110 |
+
Whether or not to add spaces between special tokens.
|
111 |
+
legacy (`bool`, *optional*):
|
112 |
+
Whether or not the `legacy` behavior of the tokenizer should be used. Legacy is before the merge of #24622
|
113 |
+
and #25224 which includes fixes to properly handle tokens that appear after special tokens. A simple
|
114 |
+
example:
|
115 |
+
|
116 |
+
- `legacy=True`:
|
117 |
+
```python
|
118 |
+
>>> from transformers import T5Tokenizer
|
119 |
+
|
120 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=True)
|
121 |
+
>>> tokenizer.encode("Hello <extra_id_0>.")
|
122 |
+
[8774, 32099, 3, 5, 1]
|
123 |
+
```
|
124 |
+
- `legacy=False`:
|
125 |
+
```python
|
126 |
+
>>> from transformers import T5Tokenizer
|
127 |
+
|
128 |
+
>>> tokenizer = T5Tokenizer.from_pretrained("t5-base", legacy=False)
|
129 |
+
>>> tokenizer.encode("Hello <extra_id_0>.") # the extra space `[3]` is no longer here
|
130 |
+
[8774, 32099, 5, 1]
|
131 |
+
```
|
132 |
+
Checkout the [pull request](https://github.com/huggingface/transformers/pull/24565) for more details.
|
133 |
+
|
134 |
+
"""
|
135 |
+
|
136 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
137 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
138 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
139 |
+
model_input_names = ["input_ids", "attention_mask"]
|
140 |
+
|
141 |
+
def __init__(
|
142 |
+
self,
|
143 |
+
vocab_file,
|
144 |
+
unk_token="<unk>",
|
145 |
+
bos_token="<s>",
|
146 |
+
eos_token="</s>",
|
147 |
+
pad_token=None,
|
148 |
+
sp_model_kwargs: Optional[Dict[str, Any]] = None,
|
149 |
+
add_bos_token=True,
|
150 |
+
add_eos_token=False,
|
151 |
+
clean_up_tokenization_spaces=False,
|
152 |
+
use_default_system_prompt=False,
|
153 |
+
spaces_between_special_tokens=False,
|
154 |
+
legacy=None,
|
155 |
+
**kwargs,
|
156 |
+
):
|
157 |
+
self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
|
158 |
+
bos_token = AddedToken(bos_token, normalized=False, special=True) if isinstance(bos_token, str) else bos_token
|
159 |
+
eos_token = AddedToken(eos_token, normalized=False, special=True) if isinstance(eos_token, str) else eos_token
|
160 |
+
unk_token = AddedToken(unk_token, normalized=False, special=True) if isinstance(unk_token, str) else unk_token
|
161 |
+
pad_token = AddedToken(pad_token, normalized=False, special=True) if isinstance(pad_token, str) else pad_token
|
162 |
+
|
163 |
+
if legacy is None:
|
164 |
+
logger.warning_once(
|
165 |
+
f"You are using the default legacy behaviour of the {self.__class__}. This is"
|
166 |
+
" expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you."
|
167 |
+
" If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it"
|
168 |
+
" means, and thoroughly read the reason why this was added as explained in"
|
169 |
+
" https://github.com/huggingface/transformers/pull/24565"
|
170 |
+
)
|
171 |
+
legacy = True
|
172 |
+
|
173 |
+
self.legacy = legacy
|
174 |
+
self.vocab_file = vocab_file
|
175 |
+
self.add_bos_token = add_bos_token
|
176 |
+
self.add_eos_token = add_eos_token
|
177 |
+
self.use_default_system_prompt = use_default_system_prompt
|
178 |
+
self.sp_model = self.get_spm_processor(kwargs.pop("from_slow", False))
|
179 |
+
|
180 |
+
super().__init__(
|
181 |
+
bos_token=bos_token,
|
182 |
+
eos_token=eos_token,
|
183 |
+
unk_token=unk_token,
|
184 |
+
pad_token=pad_token,
|
185 |
+
add_bos_token=add_bos_token,
|
186 |
+
add_eos_token=add_eos_token,
|
187 |
+
sp_model_kwargs=self.sp_model_kwargs,
|
188 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
189 |
+
use_default_system_prompt=use_default_system_prompt,
|
190 |
+
spaces_between_special_tokens=spaces_between_special_tokens,
|
191 |
+
legacy=legacy,
|
192 |
+
**kwargs,
|
193 |
+
)
|
194 |
+
|
195 |
+
@property
|
196 |
+
def unk_token_length(self):
|
197 |
+
return len(self.sp_model.encode(str(self.unk_token)))
|
198 |
+
|
199 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.get_spm_processor
|
200 |
+
def get_spm_processor(self, from_slow=False):
|
201 |
+
tokenizer = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
202 |
+
if self.legacy or from_slow: # no dependency on protobuf
|
203 |
+
tokenizer.Load(self.vocab_file)
|
204 |
+
return tokenizer
|
205 |
+
|
206 |
+
with open(self.vocab_file, "rb") as f:
|
207 |
+
sp_model = f.read()
|
208 |
+
model_pb2 = import_protobuf(f"The new behaviour of {self.__class__.__name__} (with `self.legacy = False`)")
|
209 |
+
model = model_pb2.ModelProto.FromString(sp_model)
|
210 |
+
normalizer_spec = model_pb2.NormalizerSpec()
|
211 |
+
normalizer_spec.add_dummy_prefix = False
|
212 |
+
model.normalizer_spec.MergeFrom(normalizer_spec)
|
213 |
+
sp_model = model.SerializeToString()
|
214 |
+
tokenizer.LoadFromSerializedProto(sp_model)
|
215 |
+
return tokenizer
|
216 |
+
|
217 |
+
def __getstate__(self):
|
218 |
+
state = self.__dict__.copy()
|
219 |
+
state["sp_model"] = None
|
220 |
+
state["sp_model_proto"] = self.sp_model.serialized_model_proto()
|
221 |
+
return state
|
222 |
+
|
223 |
+
def __setstate__(self, d):
|
224 |
+
self.__dict__ = d
|
225 |
+
self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
|
226 |
+
self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
|
227 |
+
|
228 |
+
@property
|
229 |
+
def vocab_size(self):
|
230 |
+
"""Returns vocab size"""
|
231 |
+
return self.sp_model.get_piece_size()
|
232 |
+
|
233 |
+
def get_vocab(self):
|
234 |
+
"""Returns vocab as a dict"""
|
235 |
+
vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
|
236 |
+
vocab.update(self.added_tokens_encoder)
|
237 |
+
return vocab
|
238 |
+
|
239 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer.tokenize
|
240 |
+
def tokenize(self, text: "TextInput", add_special_tokens=False, **kwargs) -> List[str]:
|
241 |
+
"""
|
242 |
+
Converts a string to a list of tokens. If `self.legacy` is set to `False`, a prefix token is added unless the
|
243 |
+
first token is special.
|
244 |
+
"""
|
245 |
+
if self.legacy or len(text) == 0:
|
246 |
+
return super().tokenize(text, **kwargs)
|
247 |
+
|
248 |
+
tokens = super().tokenize(SPIECE_UNDERLINE + text.replace(SPIECE_UNDERLINE, " "), **kwargs)
|
249 |
+
|
250 |
+
if len(tokens) > 1 and tokens[0] == SPIECE_UNDERLINE and tokens[1] in self.all_special_tokens:
|
251 |
+
tokens = tokens[1:]
|
252 |
+
return tokens
|
253 |
+
|
254 |
+
# Copied from transformers.models.t5.tokenization_t5.T5Tokenizer._tokenize
|
255 |
+
def _tokenize(self, text, **kwargs):
|
256 |
+
"""
|
257 |
+
Returns a tokenized string.
|
258 |
+
|
259 |
+
We de-activated the `add_dummy_prefix` option, thus the sentencepiece internals will always strip any
|
260 |
+
SPIECE_UNDERLINE. For example: `self.sp_model.encode(f"{SPIECE_UNDERLINE}Hey", out_type = str)` will give
|
261 |
+
`['H', 'e', 'y']` instead of `['▁He', 'y']`. Thus we always encode `f"{unk_token}text"` and strip the
|
262 |
+
`unk_token`. Here is an example with `unk_token = "<unk>"` and `unk_token_length = 4`.
|
263 |
+
`self.tokenizer.sp_model.encode("<unk> Hey", out_type = str)[4:]`.
|
264 |
+
"""
|
265 |
+
tokens = self.sp_model.encode(text, out_type=str)
|
266 |
+
if self.legacy or not text.startswith((SPIECE_UNDERLINE, " ")):
|
267 |
+
return tokens
|
268 |
+
|
269 |
+
# 1. Encode string + prefix ex: "<unk> Hey"
|
270 |
+
tokens = self.sp_model.encode(self.unk_token + text, out_type=str)
|
271 |
+
# 2. Remove self.unk_token from ['<','unk','>', '▁Hey']
|
272 |
+
return tokens[self.unk_token_length :] if len(tokens) >= self.unk_token_length else tokens
|
273 |
+
|
274 |
+
def _convert_token_to_id(self, token):
|
275 |
+
"""Converts a token (str) in an id using the vocab."""
|
276 |
+
return self.sp_model.piece_to_id(token)
|
277 |
+
|
278 |
+
def _convert_id_to_token(self, index):
|
279 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
280 |
+
token = self.sp_model.IdToPiece(index)
|
281 |
+
return token
|
282 |
+
|
283 |
+
def convert_tokens_to_string(self, tokens):
|
284 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
285 |
+
# since we manually add the prefix space, we have to remove it when decoding
|
286 |
+
if tokens[0].startswith(SPIECE_UNDERLINE):
|
287 |
+
tokens[0] = tokens[0][1:]
|
288 |
+
|
289 |
+
current_sub_tokens = []
|
290 |
+
out_string = ""
|
291 |
+
prev_is_special = False
|
292 |
+
for i, token in enumerate(tokens):
|
293 |
+
# make sure that special tokens are not decoded using sentencepiece model
|
294 |
+
if token in self.all_special_tokens:
|
295 |
+
if not prev_is_special and i != 0 and self.legacy:
|
296 |
+
out_string += " "
|
297 |
+
out_string += self.sp_model.decode(current_sub_tokens) + token
|
298 |
+
prev_is_special = True
|
299 |
+
current_sub_tokens = []
|
300 |
+
else:
|
301 |
+
current_sub_tokens.append(token)
|
302 |
+
prev_is_special = False
|
303 |
+
out_string += self.sp_model.decode(current_sub_tokens)
|
304 |
+
return out_string
|
305 |
+
|
306 |
+
def save_vocabulary(self, save_directory, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
307 |
+
"""
|
308 |
+
Save the vocabulary and special tokens file to a directory.
|
309 |
+
|
310 |
+
Args:
|
311 |
+
save_directory (`str`):
|
312 |
+
The directory in which to save the vocabulary.
|
313 |
+
|
314 |
+
Returns:
|
315 |
+
`Tuple(str)`: Paths to the files saved.
|
316 |
+
"""
|
317 |
+
if not os.path.isdir(save_directory):
|
318 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
319 |
+
return
|
320 |
+
out_vocab_file = os.path.join(
|
321 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
322 |
+
)
|
323 |
+
|
324 |
+
if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
|
325 |
+
copyfile(self.vocab_file, out_vocab_file)
|
326 |
+
elif not os.path.isfile(self.vocab_file):
|
327 |
+
with open(out_vocab_file, "wb") as fi:
|
328 |
+
content_spiece_model = self.sp_model.serialized_model_proto()
|
329 |
+
fi.write(content_spiece_model)
|
330 |
+
|
331 |
+
return (out_vocab_file,)
|
332 |
+
|
333 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
334 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
335 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
336 |
+
|
337 |
+
output = bos_token_id + token_ids_0 + eos_token_id
|
338 |
+
|
339 |
+
if token_ids_1 is not None:
|
340 |
+
output = output + bos_token_id + token_ids_1 + eos_token_id
|
341 |
+
|
342 |
+
return output
|
343 |
+
|
344 |
+
def get_special_tokens_mask(
|
345 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
|
346 |
+
) -> List[int]:
|
347 |
+
"""
|
348 |
+
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
|
349 |
+
special tokens using the tokenizer `prepare_for_model` method.
|
350 |
+
|
351 |
+
Args:
|
352 |
+
token_ids_0 (`List[int]`):
|
353 |
+
List of IDs.
|
354 |
+
token_ids_1 (`List[int]`, *optional*):
|
355 |
+
Optional second list of IDs for sequence pairs.
|
356 |
+
already_has_special_tokens (`bool`, *optional*, defaults to `False`):
|
357 |
+
Whether or not the token list is already formatted with special tokens for the model.
|
358 |
+
|
359 |
+
Returns:
|
360 |
+
`List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
|
361 |
+
"""
|
362 |
+
if already_has_special_tokens:
|
363 |
+
return super().get_special_tokens_mask(
|
364 |
+
token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
|
365 |
+
)
|
366 |
+
|
367 |
+
bos_token_id = [1] if self.add_bos_token else []
|
368 |
+
eos_token_id = [1] if self.add_eos_token else []
|
369 |
+
|
370 |
+
if token_ids_1 is None:
|
371 |
+
return bos_token_id + ([0] * len(token_ids_0)) + eos_token_id
|
372 |
+
return (
|
373 |
+
bos_token_id
|
374 |
+
+ ([0] * len(token_ids_0))
|
375 |
+
+ eos_token_id
|
376 |
+
+ bos_token_id
|
377 |
+
+ ([0] * len(token_ids_1))
|
378 |
+
+ eos_token_id
|
379 |
+
)
|
380 |
+
|
381 |
+
def create_token_type_ids_from_sequences(
|
382 |
+
self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
|
383 |
+
) -> List[int]:
|
384 |
+
"""
|
385 |
+
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An ALBERT
|
386 |
+
sequence pair mask has the following format:
|
387 |
+
|
388 |
+
```
|
389 |
+
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
|
390 |
+
| first sequence | second sequence |
|
391 |
+
```
|
392 |
+
|
393 |
+
if token_ids_1 is None, only returns the first portion of the mask (0s).
|
394 |
+
|
395 |
+
Args:
|
396 |
+
token_ids_0 (`List[int]`):
|
397 |
+
List of ids.
|
398 |
+
token_ids_1 (`List[int]`, *optional*):
|
399 |
+
Optional second list of IDs for sequence pairs.
|
400 |
+
|
401 |
+
Returns:
|
402 |
+
`List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
|
403 |
+
"""
|
404 |
+
bos_token_id = [self.bos_token_id] if self.add_bos_token else []
|
405 |
+
eos_token_id = [self.eos_token_id] if self.add_eos_token else []
|
406 |
+
|
407 |
+
output = [0] * len(bos_token_id + token_ids_0 + eos_token_id)
|
408 |
+
|
409 |
+
if token_ids_1 is not None:
|
410 |
+
output += [1] * len(bos_token_id + token_ids_1 + eos_token_id)
|
411 |
+
|
412 |
+
return output
|
413 |
+
|
414 |
+
@property
|
415 |
+
def default_chat_template(self):
|
416 |
+
"""
|
417 |
+
LLaMA uses [INST] and [/INST] to indicate user messages, and <<SYS>> and <</SYS>> to indicate system messages.
|
418 |
+
Assistant messages do not have special tokens, because LLaMA chat models are generally trained with strict
|
419 |
+
user/assistant/user/assistant message ordering, and so assistant messages can be identified from the ordering
|
420 |
+
rather than needing special tokens. The system message is partly 'embedded' in the first user message, which
|
421 |
+
results in an unusual token ordering when it is present. This template should definitely be changed if you wish
|
422 |
+
to fine-tune a model with more flexible role ordering!
|
423 |
+
|
424 |
+
The output should look something like:
|
425 |
+
|
426 |
+
<bos>[INST] B_SYS SystemPrompt E_SYS Prompt [/INST] Answer <eos><bos>[INST] Prompt [/INST] Answer <eos>
|
427 |
+
<bos>[INST] Prompt [/INST]
|
428 |
+
|
429 |
+
The reference for this chat template is [this code
|
430 |
+
snippet](https://github.com/facebookresearch/llama/blob/556949fdfb72da27c2f4a40b7f0e4cf0b8153a28/llama/generation.py#L320-L362)
|
431 |
+
in the original repository.
|
432 |
+
"""
|
433 |
+
logger.warning_once(
|
434 |
+
"\nNo chat template is defined for this tokenizer - using the default template "
|
435 |
+
f"for the {self.__class__.__name__} class. If the default is not appropriate for "
|
436 |
+
"your model, please set `tokenizer.chat_template` to an appropriate template. "
|
437 |
+
"See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
|
438 |
+
)
|
439 |
+
template = (
|
440 |
+
"{% if messages[0]['role'] == 'system' %}"
|
441 |
+
"{% set loop_messages = messages[1:] %}" # Extract system message if it's present
|
442 |
+
"{% set system_message = messages[0]['content'] %}"
|
443 |
+
"{% elif USE_DEFAULT_PROMPT == true and not '<<SYS>>' in messages[0]['content'] %}"
|
444 |
+
"{% set loop_messages = messages %}" # Or use the default system message if the flag is set
|
445 |
+
"{% set system_message = 'DEFAULT_SYSTEM_MESSAGE' %}"
|
446 |
+
"{% else %}"
|
447 |
+
"{% set loop_messages = messages %}"
|
448 |
+
"{% set system_message = false %}"
|
449 |
+
"{% endif %}"
|
450 |
+
"{% for message in loop_messages %}" # Loop over all non-system messages
|
451 |
+
"{% if (message['role'] == 'user') != (loop.index0 % 2 == 0) %}"
|
452 |
+
"{{ raise_exception('Conversation roles must alternate user/assistant/user/assistant/...') }}"
|
453 |
+
"{% endif %}"
|
454 |
+
"{% if loop.index0 == 0 and system_message != false %}" # Embed system message in first message
|
455 |
+
"{% set content = '<<SYS>>\\n' + system_message + '\\n<</SYS>>\\n\\n' + message['content'] %}"
|
456 |
+
"{% else %}"
|
457 |
+
"{% set content = message['content'] %}"
|
458 |
+
"{% endif %}"
|
459 |
+
"{% if message['role'] == 'user' %}" # After all of that, handle messages/roles in a fairly normal way
|
460 |
+
"{{ bos_token + '[INST] ' + content.strip() + ' [/INST]' }}"
|
461 |
+
"{% elif message['role'] == 'system' %}"
|
462 |
+
"{{ '<<SYS>>\\n' + content.strip() + '\\n<</SYS>>\\n\\n' }}"
|
463 |
+
"{% elif message['role'] == 'assistant' %}"
|
464 |
+
"{{ ' ' + content.strip() + ' ' + eos_token }}"
|
465 |
+
"{% endif %}"
|
466 |
+
"{% endfor %}"
|
467 |
+
)
|
468 |
+
template = template.replace("USE_DEFAULT_PROMPT", "true" if self.use_default_system_prompt else "false")
|
469 |
+
default_message = DEFAULT_SYSTEM_PROMPT.replace("\n", "\\n").replace("'", "\\'")
|
470 |
+
template = template.replace("DEFAULT_SYSTEM_MESSAGE", default_message)
|
471 |
+
|
472 |
+
return template
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer.model
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9e556afd44213b6bd1be2b850ebbbd98f5481437a8021afaf58ee7fb1818d347
|
3 |
+
size 499723
|
tokenizer_config.json
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_bos_token": true,
|
3 |
+
"add_eos_token": false,
|
4 |
+
"bos_token": {
|
5 |
+
"__type": "AddedToken",
|
6 |
+
"content": "<s>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false
|
11 |
+
},
|
12 |
+
"clean_up_tokenization_spaces": false,
|
13 |
+
"eos_token": {
|
14 |
+
"__type": "AddedToken",
|
15 |
+
"content": "</s>",
|
16 |
+
"lstrip": false,
|
17 |
+
"normalized": false,
|
18 |
+
"rstrip": false,
|
19 |
+
"single_word": false
|
20 |
+
},
|
21 |
+
"legacy": false,
|
22 |
+
"model_max_length": 1000000000000000019884624838656,
|
23 |
+
"pad_token": null,
|
24 |
+
"padding_side": "right",
|
25 |
+
"sp_model_kwargs": {},
|
26 |
+
"tokenizer_class": "LlamaTokenizer",
|
27 |
+
"unk_token": {
|
28 |
+
"__type": "AddedToken",
|
29 |
+
"content": "<unk>",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": false,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false
|
34 |
+
}
|
35 |
+
}
|
truthx.py
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from torch import nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from abc import abstractmethod
|
5 |
+
from torch import tensor as Tensor
|
6 |
+
from typing import List, Any
|
7 |
+
|
8 |
+
|
9 |
+
class BaseVAE(nn.Module):
|
10 |
+
|
11 |
+
def __init__(self) -> None:
|
12 |
+
super(BaseVAE, self).__init__()
|
13 |
+
|
14 |
+
def encode(self, input: Tensor) -> List[Tensor]:
|
15 |
+
raise NotImplementedError
|
16 |
+
|
17 |
+
def decode(self, input: Tensor) -> Any:
|
18 |
+
raise NotImplementedError
|
19 |
+
|
20 |
+
def sample(self, batch_size: int, current_device: int, **kwargs) -> Tensor:
|
21 |
+
raise NotImplementedError
|
22 |
+
|
23 |
+
def generate(self, x: Tensor, **kwargs) -> Tensor:
|
24 |
+
raise NotImplementedError
|
25 |
+
|
26 |
+
@abstractmethod
|
27 |
+
def forward(self, *inputs: Tensor) -> Tensor:
|
28 |
+
pass
|
29 |
+
|
30 |
+
@abstractmethod
|
31 |
+
def loss_function(self, *inputs: Any, **kwargs) -> Tensor:
|
32 |
+
pass
|
33 |
+
|
34 |
+
|
35 |
+
class MLPAE(BaseVAE):
|
36 |
+
def __init__(
|
37 |
+
self,
|
38 |
+
in_channels: int,
|
39 |
+
semantic_latent_dim: int,
|
40 |
+
truthful_latent_dim: int,
|
41 |
+
semantic_hidden_dims: List = None,
|
42 |
+
truthful_hidden_dims: List = None,
|
43 |
+
decoder_hidden_dims: List = None,
|
44 |
+
**kwargs
|
45 |
+
) -> None:
|
46 |
+
super(MLPAE, self).__init__()
|
47 |
+
|
48 |
+
self.semantic_latent_dim = semantic_latent_dim
|
49 |
+
|
50 |
+
if semantic_hidden_dims is None:
|
51 |
+
semantic_hidden_dims = []
|
52 |
+
|
53 |
+
# Build Semantic Encoder
|
54 |
+
semantic_encoder_modules = []
|
55 |
+
flat_size = in_channels
|
56 |
+
for h_dim in semantic_hidden_dims:
|
57 |
+
semantic_encoder_modules.append(
|
58 |
+
nn.Sequential(
|
59 |
+
nn.Linear(flat_size, h_dim), nn.LayerNorm(h_dim), nn.LeakyReLU()
|
60 |
+
)
|
61 |
+
)
|
62 |
+
flat_size = h_dim
|
63 |
+
semantic_encoder_modules.append(
|
64 |
+
nn.Sequential(
|
65 |
+
nn.Linear(flat_size, semantic_latent_dim),
|
66 |
+
nn.LayerNorm(semantic_latent_dim),
|
67 |
+
nn.LeakyReLU(),
|
68 |
+
)
|
69 |
+
)
|
70 |
+
|
71 |
+
self.semantic_encoder = nn.Sequential(*semantic_encoder_modules)
|
72 |
+
|
73 |
+
if truthful_hidden_dims is None:
|
74 |
+
truthful_hidden_dims = []
|
75 |
+
|
76 |
+
# Build Truthful Encoder
|
77 |
+
truthful_encoder_modules = []
|
78 |
+
flat_size = in_channels
|
79 |
+
for h_dim in truthful_hidden_dims:
|
80 |
+
truthful_encoder_modules.append(
|
81 |
+
nn.Sequential(
|
82 |
+
(
|
83 |
+
nn.Linear(flat_size, h_dim)
|
84 |
+
if flat_size != h_dim
|
85 |
+
else nn.Identity()
|
86 |
+
),
|
87 |
+
nn.LayerNorm(h_dim),
|
88 |
+
nn.LeakyReLU(),
|
89 |
+
)
|
90 |
+
)
|
91 |
+
flat_size = h_dim
|
92 |
+
truthful_encoder_modules.append(
|
93 |
+
nn.Sequential(
|
94 |
+
(
|
95 |
+
nn.Linear(flat_size, truthful_latent_dim)
|
96 |
+
if flat_size != truthful_latent_dim
|
97 |
+
else nn.Identity()
|
98 |
+
),
|
99 |
+
nn.LayerNorm(truthful_latent_dim),
|
100 |
+
nn.LeakyReLU(),
|
101 |
+
)
|
102 |
+
)
|
103 |
+
|
104 |
+
self.truthful_encoder = nn.Sequential(*truthful_encoder_modules)
|
105 |
+
|
106 |
+
# Cross-Attention Module
|
107 |
+
self.num_heads = 1
|
108 |
+
self.cross_attention = nn.MultiheadAttention(
|
109 |
+
embed_dim=semantic_latent_dim, num_heads=self.num_heads
|
110 |
+
)
|
111 |
+
|
112 |
+
self.proj = None
|
113 |
+
if semantic_latent_dim != truthful_latent_dim:
|
114 |
+
self.proj = nn.Linear(truthful_latent_dim, semantic_latent_dim, bias=False)
|
115 |
+
|
116 |
+
# Build Decoder
|
117 |
+
decoder_modules = []
|
118 |
+
if len(decoder_hidden_dims) > 0:
|
119 |
+
flat_size = semantic_latent_dim
|
120 |
+
for h_dim in decoder_hidden_dims:
|
121 |
+
decoder_modules.append(
|
122 |
+
nn.Sequential(
|
123 |
+
nn.Linear(flat_size, h_dim), nn.LayerNorm(h_dim), nn.LeakyReLU()
|
124 |
+
)
|
125 |
+
)
|
126 |
+
flat_size = h_dim
|
127 |
+
|
128 |
+
flat_size = decoder_hidden_dims[-1]
|
129 |
+
self.decoder = nn.Sequential(*decoder_modules)
|
130 |
+
else:
|
131 |
+
self.decoder_input = None
|
132 |
+
|
133 |
+
self.decoder = None
|
134 |
+
flat_size = semantic_latent_dim
|
135 |
+
self.final_layer = nn.Sequential(nn.Linear(flat_size, in_channels))
|
136 |
+
|
137 |
+
def encode_semantic(self, input: Tensor) -> List[Tensor]:
|
138 |
+
semantic_latent_rep = self.semantic_encoder(input)
|
139 |
+
return semantic_latent_rep
|
140 |
+
|
141 |
+
def encode_truthful(self, input: Tensor) -> List[Tensor]:
|
142 |
+
truthful_latent_rep = self.truthful_encoder(input)
|
143 |
+
truthful_latent_rep = F.normalize(truthful_latent_rep, p=2, dim=-1)
|
144 |
+
|
145 |
+
return truthful_latent_rep
|
146 |
+
|
147 |
+
def attention(self, query: Tensor, key: Tensor, value: Tensor) -> Tensor:
|
148 |
+
if self.proj is not None and query.size(-1) != key.size(-1):
|
149 |
+
key = self.proj(key)
|
150 |
+
value = self.proj(value)
|
151 |
+
query = query.unsqueeze(0)
|
152 |
+
key = key.unsqueeze(0)
|
153 |
+
value = value.unsqueeze(0)
|
154 |
+
|
155 |
+
output, attention_weights = self.cross_attention(query, key, value)
|
156 |
+
|
157 |
+
return output[0]
|
158 |
+
|
159 |
+
def decode(self, z: Tensor) -> Tensor:
|
160 |
+
result = z
|
161 |
+
if self.decoder is not None:
|
162 |
+
result = self.decoder(result)
|
163 |
+
result = self.final_layer(result)
|
164 |
+
return result
|
165 |
+
|
166 |
+
def forward(
|
167 |
+
self, input: Tensor, truthful_latent_rep=None, **kwargs
|
168 |
+
) -> List[Tensor]:
|
169 |
+
semantic_latent_rep = self.encode_semantic(input)
|
170 |
+
if truthful_latent_rep is None:
|
171 |
+
truthful_latent_rep = self.encode_truthful(input)
|
172 |
+
truthful_latent_rep = truthful_latent_rep.reshape(
|
173 |
+
-1, truthful_latent_rep.size(-1)
|
174 |
+
)
|
175 |
+
z = semantic_latent_rep + self.attention(
|
176 |
+
semantic_latent_rep,
|
177 |
+
truthful_latent_rep.contiguous(),
|
178 |
+
truthful_latent_rep.contiguous(),
|
179 |
+
)
|
180 |
+
output = self.decode(z)
|
181 |
+
|
182 |
+
return [output, input, semantic_latent_rep, truthful_latent_rep]
|
183 |
+
|
184 |
+
def forward_decoder(self, input, semantic_latent_rep, truthful_latent_rep):
|
185 |
+
z = semantic_latent_rep + self.attention(
|
186 |
+
semantic_latent_rep, truthful_latent_rep, truthful_latent_rep
|
187 |
+
)
|
188 |
+
output = self.decode(z)
|
189 |
+
return [output, input, semantic_latent_rep, truthful_latent_rep]
|
190 |
+
|
191 |
+
def get_semantic_latent_rep(self, input: Tensor, **kwargs) -> List[Tensor]:
|
192 |
+
semantic_latent_rep = self.encode_semantic(input)
|
193 |
+
return semantic_latent_rep
|
194 |
+
|
195 |
+
def get_truthful_latent_rep(self, input: Tensor, **kwargs) -> List[Tensor]:
|
196 |
+
truthful_latent_rep = self.encode_truthful(input)
|
197 |
+
return truthful_latent_rep
|
198 |
+
|
199 |
+
def loss_function(self, *args, **kwargs) -> dict:
|
200 |
+
recons = args[0]
|
201 |
+
input = args[1]
|
202 |
+
recons_loss = F.mse_loss(recons, input)
|
203 |
+
|
204 |
+
loss = recons_loss
|
205 |
+
return {"loss": loss, "Reconstruction_Loss": recons_loss.detach()}
|
206 |
+
|
207 |
+
|
208 |
+
class TruthX:
|
209 |
+
def __init__(self, model_path, hidden_size, edit_strength=1.0, top_layers=10):
|
210 |
+
|
211 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
212 |
+
|
213 |
+
checkpoint = torch.load(model_path)
|
214 |
+
args = checkpoint["args"]
|
215 |
+
|
216 |
+
semantic_latent_dim = args.semantic_latent_dim # Adjust as needed
|
217 |
+
truthful_latent_dim = args.truthful_latent_dim
|
218 |
+
semantic_hidden_dims = (
|
219 |
+
[int(_) for _ in args.semantic_hidden_dims.split(",")]
|
220 |
+
if args.semantic_hidden_dims != ""
|
221 |
+
else []
|
222 |
+
)
|
223 |
+
truthful_hidden_dims = (
|
224 |
+
[int(_) for _ in args.truthful_hidden_dims.split(",")]
|
225 |
+
if args.truthful_hidden_dims != ""
|
226 |
+
else []
|
227 |
+
)
|
228 |
+
decoder_hidden_dims = (
|
229 |
+
[int(_) for _ in args.decoder_hidden_dims.split(",")]
|
230 |
+
if args.decoder_hidden_dims != ""
|
231 |
+
else []
|
232 |
+
)
|
233 |
+
|
234 |
+
ae_model = MLPAE(
|
235 |
+
in_channels=hidden_size,
|
236 |
+
semantic_latent_dim=semantic_latent_dim,
|
237 |
+
truthful_latent_dim=truthful_latent_dim,
|
238 |
+
semantic_hidden_dims=semantic_hidden_dims,
|
239 |
+
truthful_hidden_dims=truthful_hidden_dims,
|
240 |
+
decoder_hidden_dims=decoder_hidden_dims,
|
241 |
+
).to(device)
|
242 |
+
|
243 |
+
ae_model.load_state_dict(checkpoint["state_dict"])
|
244 |
+
|
245 |
+
ae_model.pos_center = ((checkpoint["pos_center"])).to(device)
|
246 |
+
ae_model.neg_center = ((checkpoint["neg_center"])).to(device)
|
247 |
+
ae_model.eval()
|
248 |
+
ae_model.to(device)
|
249 |
+
self.ae_model = ae_model
|
250 |
+
|
251 |
+
self.rank = checkpoint["rank"]
|
252 |
+
|
253 |
+
self.top_layers = top_layers
|
254 |
+
self.edit_strength = edit_strength
|
255 |
+
self.cur_layer_id = 0
|
256 |
+
self.prompt_length = None
|
257 |
+
self.mc = False
|
258 |
+
|
259 |
+
@torch.inference_mode()
|
260 |
+
def edit(self, X):
|
261 |
+
layer_id = int(self.cur_layer_id.split(".")[0])
|
262 |
+
if self.cur_layer_id.endswith("attn"):
|
263 |
+
layer_id = 2 * layer_id
|
264 |
+
else:
|
265 |
+
layer_id = 2 * layer_id + 1
|
266 |
+
|
267 |
+
if self.rank[layer_id] > self.top_layers:
|
268 |
+
return X
|
269 |
+
|
270 |
+
bsz, s_len, d = X.size()
|
271 |
+
x = (
|
272 |
+
X.contiguous()
|
273 |
+
.view(-1, d)
|
274 |
+
.type_as(self.ae_model.semantic_encoder[0][0].weight)
|
275 |
+
)
|
276 |
+
x_truthful = self.ae_model.get_truthful_latent_rep(
|
277 |
+
X.type_as(self.ae_model.semantic_encoder[0][0].weight)
|
278 |
+
)
|
279 |
+
|
280 |
+
pos_center = self.ae_model.pos_center[layer_id].unsqueeze(0)
|
281 |
+
neg_center = self.ae_model.neg_center[layer_id].unsqueeze(0)
|
282 |
+
|
283 |
+
delta = (pos_center - neg_center).unsqueeze(0)
|
284 |
+
recon_x_pos = (
|
285 |
+
self.ae_model(
|
286 |
+
x,
|
287 |
+
truthful_latent_rep=F.normalize(
|
288 |
+
x_truthful + delta, p=2, dim=-1
|
289 |
+
).type_as(x),
|
290 |
+
)[0]
|
291 |
+
.contiguous()
|
292 |
+
.view(bsz, s_len, d)
|
293 |
+
)
|
294 |
+
recon_x_neg = (
|
295 |
+
self.ae_model(
|
296 |
+
x,
|
297 |
+
truthful_latent_rep=F.normalize(
|
298 |
+
x_truthful - delta, p=2, dim=-1
|
299 |
+
).type_as(x),
|
300 |
+
)[0]
|
301 |
+
.contiguous()
|
302 |
+
.view(bsz, s_len, d)
|
303 |
+
)
|
304 |
+
Delta = recon_x_pos - recon_x_neg
|
305 |
+
Delta = Delta.contiguous().to(X.dtype)
|
306 |
+
Delta = F.normalize(Delta, p=2, dim=-1).type_as(X) * torch.norm(
|
307 |
+
X, p=2, dim=-1
|
308 |
+
).unsqueeze(2)
|
309 |
+
|
310 |
+
mask = torch.ones((bsz, s_len), device=Delta.device)
|
311 |
+
|
312 |
+
if self.mc:
|
313 |
+
# multiple-choice, only edit the tokens in answer
|
314 |
+
mask[:, : self.prompt_length + 1] = 0
|
315 |
+
# probing those untruthful position
|
316 |
+
probing = (
|
317 |
+
torch.nn.functional.cosine_similarity(
|
318 |
+
x_truthful, neg_center.unsqueeze(1), dim=-1
|
319 |
+
)
|
320 |
+
- torch.nn.functional.cosine_similarity(
|
321 |
+
x_truthful, pos_center.unsqueeze(1), dim=-1
|
322 |
+
)
|
323 |
+
).clamp(0, 999)
|
324 |
+
mask = mask * probing
|
325 |
+
|
326 |
+
else:
|
327 |
+
# open-ended generation, only edit the generated token (i.e., last token)
|
328 |
+
mask[:, :-1] = 0
|
329 |
+
mask[:, -1:] = 1
|
330 |
+
|
331 |
+
new_X = X + (Delta.type_as(X)) * self.edit_strength * mask.unsqueeze(2).type_as(X)
|
332 |
+
return new_X
|
truthx_model.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:4fa2e743f8551f3c449c741a74c670d1a6121f50a40073a0ef9eac7cddc48b84
|
3 |
+
size 143270759
|