legraphista commited on
Commit
5e809e1
1 Parent(s): e60f166

Upload convert_mistral_weights_to_hf-22B.py

Browse files
Files changed (1) hide show
  1. convert_mistral_weights_to_hf-22B.py +299 -0
convert_mistral_weights_to_hf-22B.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Mistral AI 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 os
18
+ import shutil
19
+ import warnings
20
+
21
+ import torch
22
+ from safetensors.torch import load_file as safe_load_file
23
+
24
+ from transformers import (
25
+ LlamaTokenizer,
26
+ MistralConfig,
27
+ MistralForCausalLM,
28
+ AddedToken,
29
+ )
30
+
31
+
32
+ try:
33
+ from transformers import LlamaTokenizerFast
34
+
35
+ tokenizer_class = LlamaTokenizerFast
36
+ except ImportError as e:
37
+ warnings.warn(e)
38
+ warnings.warn(
39
+ "The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
40
+ )
41
+ tokenizer_class = LlamaTokenizer
42
+
43
+ """
44
+ Sample usage:
45
+
46
+ ```
47
+ python src/transformers/models/mistral/convert_mistral_weights_to_hf.py \
48
+ --input_dir /path/to/downloaded/mistral/weights --model_size 22B --output_dir /output/path
49
+ ```
50
+
51
+ Thereafter, models can be loaded via:
52
+
53
+ ```py
54
+ from transformers import MistralForCausalLM, LlamaTokenizer
55
+
56
+ model = MistralForCausalLM.from_pretrained("/output/path")
57
+ tokenizer = LlamaTokenizer.from_pretrained("/output/path")
58
+ ```
59
+
60
+ Important note: you need to be able to host the whole model in RAM to execute this script (even if the biggest versions
61
+ come in several checkpoints they each contain a part of each weight of the model, so we need to load them all in RAM).
62
+ """
63
+
64
+ NUM_SHARDS = {"22B": 1}
65
+
66
+
67
+ def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
68
+ return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
69
+
70
+
71
+ def read_json(path):
72
+ with open(path, "r") as f:
73
+ return json.load(f)
74
+
75
+
76
+ def write_json(text, path):
77
+ with open(path, "w") as f:
78
+ json.dump(text, f)
79
+
80
+
81
+ def write_model(model_path, input_base_path, model_size, tokenizer_path=None, safe_serialization=True, is_v3=False):
82
+ # for backward compatibility, before you needed the repo to be called `my_repo/model_size`
83
+ if not os.path.isfile(os.path.join(input_base_path, "params.json")):
84
+ input_base_path = os.path.join(input_base_path, model_size)
85
+
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
+ params = read_json(os.path.join(input_base_path, "params.json"))
91
+ num_shards = NUM_SHARDS[model_size]
92
+
93
+ sliding_window = params.get("sliding_window", None)
94
+
95
+ # For some reason this is a string in the params.json
96
+ if sliding_window is not None:
97
+ sliding_window = int(sliding_window)
98
+
99
+ n_layers = params["n_layers"]
100
+ n_heads = params["n_heads"]
101
+ n_heads_per_shard = n_heads // num_shards
102
+ dim = params["dim"]
103
+ dims_per_head = dim // n_heads
104
+ base = params.get("rope_theta", 10000.0)
105
+ inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
106
+ max_position_embeddings = 4096 * 8
107
+
108
+ if tokenizer_path is not None:
109
+ tokenizer = write_tokenizer(model_path, tokenizer_path + ".v3" if is_v3 else "")
110
+ vocab_size = tokenizer.vocab_size if tokenizer_path is not None else 32000
111
+
112
+ if "n_kv_heads" in params:
113
+ num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
114
+ num_local_key_value_heads = num_key_value_heads // num_shards
115
+ key_value_dim = dims_per_head * num_local_key_value_heads
116
+ else: # compatibility with other checkpoints
117
+ num_key_value_heads = n_heads
118
+ num_local_key_value_heads = n_heads_per_shard
119
+ key_value_dim = dim
120
+
121
+ # permute for sliced rotary
122
+ def permute(w, n_heads=n_heads, dim1=dim, dim2=dim):
123
+ return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
124
+
125
+ print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
126
+
127
+ # Load weights - for v3 models the consolidated weights are in a single file format in safetensors
128
+ if is_v3:
129
+ loaded = [safe_load_file(os.path.join(input_base_path, "consolidated.safetensors"))]
130
+ else:
131
+ loaded = [
132
+ torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
133
+ for i in range(num_shards)
134
+ ]
135
+ param_count = 0
136
+ index_dict = {"weight_map": {}}
137
+ for layer_i in range(n_layers):
138
+ filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
139
+
140
+ # Sharded
141
+ # Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
142
+ # the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
143
+ # redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
144
+
145
+ state_dict = {
146
+ f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
147
+ f"layers.{layer_i}.attention_norm.weight"
148
+ ].clone(),
149
+ f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
150
+ f"layers.{layer_i}.ffn_norm.weight"
151
+ ].clone(),
152
+ }
153
+ state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
154
+ torch.cat(
155
+ [
156
+ loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
157
+ for i in range(num_shards)
158
+ ],
159
+ dim=0,
160
+ ).reshape(dim, dim)
161
+ )
162
+ state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
163
+ torch.cat(
164
+ [
165
+ loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
166
+ num_local_key_value_heads, dims_per_head, dim
167
+ )
168
+ for i in range(num_shards)
169
+ ],
170
+ dim=0,
171
+ ).reshape(key_value_dim, dim),
172
+ num_key_value_heads,
173
+ key_value_dim,
174
+ dim,
175
+ )
176
+ state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
177
+ [
178
+ loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(num_local_key_value_heads, dims_per_head, dim)
179
+ for i in range(num_shards)
180
+ ],
181
+ dim=0,
182
+ ).reshape(key_value_dim, dim)
183
+
184
+ state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
185
+ [loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
186
+ )
187
+ state_dict[f"model.layers.{layer_i}.mlp.gate_proj.weight"] = torch.cat(
188
+ [loaded[i][f"layers.{layer_i}.feed_forward.w1.weight"] for i in range(num_shards)], dim=0
189
+ )
190
+ state_dict[f"model.layers.{layer_i}.mlp.down_proj.weight"] = torch.cat(
191
+ [loaded[i][f"layers.{layer_i}.feed_forward.w2.weight"] for i in range(num_shards)], dim=1
192
+ )
193
+ state_dict[f"model.layers.{layer_i}.mlp.up_proj.weight"] = torch.cat(
194
+ [loaded[i][f"layers.{layer_i}.feed_forward.w3.weight"] for i in range(num_shards)], dim=0
195
+ )
196
+
197
+ state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
198
+ for k, v in state_dict.items():
199
+ index_dict["weight_map"][k] = filename
200
+ param_count += v.numel()
201
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
202
+
203
+ filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
204
+ state_dict = {
205
+ "model.norm.weight": loaded[0]["norm.weight"],
206
+ "model.embed_tokens.weight": torch.cat([loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1),
207
+ "lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
208
+ }
209
+
210
+ for k, v in state_dict.items():
211
+ index_dict["weight_map"][k] = filename
212
+ param_count += v.numel()
213
+ torch.save(state_dict, os.path.join(tmp_model_path, filename))
214
+
215
+ # Write configs
216
+ index_dict["metadata"] = {"total_size": param_count * 2}
217
+ write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
218
+ config = MistralConfig(
219
+ hidden_size=dim,
220
+ intermediate_size=params["hidden_dim"],
221
+ num_attention_heads=params["n_heads"],
222
+ num_hidden_layers=params["n_layers"],
223
+ rms_norm_eps=params["norm_eps"],
224
+ num_key_value_heads=num_key_value_heads,
225
+ vocab_size=vocab_size,
226
+ rope_theta=base,
227
+ max_position_embeddings=max_position_embeddings,
228
+ sliding_window=sliding_window,
229
+ )
230
+ config.save_pretrained(tmp_model_path)
231
+
232
+ # Make space so we can load the model properly now.
233
+ del state_dict
234
+ del loaded
235
+ gc.collect()
236
+
237
+ print("Loading the checkpoint in a Mistral model.")
238
+ model = MistralForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.bfloat16, low_cpu_mem_usage=True)
239
+ # Avoid saving this as part of the config.
240
+ del model.config._name_or_path
241
+ model.config.torch_dtype = torch.float16
242
+ print("Saving in the Transformers format.")
243
+
244
+ model.save_pretrained(model_path, safe_serialization=safe_serialization)
245
+ shutil.rmtree(tmp_model_path)
246
+
247
+
248
+ def write_tokenizer(tokenizer_path, input_tokenizer_path):
249
+ # Initialize the tokenizer based on the `spm` model
250
+ print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
251
+ tokenizer = tokenizer_class(input_tokenizer_path)
252
+ tokenizer.add_tokens([
253
+ AddedToken('[INST]', special=True),
254
+ AddedToken('[/INST]', special=True),
255
+ AddedToken('[PREFIX]', special=True),
256
+ AddedToken('[SUFFIX]', special=True),
257
+ AddedToken('[MIDDLE]', special=True),
258
+ AddedToken('[IMG]', special=True),
259
+ ])
260
+ tokenizer.save_pretrained(tokenizer_path)
261
+ return tokenizer
262
+
263
+
264
+ def main():
265
+ parser = argparse.ArgumentParser()
266
+ parser.add_argument(
267
+ "--input_dir",
268
+ help="Location of Mistral weights, which contains tokenizer.model and model folders",
269
+ )
270
+ parser.add_argument(
271
+ "--model_size",
272
+ choices=["22B", "tokenizer_only"],
273
+ help="'f' models correspond to the finetuned versions, and are specific to the Mistral2 official release. For more details on Mistral2, checkout the original repo: https://huggingface.co/meta-mistral",
274
+ )
275
+ parser.add_argument(
276
+ "--output_dir",
277
+ help="Location to write HF model and tokenizer",
278
+ )
279
+ parser.add_argument("--safe_serialization", type=bool, help="Whether or not to save using `safetensors`.")
280
+ parser.add_argument(
281
+ "--is_v3", action="store_true", help="Whether the checkpoints correspond to the 3rd version or not."
282
+ )
283
+ args = parser.parse_args()
284
+ spm_path = os.path.join(args.input_dir, "tokenizer.model")
285
+ if args.model_size != "tokenizer_only":
286
+ write_model(
287
+ model_path=args.output_dir,
288
+ input_base_path=args.input_dir,
289
+ model_size=args.model_size,
290
+ safe_serialization=args.safe_serialization,
291
+ tokenizer_path=spm_path,
292
+ is_v3=args.is_v3,
293
+ )
294
+ else:
295
+ write_tokenizer(args.output_dir, spm_path)
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()