Delete patch before release (#3)
Browse files- Delete before release (7662a4150a62440e5cd64bc7c6cf1c556e00e573)
Co-authored-by: Pedro Cuenca <pcuenq@users.noreply.huggingface.co>
- patch.diff +0 -291
patch.diff
DELETED
@@ -1,291 +0,0 @@
|
|
1 |
-
diff --git a/src/transformers/models/llama/convert_llama_weights_to_hf.py b/src/transformers/models/llama/convert_llama_weights_to_hf.py
|
2 |
-
index a0fbe4680..8b0ce2b13 100644
|
3 |
-
--- a/src/transformers/models/llama/convert_llama_weights_to_hf.py
|
4 |
-
+++ b/src/transformers/models/llama/convert_llama_weights_to_hf.py
|
5 |
-
@@ -17,10 +17,10 @@ import json
|
6 |
-
import os
|
7 |
-
import shutil
|
8 |
-
import warnings
|
9 |
-
-
|
10 |
-
+from typing import List
|
11 |
-
import torch
|
12 |
-
|
13 |
-
-from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer, PreTrainedTokenizerFast
|
14 |
-
+from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer, PreTrainedTokenizerFast, GenerationConfig
|
15 |
-
from transformers.convert_slow_tokenizer import TikTokenConverter
|
16 |
-
|
17 |
-
|
18 |
-
@@ -85,8 +85,12 @@ NUM_SHARDS = {
|
19 |
-
"65B": 8,
|
20 |
-
"70B": 8,
|
21 |
-
"70Bf": 8,
|
22 |
-
+ "405B": 8,
|
23 |
-
+ "405B-MP16": 16,
|
24 |
-
}
|
25 |
-
|
26 |
-
+CONTEXT_LENGTH_FOR_VERSION = {"3.1": 131072, "3": 8192, "2": 4096, "1": 2048}
|
27 |
-
+
|
28 |
-
|
29 |
-
def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
|
30 |
-
return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
|
31 |
-
@@ -107,9 +111,10 @@ def write_model(
|
32 |
-
input_base_path,
|
33 |
-
model_size=None,
|
34 |
-
safe_serialization=True,
|
35 |
-
- llama_version=1,
|
36 |
-
+ llama_version="1",
|
37 |
-
vocab_size=None,
|
38 |
-
num_shards=None,
|
39 |
-
+ instruct=False,
|
40 |
-
):
|
41 |
-
os.makedirs(model_path, exist_ok=True)
|
42 |
-
tmp_model_path = os.path.join(model_path, "tmp")
|
43 |
-
@@ -125,18 +130,11 @@ def write_model(
|
44 |
-
dims_per_head = dim // n_heads
|
45 |
-
base = params.get("rope_theta", 10000.0)
|
46 |
-
inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
|
47 |
-
- if base > 10000.0 and llama_version != 3:
|
48 |
-
+ if base > 10000.0 and float(llama_version) < 3:
|
49 |
-
max_position_embeddings = 16384
|
50 |
-
else:
|
51 |
-
- # Depending on the Llama version, the default max_position_embeddings has different values.
|
52 |
-
- if llama_version == 1:
|
53 |
-
- max_position_embeddings = 2048
|
54 |
-
- elif llama_version == 2:
|
55 |
-
- max_position_embeddings = 4096
|
56 |
-
- elif llama_version == 3:
|
57 |
-
- max_position_embeddings = 8192
|
58 |
-
-
|
59 |
-
- vocab_size = vocab_size if vocab_size is not None else 32000
|
60 |
-
+ max_position_embeddings = CONTEXT_LENGTH_FOR_VERSION[llama_version]
|
61 |
-
+
|
62 |
-
if params.get("n_kv_heads", None) is not None:
|
63 |
-
num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
|
64 |
-
num_key_value_heads_per_shard = num_key_value_heads // num_shards
|
65 |
-
@@ -144,8 +142,7 @@ def write_model(
|
66 |
-
else: # compatibility with other checkpoints
|
67 |
-
num_key_value_heads = n_heads
|
68 |
-
num_key_value_heads_per_shard = n_heads_per_shard
|
69 |
-
- key_value_dim = dims_per_head * num_key_value_heads
|
70 |
-
- print(num_shards, num_key_value_heads, num_key_value_heads_per_shard, key_value_dim)
|
71 |
-
+ key_value_dim = dim
|
72 |
-
|
73 |
-
# permute for sliced rotary
|
74 |
-
def permute(w, n_heads, dim1=dim, dim2=dim):
|
75 |
-
@@ -159,11 +156,9 @@ def write_model(
|
76 |
-
loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
|
77 |
-
else:
|
78 |
-
# Sharded
|
79 |
-
- loaded = [
|
80 |
-
- torch.load(os.path.join(input_base_path, file), map_location="cpu")
|
81 |
-
- for file in os.listdir(input_base_path)
|
82 |
-
- if file.endswith(".pth")
|
83 |
-
- ]
|
84 |
-
+ checkpoint_list = sorted([file for file in os.listdir(input_base_path) if file.endswith(".pth")])
|
85 |
-
+ print("Loading in order:", checkpoint_list)
|
86 |
-
+ loaded = [torch.load(os.path.join(input_base_path, file), map_location="cpu") for file in checkpoint_list]
|
87 |
-
param_count = 0
|
88 |
-
index_dict = {"weight_map": {}}
|
89 |
-
for layer_i in range(n_layers):
|
90 |
-
@@ -263,7 +258,7 @@ def write_model(
|
91 |
-
"lm_head.weight": loaded["output.weight"],
|
92 |
-
}
|
93 |
-
else:
|
94 |
-
- concat_dim = 0 if llama_version == 3 else 1
|
95 |
-
+ concat_dim = 0 if llama_version in ['3', '3.1'] else 1
|
96 |
-
state_dict = {
|
97 |
-
"model.norm.weight": loaded[0]["norm.weight"],
|
98 |
-
"model.embed_tokens.weight": torch.cat(
|
99 |
-
@@ -282,6 +277,18 @@ def write_model(
|
100 |
-
write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
|
101 |
-
ffn_dim_multiplier = params["ffn_dim_multiplier"] if "ffn_dim_multiplier" in params else 1
|
102 |
-
multiple_of = params["multiple_of"] if "multiple_of" in params else 256
|
103 |
-
+
|
104 |
-
+ if llama_version in ['3', '3.1']:
|
105 |
-
+ bos_token_id = 128000
|
106 |
-
+
|
107 |
-
+ if instruct:
|
108 |
-
+ eos_token_id = [128001, 128008, 128009]
|
109 |
-
+ else:
|
110 |
-
+ eos_token_id = 128001
|
111 |
-
+ else:
|
112 |
-
+ bos_token_id = 1
|
113 |
-
+ eos_token_id = 2
|
114 |
-
+
|
115 |
-
config = LlamaConfig(
|
116 |
-
hidden_size=dim,
|
117 |
-
intermediate_size=compute_intermediate_size(dim, ffn_dim_multiplier, multiple_of),
|
118 |
-
@@ -292,11 +299,21 @@ def write_model(
|
119 |
-
vocab_size=vocab_size,
|
120 |
-
rope_theta=base,
|
121 |
-
max_position_embeddings=max_position_embeddings,
|
122 |
-
- bos_token_id=128000 if llama_version == 3 else 1,
|
123 |
-
- eos_token_id=128001 if llama_version == 3 else 2,
|
124 |
-
+ bos_token_id=bos_token_id,
|
125 |
-
+ eos_token_id=eos_token_id,
|
126 |
-
)
|
127 |
-
config.save_pretrained(tmp_model_path)
|
128 |
-
|
129 |
-
+ if instruct:
|
130 |
-
+ generation_config = GenerationConfig(
|
131 |
-
+ do_sample=True,
|
132 |
-
+ temperature=0.6,
|
133 |
-
+ top_p=0.9,
|
134 |
-
+ bos_token_id=bos_token_id,
|
135 |
-
+ eos_token_id=eos_token_id,
|
136 |
-
+ )
|
137 |
-
+ generation_config.save_pretrained(tmp_model_path)
|
138 |
-
+
|
139 |
-
# Make space so we can load the model properly now.
|
140 |
-
del state_dict
|
141 |
-
del loaded
|
142 |
-
@@ -313,7 +330,7 @@ def write_model(
|
143 |
-
|
144 |
-
|
145 |
-
class Llama3Converter(TikTokenConverter):
|
146 |
-
- def __init__(self, vocab_file, num_reserved_special_tokens=256, **kwargs):
|
147 |
-
+ def __init__(self, vocab_file, special_tokens=None, instruct=False, model_max_length=None, **kwargs):
|
148 |
-
super().__init__(vocab_file, **kwargs)
|
149 |
-
tokenizer = self.converted()
|
150 |
-
chat_template = (
|
151 |
-
@@ -327,34 +344,27 @@ class Llama3Converter(TikTokenConverter):
|
152 |
-
"{% endfor %}"
|
153 |
-
"{{ '<|start_header_id|>assistant<|end_header_id|>\n\n' }}"
|
154 |
-
)
|
155 |
-
- num_reserved_special_tokens = 256
|
156 |
-
- special_tokens = [
|
157 |
-
- "<|begin_of_text|>",
|
158 |
-
- "<|end_of_text|>",
|
159 |
-
- "<|reserved_special_token_0|>",
|
160 |
-
- "<|reserved_special_token_1|>",
|
161 |
-
- "<|reserved_special_token_2|>",
|
162 |
-
- "<|reserved_special_token_3|>",
|
163 |
-
- "<|start_header_id|>",
|
164 |
-
- "<|end_header_id|>",
|
165 |
-
- "<|reserved_special_token_4|>",
|
166 |
-
- "<|eot_id|>", # end of turn
|
167 |
-
- ] + [f"<|reserved_special_token_{i}|>" for i in range(5, num_reserved_special_tokens - 5)]
|
168 |
-
tokenizer.add_special_tokens(special_tokens)
|
169 |
-
|
170 |
-
self.tokenizer = PreTrainedTokenizerFast(
|
171 |
-
tokenizer_object=tokenizer,
|
172 |
-
bos_token="<|begin_of_text|>",
|
173 |
-
- eos_token="<|end_of_text|>",
|
174 |
-
- chat_template=chat_template,
|
175 |
-
+ eos_token="<|end_of_text|>" if not instruct else "<|eot_id|>",
|
176 |
-
+ chat_template=chat_template if instruct else None,
|
177 |
-
model_input_names=["input_ids", "attention_mask"],
|
178 |
-
+ model_max_length=model_max_length,
|
179 |
-
)
|
180 |
-
|
181 |
-
|
182 |
-
-def write_tokenizer(tokenizer_path, input_tokenizer_path, llama_version=2):
|
183 |
-
+def write_tokenizer(tokenizer_path, input_tokenizer_path, llama_version="2", special_tokens=None, instruct=False):
|
184 |
-
tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
|
185 |
-
- if llama_version == 3:
|
186 |
-
- tokenizer = Llama3Converter(input_tokenizer_path).tokenizer
|
187 |
-
+ if llama_version in ["3", "3.1"]:
|
188 |
-
+ tokenizer = Llama3Converter(
|
189 |
-
+ input_tokenizer_path,
|
190 |
-
+ special_tokens,
|
191 |
-
+ instruct,
|
192 |
-
+ model_max_length=CONTEXT_LENGTH_FOR_VERSION[llama_version]
|
193 |
-
+ ).tokenizer
|
194 |
-
else:
|
195 |
-
tokenizer = tokenizer_class(input_tokenizer_path)
|
196 |
-
print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
|
197 |
-
@@ -362,6 +372,37 @@ def write_tokenizer(tokenizer_path, input_tokenizer_path, llama_version=2):
|
198 |
-
return tokenizer
|
199 |
-
|
200 |
-
|
201 |
-
+DEFAULT_LLAMA_SPECIAL_TOKENS = {
|
202 |
-
+ "3": [
|
203 |
-
+ "<|begin_of_text|>",
|
204 |
-
+ "<|end_of_text|>",
|
205 |
-
+ "<|reserved_special_token_0|>",
|
206 |
-
+ "<|reserved_special_token_1|>",
|
207 |
-
+ "<|reserved_special_token_2|>",
|
208 |
-
+ "<|reserved_special_token_3|>",
|
209 |
-
+ "<|start_header_id|>",
|
210 |
-
+ "<|end_header_id|>",
|
211 |
-
+ "<|reserved_special_token_4|>",
|
212 |
-
+ "<|eot_id|>", # end of turn
|
213 |
-
+ ]
|
214 |
-
+ + [f"<|reserved_special_token_{i}|>" for i in range(5, 256 - 5)],
|
215 |
-
+ "3.1": [
|
216 |
-
+ "<|begin_of_text|>",
|
217 |
-
+ "<|end_of_text|>",
|
218 |
-
+ "<|reserved_special_token_0|>",
|
219 |
-
+ "<|reserved_special_token_1|>",
|
220 |
-
+ "<|finetune_right_pad_id|>",
|
221 |
-
+ "<|reserved_special_token_2|>",
|
222 |
-
+ "<|start_header_id|>",
|
223 |
-
+ "<|end_header_id|>",
|
224 |
-
+ "<|eom_id|>", # end of message
|
225 |
-
+ "<|eot_id|>", # end of turn
|
226 |
-
+ "<|python_tag|>",
|
227 |
-
+ ]
|
228 |
-
+ + [f"<|reserved_special_token_{i}|>" for i in range(3, 256 - 8)],
|
229 |
-
+}
|
230 |
-
+
|
231 |
-
+
|
232 |
-
def main():
|
233 |
-
parser = argparse.ArgumentParser()
|
234 |
-
parser.add_argument(
|
235 |
-
@@ -383,9 +424,9 @@ def main():
|
236 |
-
# Different Llama versions used different default values for max_position_embeddings, hence the need to be able to specify which version is being used.
|
237 |
-
parser.add_argument(
|
238 |
-
"--llama_version",
|
239 |
-
- choices=[1, 2, 3],
|
240 |
-
- default=1,
|
241 |
-
- type=int,
|
242 |
-
+ choices=["1", "2", "3", "3.1"],
|
243 |
-
+ default="1",
|
244 |
-
+ type=str,
|
245 |
-
help="Version of the Llama model to convert. Currently supports Llama1 and Llama2. Controls the context size",
|
246 |
-
)
|
247 |
-
parser.add_argument(
|
248 |
-
@@ -394,11 +435,34 @@ def main():
|
249 |
-
type=int,
|
250 |
-
help="The number of individual shards used for the model. Does not have to be the same as the number of consolidated_xx.pth",
|
251 |
-
)
|
252 |
-
+ parser.add_argument(
|
253 |
-
+ "--special_tokens",
|
254 |
-
+ default=None,
|
255 |
-
+ type=List[str],
|
256 |
-
+ help="The list of special tokens that should be added to the model.",
|
257 |
-
+ )
|
258 |
-
+ parser.add_argument(
|
259 |
-
+ "--instruct",
|
260 |
-
+ default=False,
|
261 |
-
+ type=bool,
|
262 |
-
+ help="Whether the model is an instruct model or not. Will affect special tokens for llama 3.1.",
|
263 |
-
+ )
|
264 |
-
args = parser.parse_args()
|
265 |
-
if args.model_size is None and args.num_shards is None:
|
266 |
-
raise ValueError("You have to set at least `num_shards` if you are not giving the `model_size`")
|
267 |
-
+ if args.special_tokens is None:
|
268 |
-
+ args.special_tokens = DEFAULT_LLAMA_SPECIAL_TOKENS[str(args.llama_version)]
|
269 |
-
+
|
270 |
-
spm_path = os.path.join(args.input_dir, "tokenizer.model")
|
271 |
-
- vocab_size = len(write_tokenizer(args.output_dir, spm_path, llama_version=args.llama_version))
|
272 |
-
+ vocab_size = len(
|
273 |
-
+ write_tokenizer(
|
274 |
-
+ args.output_dir,
|
275 |
-
+ spm_path,
|
276 |
-
+ llama_version=args.llama_version,
|
277 |
-
+ special_tokens=args.special_tokens,
|
278 |
-
+ instruct=args.instruct
|
279 |
-
+ )
|
280 |
-
+ )
|
281 |
-
if args.model_size != "tokenizer_only":
|
282 |
-
write_model(
|
283 |
-
model_path=args.output_dir,
|
284 |
-
@@ -408,6 +472,7 @@ def main():
|
285 |
-
llama_version=args.llama_version,
|
286 |
-
vocab_size=vocab_size,
|
287 |
-
num_shards=args.num_shards,
|
288 |
-
+ instruct=args.instruct
|
289 |
-
)
|
290 |
-
|
291 |
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