sammysun0711 commited on
Commit
f667769
1 Parent(s): 2e8fc91

Upload convert_aquila_weights_to_hf.py (#3)

Browse files

- Upload convert_aquila_weights_to_hf.py (d40284a7e38961b9831aec08021296ff906333b5)

Files changed (1) hide show
  1. convert_aquila_weights_to_hf.py +301 -0
convert_aquila_weights_to_hf.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 EleutherAI and The HuggingFace Inc. team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import argparse
15
+ import gc
16
+ import json
17
+ import math
18
+ import os
19
+ import shutil
20
+ import warnings
21
+
22
+ import torch
23
+
24
+ from transformers import LlamaConfig, LlamaForCausalLM, LlamaTokenizer
25
+
26
+
27
+ try:
28
+ from transformers import LlamaTokenizerFast
29
+ except ImportError as e:
30
+ warnings.warn(e)
31
+ warnings.warn(
32
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
33
+ )
34
+ LlamaTokenizerFast = None
35
+
36
+ """
37
+ Sample usage:
38
+
39
+ ```
40
+ python src/transformers/models/llama/convert_llama_weights_to_hf.py \
41
+ --input_dir /path/to/downloaded/llama/weights --model_size 7B --output_dir /output/path
42
+ ```
43
+
44
+ Thereafter, models can be loaded via:
45
+
46
+ ```py
47
+ from transformers import LlamaForCausalLM, LlamaTokenizer
48
+
49
+ model = LlamaForCausalLM.from_pretrained("/output/path")
50
+ tokenizer = LlamaTokenizer.from_pretrained("/output/path")
51
+ ```
52
+
53
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
54
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
55
+ """
56
+
57
+ INTERMEDIATE_SIZE_MAP = {
58
+ "7B": 11008,
59
+ "13B": 13824,
60
+ "30B": 17920,
61
+ "65B": 22016,
62
+ }
63
+ NUM_SHARDS = {
64
+ "7B": 1,
65
+ "13B": 2,
66
+ "30B": 4,
67
+ "65B": 8,
68
+ }
69
+
70
+
71
+ def compute_intermediate_size(n):
72
+ return int(math.ceil(n * 8 / 3) + 255) // 256 * 256
73
+
74
+
75
+ def read_json(path):
76
+ with open(path, "r") as f:
77
+ return json.load(f)
78
+
79
+
80
+ def write_json(text, path):
81
+ with open(path, "w") as f:
82
+ json.dump(text, f)
83
+
84
+
85
+ def write_model(model_path, input_base_path, model_size):
86
+ os.makedirs(model_path, exist_ok=True)
87
+ tmp_model_path = os.path.join(model_path, "tmp")
88
+ os.makedirs(tmp_model_path, exist_ok=True)
89
+
90
+
91
+ #params = read_json(os.path.join(input_base_path, "params.json"))
92
+ params = read_json(os.path.join(input_base_path, "config.json"))
93
+ print("params: ", params)
94
+
95
+ num_shards = NUM_SHARDS[model_size]
96
+ n_layers = params["n_layers"]
97
+ n_heads = params["n_heads"]
98
+ n_heads_per_shard = n_heads // num_shards
99
+ dim = params["dim"]
100
+ dims_per_head = dim // n_heads
101
+ base = 10000.0
102
+ inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
103
+
104
+ """
105
+ params = {}
106
+ num_shards = 1
107
+ n_layers = 32
108
+ n_heads = 32
109
+ n_heads_per_shard = n_heads // num_shards
110
+ dim = 4096
111
+ dims_per_head = dim // n_heads
112
+ base = 10000.0
113
+ inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
114
+
115
+ params["n_layers"] = n_layers
116
+ params["n_heads"] = n_heads
117
+ params["dim"] = dim
118
+ params["norm_eps"] = 1e-05
119
+ """
120
+
121
+ # permute for sliced rotary
122
+ def permute(w):
123
+ return w.view(n_heads, dim // n_heads // 2, 2, dim).transpose(1, 2).reshape(dim, dim)
124
+
125
+ print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
126
+ # Load weights
127
+ if model_size == "7B":
128
+ # Not sharded
129
+ # (The sharded implementation would also work, but this is simpler.)
130
+ #loaded = torch.load(os.path.join(input_base_path, "consolidated.00.pth"), map_location="cpu")
131
+ loaded = torch.load(os.path.join(input_base_path, "pytorch_model.bin"), map_location="cpu")
132
+ else:
133
+ # Sharded
134
+ loaded = [
135
+ torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
136
+ for i in range(num_shards)
137
+ ]
138
+ param_count = 0
139
+ index_dict = {"weight_map": {}}
140
+ for layer_i in range(n_layers):
141
+ filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
142
+ if model_size == "7B":
143
+ # Unsharded
144
+ state_dict = {
145
+ f"model.layers.{layer_i}.self_attn.q_proj.weight": permute(
146
+ loaded[f"layers.{layer_i}.attention.wq.weight"]
147
+ ),
148
+ f"model.layers.{layer_i}.self_attn.k_proj.weight": permute(
149
+ loaded[f"layers.{layer_i}.attention.wk.weight"]
150
+ ),
151
+ f"model.layers.{layer_i}.self_attn.v_proj.weight": loaded[f"layers.{layer_i}.attention.wv.weight"],
152
+ f"model.layers.{layer_i}.self_attn.o_proj.weight": loaded[f"layers.{layer_i}.attention.wo.weight"],
153
+ f"model.layers.{layer_i}.mlp.gate_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w1.weight"],
154
+ f"model.layers.{layer_i}.mlp.down_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w2.weight"],
155
+ f"model.layers.{layer_i}.mlp.up_proj.weight": loaded[f"layers.{layer_i}.feed_forward.w3.weight"],
156
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[f"layers.{layer_i}.attention_norm.weight"],
157
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[f"layers.{layer_i}.ffn_norm.weight"],
158
+ }
159
+ else:
160
+ # Sharded
161
+ # Note that in the 13B checkpoint, not cloning the two following weights will result in the checkpoint
162
+ # becoming 37GB instead of 26GB for some reason.
163
+ state_dict = {
164
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
165
+ f"layers.{layer_i}.attention_norm.weight"
166
+ ].clone(),
167
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
168
+ f"layers.{layer_i}.ffn_norm.weight"
169
+ ].clone(),
170
+ }
171
+ state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
172
+ torch.cat(
173
+ [
174
+ loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
175
+ for i in range(num_shards)
176
+ ],
177
+ dim=0,
178
+ ).reshape(dim, dim)
179
+ )
180
+ state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
181
+ torch.cat(
182
+ [
183
+ loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(n_heads_per_shard, dims_per_head, dim)
184
+ for i in range(num_shards)
185
+ ],
186
+ dim=0,
187
+ ).reshape(dim, dim)
188
+ )
189
+ state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
190
+ [
191
+ loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(n_heads_per_shard, dims_per_head, dim)
192
+ for i in range(num_shards)
193
+ ],
194
+ dim=0,
195
+ ).reshape(dim, dim)
196
+
197
+ state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
198
+ [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
199
+ )
200
+ state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
201
+ [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
202
+ )
203
+ state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
204
+ [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
205
+ )
206
+ state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
207
+ [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
208
+ )
209
+
210
+ state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
211
+ for k, v in state_dict.items():
212
+ index_dict["weight_map"][k] = filename
213
+ param_count += v.numel()
214
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
215
+
216
+ filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
217
+ if model_size == "7B":
218
+ # Unsharded
219
+ state_dict = {
220
+ "model.embed_tokens.weight": loaded["tok_embeddings.weight"],
221
+ "model.norm.weight": loaded["norm.weight"],
222
+ "lm_head.weight": loaded["output.weight"],
223
+ }
224
+ else:
225
+ state_dict = {
226
+ "model.norm.weight": loaded[0]["norm.weight"],
227
+ "model.embed_tokens.weight": torch.cat(
228
+ [loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1
229
+ ),
230
+ "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
231
+ }
232
+
233
+ for k, v in state_dict.items():
234
+ index_dict["weight_map"][k] = filename
235
+ param_count += v.numel()
236
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
237
+
238
+ # Write configs
239
+ index_dict["metadata"] = {"total_size": param_count * 2}
240
+ write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
241
+
242
+ config = LlamaConfig(
243
+ hidden_size=dim,
244
+ intermediate_size=compute_intermediate_size(dim),
245
+ num_attention_heads=params["n_heads"],
246
+ num_hidden_layers=params["n_layers"],
247
+ rms_norm_eps=params["norm_eps"],
248
+ )
249
+ config.save_pretrained(tmp_model_path)
250
+
251
+ # Make space so we can load the model properly now.
252
+ del state_dict
253
+ del loaded
254
+ gc.collect()
255
+
256
+ print("Loading the checkpoint in a Llama model.")
257
+ model = LlamaForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
258
+ # Avoid saving this as part of the config.
259
+ del model.config._name_or_path
260
+
261
+ print("Saving in the Transformers format.")
262
+ model.save_pretrained(model_path)
263
+ shutil.rmtree(tmp_model_path)
264
+
265
+
266
+ def write_tokenizer(tokenizer_path, input_tokenizer_path):
267
+ # Initialize the tokenizer based on the `spm` model
268
+ tokenizer_class = LlamaTokenizer if LlamaTokenizerFast is None else LlamaTokenizerFast
269
+ print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
270
+ tokenizer = tokenizer_class(input_tokenizer_path)
271
+ tokenizer.save_pretrained(tokenizer_path)
272
+
273
+
274
+ def main():
275
+ parser = argparse.ArgumentParser()
276
+ parser.add_argument(
277
+ "--input_dir",
278
+ help="Location of LLaMA weights, which contains tokenizer.model and model folders",
279
+ )
280
+ parser.add_argument(
281
+ "--model_size",
282
+ choices=["7B", "13B", "30B", "65B", "tokenizer_only"],
283
+ )
284
+ parser.add_argument(
285
+ "--output_dir",
286
+ help="Location to write HF model and tokenizer",
287
+ )
288
+ args = parser.parse_args()
289
+ if args.model_size != "tokenizer_only":
290
+ write_model(
291
+ model_path=args.output_dir,
292
+ #input_base_path=os.path.join(args.input_dir, args.model_size),
293
+ input_base_path=args.input_dir,
294
+ model_size=args.model_size,
295
+ )
296
+ #spm_path = os.path.join(args.input_dir, "tokenizer.model")
297
+ #write_tokenizer(args.output_dir, spm_path)
298
+
299
+
300
+ if __name__ == "__main__":
301
+ main()