-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathconvert_hf_checkpoint.py
More file actions
327 lines (288 loc) · 13.2 KB
/
convert_hf_checkpoint.py
File metadata and controls
327 lines (288 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys
sys.path.append("..")
import json
import re
import shutil
import sys
from pathlib import Path
from typing import Optional
from safetensors.torch import load_file as load_safetensors_file
import torch
# support running without installing as a package
wd = Path(__file__).parent.parent.resolve()
sys.path.append(str(wd))
from MagicDec.Engine.SnapKV.model import ModelArgs
@torch.inference_mode()
def convert_hf_checkpoint(
*,
checkpoint_dir: Path = Path("checkpoints/meta-Transformer/Transformer-2-7b-chat-hf"),
model_name: Optional[str] = None,
) -> None:
if model_name is None:
model_name = checkpoint_dir.name
config = ModelArgs.from_name(model_name)
print(f"Model config {config.__dict__}")
# Load the json file containing weight mapping
model_map_json_safetensors = checkpoint_dir / 'model.safetensors.index.json'
model_map_json_pytorch = checkpoint_dir / "pytorch_model.bin.index.json"
model_safetensors = checkpoint_dir / "model.safetensors"
model_pytorch = checkpoint_dir / "pytorch_model.bin"
model_map_json = None
model_file = None
try:
assert model_map_json_safetensors.is_file()
model_map_json = model_map_json_safetensors
print(f"Found safetensors index at {model_map_json_safetensors}")
except AssertionError:
print(f"{model_map_json_safetensors} not found")
if model_map_json is None:
try:
assert model_map_json_pytorch.is_file()
model_map_json = model_map_json_pytorch
print(f"Found pytorch index at {model_map_json_pytorch}")
except AssertionError:
print(f"{model_map_json_pytorch} not found")
if model_map_json is None:
try:
assert model_safetensors.is_file()
model_file = model_safetensors
print(f"Found safetensors weights at {model_safetensors}")
except AssertionError:
print(f"{model_safetensors} not found")
if model_map_json is None and model_file is None:
try:
assert model_safetensors.is_file()
model_file = model_pytorch
print(f"Found pytorch weights at {model_pytorch}")
except AssertionError:
print(f"{model_pytorch} not found, can't find any weights or index.")
exit()
if model_map_json != None:
with open(model_map_json) as json_map:
bin_index = json.load(json_map)
weight_map = {
"model.embed_tokens.weight": "tok_embeddings.weight",
"model.layers.{}.self_attn.q_proj.weight": "layers.{}.attention.wq.weight",
"model.layers.{}.self_attn.k_proj.weight": "layers.{}.attention.wk.weight",
"model.layers.{}.self_attn.v_proj.weight": "layers.{}.attention.wv.weight",
"model.layers.{}.self_attn.o_proj.weight": "layers.{}.attention.wo.weight",
'model.layers.{}.self_attn.rotary_emb.inv_freq': None,
'model.layers.{}.mlp.gate_proj.weight': 'layers.{}.feed_forward.w1.weight',
"model.layers.{}.mlp.up_proj.weight": "layers.{}.feed_forward.w3.weight",
"model.layers.{}.mlp.down_proj.weight": "layers.{}.feed_forward.w2.weight",
"model.layers.{}.input_layernorm.weight": "layers.{}.attention_norm.weight",
"model.layers.{}.post_attention_layernorm.weight": "layers.{}.ffn_norm.weight",
"model.norm.weight": "norm.weight",
"lm_head.weight": "output.weight",
}
if "qwen" in model_name.lower():
weight_map.update({
"model.layers.{}.self_attn.q_proj.bias": "layers.{}.attention.wq.bias",
"model.layers.{}.self_attn.k_proj.bias": "layers.{}.attention.wk.bias",
"model.layers.{}.self_attn.v_proj.bias": "layers.{}.attention.wv.bias",
})
if model_map_json != None:
bin_files = {checkpoint_dir / bin for bin in bin_index["weight_map"].values()}
def permute(w, n_head):
if len(w.shape) == 2:
# weight term
dim = config.dim
return (
w.view(n_head, 2, config.head_dim // 2, dim)
.transpose(1, 2)
.reshape(config.head_dim * n_head, dim)
)
else:
# bias term
return w.view(n_head, 2, config.head_dim // 2).transpose(1, 2).reshape(config.head_dim * n_head)
merged_result = {}
if model_map_json != None:
for file in sorted(bin_files):
if "safetensors" in str(file):
state_dict = load_safetensors_file(str(file), device="cpu")
merged_result.update(state_dict)
else:
state_dict = torch.load(str(file), map_location="cpu", mmap=True, weights_only=True)
merged_result.update(state_dict)
else:
# state_dict = state_dict = torch.load(str(bin_file), map_location="cpu", mmap=True, weights_only=True)
if "safetensors" in str(model_file):
state_dict = load_safetensors_file(str(model_file), device="cpu")
merged_result.update(state_dict)
else:
state_dict = state_dict = torch.load(str(model_file), map_location="cpu", mmap=True, weights_only=True)
merged_result.update(state_dict)
final_result = {}
for key, value in merged_result.items():
if "layers" in key:
abstract_key = re.sub(r'(\d+)', '{}', key)
layer_num = re.search(r'\d+', key).group(0)
new_key = weight_map[abstract_key]
if new_key is None:
continue
new_key = new_key.format(layer_num)
else:
new_key = weight_map[key]
final_result[new_key] = value
if 'output.weight' not in final_result.keys():
final_result['output.weight'] = merged_result["model.embed_tokens.weight"]
print("Use input embedding as the output lm_head")
for key in tuple(final_result.keys()):
if "wq" in key:
q = final_result[key]
k = final_result[key.replace("wq", "wk")]
v = final_result[key.replace("wq", "wv")]
q = permute(q, config.n_head)
k = permute(k, config.n_local_heads)
final_result[key.replace("wq", "wqkv")] = torch.cat([q, k, v])
del final_result[key]
del final_result[key.replace("wq", "wk")]
del final_result[key.replace("wq", "wv")]
print(f"Saving checkpoint to {checkpoint_dir / 'model.pth'}")
torch.save(final_result, checkpoint_dir / "model.pth")
if 'llama-3' in model_name.lower():
original_dir = checkpoint_dir / "original"
tokenizer_model = original_dir / "tokenizer.model"
tokenizer_model_tiktoken = checkpoint_dir / "tokenizer.model"
print(f"Copying {tokenizer_model} to {tokenizer_model_tiktoken}")
shutil.copy(tokenizer_model, tokenizer_model_tiktoken)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Convert HuggingFace checkpoint.')
parser.add_argument('--checkpoint_dir', type=Path, default=Path("/scratch/models/meta-llama/Llama-3.2-1B"))
parser.add_argument('--model_name', type=str, default=None)
args = parser.parse_args()
convert_hf_checkpoint(
checkpoint_dir=args.checkpoint_dir,
model_name=args.model_name,
)
# # Copyright (c) Meta Platforms, Inc. and affiliates.
# # All rights reserved.
# # This source code is licensed under the license found in the
# # LICENSE file in the root directory of this source tree.
# import sys
# sys.path.append("..")
# import json
# import re
# import shutil
# import sys
# import copy
# from pathlib import Path
# from typing import Optional
# from safetensors.torch import load_file as load_safetensors_file
# import torch
# # support running without installing as a package
# wd = Path(__file__).parent.parent.resolve()
# sys.path.append(str(wd))
# from MagicDec.Engine.model import ModelArgs
# @torch.inference_mode()
# def convert_hf_checkpoint(
# *,
# checkpoint_dir: Path = Path("checkpoints/meta-Transformer/Transformer-2-7b-chat-hf"),
# model_name: Optional[str] = None,
# ) -> None:
# if model_name is None:
# model_name = checkpoint_dir.name
# config = ModelArgs.from_name(model_name)
# print(f"Model config {config.__dict__}")
# # Load the json file containing weight mapping
# model_map_json_safetensors = checkpoint_dir / 'model.safetensors.index.json'
# model_map_json_pytorch = checkpoint_dir / "pytorch_model.bin.index.json"
# model_map_json = None
# try:
# assert model_map_json_safetensors.is_file()
# model_map_json = model_map_json_safetensors
# print(f"Found safetensors index at {model_map_json_safetensors}")
# except AssertionError:
# print(f"{model_map_json_safetensors} not found")
# if model_map_json is None:
# try:
# assert model_map_json_pytorch.is_file()
# model_map_json = model_map_json_pytorch
# print(f"Found pytorch index at {model_map_json_pytorch}")
# except AssertionError:
# print(f"{model_map_json_pytorch} not found")
# if model_map_json is None: raise Exception("No model map found!")
# with open(model_map_json) as json_map:
# bin_index = json.load(json_map)
# weight_map = {
# "model.embed_tokens.weight": "tok_embeddings.weight",
# "model.layers.{}.self_attn.q_proj.weight": "layers.{}.attention.wq.weight",
# "model.layers.{}.self_attn.k_proj.weight": "layers.{}.attention.wk.weight",
# "model.layers.{}.self_attn.v_proj.weight": "layers.{}.attention.wv.weight",
# "model.layers.{}.self_attn.o_proj.weight": "layers.{}.attention.wo.weight",
# 'model.layers.{}.self_attn.rotary_emb.inv_freq': None,
# 'model.layers.{}.mlp.gate_proj.weight': 'layers.{}.feed_forward.w1.weight',
# "model.layers.{}.mlp.up_proj.weight": "layers.{}.feed_forward.w3.weight",
# "model.layers.{}.mlp.down_proj.weight": "layers.{}.feed_forward.w2.weight",
# "model.layers.{}.input_layernorm.weight": "layers.{}.attention_norm.weight",
# "model.layers.{}.post_attention_layernorm.weight": "layers.{}.ffn_norm.weight",
# "model.norm.weight": "norm.weight",
# "lm_head.weight": "output.weight"
# }
# bin_files = {checkpoint_dir / bin for bin in bin_index["weight_map"].values()}
# def permute(w, n_head):
# dim = config.dim
# return (
# w.view(n_head, 2, config.head_dim // 2, dim)
# .transpose(1, 2)
# .reshape(config.head_dim * n_head, dim)
# )
# merged_result = {}
# for file in sorted(bin_files):
# if "safetensors" in str(file):
# state_dict = load_safetensors_file(str(file), device="cpu")
# merged_result.update(state_dict)
# else:
# state_dict = torch.load(str(file), map_location="cpu", mmap=True, weights_only=True)
# merged_result.update(state_dict)
# if "lm_head.weight" not in merged_result.keys():
# merged_result["lm_head.weight"] = copy.deepcopy(merged_result["model.embed_tokens.weight"])
# final_result = {}
# for key, value in merged_result.items():
# if "layers" in key:
# abstract_key = re.sub(r'(\d+)', '{}', key)
# layer_num = re.search(r'\d+', key).group(0)
# new_key = weight_map[abstract_key]
# if new_key is None:
# continue
# new_key = new_key.format(layer_num)
# else:
# new_key = weight_map[key]
# final_result[new_key] = value
# for key in tuple(final_result.keys()):
# if "wq" in key:
# q = final_result[key]
# k = final_result[key.replace("wq", "wk")]
# v = final_result[key.replace("wq", "wv")]
# q = permute(q, config.n_head)
# k = permute(k, config.n_local_heads)
# final_result[key.replace("wq", "wqkv")] = torch.cat([q, k, v])
# del final_result[key]
# del final_result[key.replace("wq", "wk")]
# del final_result[key.replace("wq", "wv")]
# print(f"Saving checkpoint to {checkpoint_dir / 'model.pth'}")
# torch.save(final_result, checkpoint_dir / "model.pth")
# if 'llama-3-' in model_name.lower() or 'llama-3.' in model_name.lower():
# if 'llama-3.1-405b' in model_name.lower():
# original_dir = checkpoint_dir / "original" / "mp16"
# else:
# original_dir = checkpoint_dir / "original"
# tokenizer_model = original_dir / "tokenizer.model"
# tokenizer_model_tiktoken = checkpoint_dir / "tokenizer.model"
# print(f"Copying {tokenizer_model} to {tokenizer_model_tiktoken}")
# shutil.copy(tokenizer_model, tokenizer_model_tiktoken)
# if __name__ == '__main__':
# import argparse
# parser = argparse.ArgumentParser(description='Convert HuggingFace checkpoint.')
# parser.add_argument('--checkpoint_dir', type=Path, default=Path("checkpoints/meta-llama/llama-2-7b-chat-hf"))
# parser.add_argument('--model_name', type=str, default=None)
# args = parser.parse_args()
# convert_hf_checkpoint(
# checkpoint_dir=args.checkpoint_dir,
# model_name=args.model_name,
# )