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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 23 |
+
from transformers import (
|
| 24 |
+
LlamaTokenizer
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from .modeling_moe_mistral import MixtralForCausalLM
|
| 28 |
+
from .configuration_moe_mistral import MixtralConfig
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
from transformers import LlamaTokenizerFast
|
| 32 |
+
|
| 33 |
+
tokenizer_class = LlamaTokenizerFast
|
| 34 |
+
except ImportError as e:
|
| 35 |
+
warnings.warn(e)
|
| 36 |
+
warnings.warn(
|
| 37 |
+
"The converted tokenizer will be the `slow` tokenizer. To use the fast, update your `tokenizers` library and re-run the tokenizer conversion"
|
| 38 |
+
)
|
| 39 |
+
tokenizer_class = LlamaTokenizer
|
| 40 |
+
|
| 41 |
+
"""
|
| 42 |
+
Sample usage:
|
| 43 |
+
```
|
| 44 |
+
python src/transformers/models/mistral/convert_mistral_weights_to_hf.py \
|
| 45 |
+
--input_dir /path/to/downloaded/mistral/weights --model_size 7B --output_dir /output/path
|
| 46 |
+
```
|
| 47 |
+
Thereafter, models can be loaded via:
|
| 48 |
+
```py
|
| 49 |
+
from transformers import MistralForCausalLM, LlamaTokenizer
|
| 50 |
+
model = MistralForCausalLM.from_pretrained("/output/path")
|
| 51 |
+
tokenizer = LlamaTokenizer.from_pretrained("/output/path")
|
| 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 |
+
NUM_SHARDS = {"7B": 1}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def compute_intermediate_size(n, ffn_dim_multiplier=1, multiple_of=256):
|
| 61 |
+
return multiple_of * ((int(ffn_dim_multiplier * int(8 * n / 3)) + multiple_of - 1) // multiple_of)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def read_json(path):
|
| 65 |
+
with open(path, "r") as f:
|
| 66 |
+
return json.load(f)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def write_json(text, path):
|
| 70 |
+
with open(path, "w") as f:
|
| 71 |
+
json.dump(text, f)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def write_model(model_path, input_base_path, model_size, tokenizer_path=None, safe_serialization=True):
|
| 75 |
+
# for backward compatibility, before you needed the repo to be called `my_repo/model_size`
|
| 76 |
+
if not os.path.isfile(os.path.join(input_base_path, "params.json")):
|
| 77 |
+
input_base_path = os.path.join(input_base_path, model_size)
|
| 78 |
+
|
| 79 |
+
os.makedirs(model_path, exist_ok=True)
|
| 80 |
+
tmp_model_path = os.path.join(model_path, "tmp")
|
| 81 |
+
os.makedirs(tmp_model_path, exist_ok=True)
|
| 82 |
+
|
| 83 |
+
params = read_json(os.path.join(input_base_path, "params.json"))
|
| 84 |
+
num_shards = NUM_SHARDS[model_size]
|
| 85 |
+
|
| 86 |
+
n_layers = params["n_layers"]
|
| 87 |
+
n_heads = params["n_heads"]
|
| 88 |
+
n_heads_per_shard = n_heads // num_shards
|
| 89 |
+
dim = params["dim"]
|
| 90 |
+
dims_per_head = dim // n_heads
|
| 91 |
+
base = params.get("rope_theta", 100000.0)
|
| 92 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, dims_per_head, 2).float() / dims_per_head))
|
| 93 |
+
max_position_embeddings = 4096 * 8
|
| 94 |
+
num_experts_per_token = params["moe"]["num_experts_per_tok"]
|
| 95 |
+
num_experts = params["moe"]["num_experts"]
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if tokenizer_path is not None:
|
| 99 |
+
tokenizer = tokenizer_class(tokenizer_path)
|
| 100 |
+
tokenizer.save_pretrained(model_path)
|
| 101 |
+
vocab_size = tokenizer.vocab_size if tokenizer_path is not None else 32000
|
| 102 |
+
|
| 103 |
+
if "n_kv_heads" in params:
|
| 104 |
+
num_key_value_heads = params["n_kv_heads"] # for GQA / MQA
|
| 105 |
+
num_local_key_value_heads = num_key_value_heads // num_shards
|
| 106 |
+
key_value_dim = dims_per_head * num_local_key_value_heads
|
| 107 |
+
else: # compatibility with other checkpoints
|
| 108 |
+
num_key_value_heads = n_heads
|
| 109 |
+
num_local_key_value_heads = n_heads_per_shard
|
| 110 |
+
key_value_dim = dim
|
| 111 |
+
|
| 112 |
+
# permute for sliced rotary
|
| 113 |
+
def permute(w, n_heads=n_heads, dim1=dim, dim2=dim):
|
| 114 |
+
return w.view(n_heads, dim1 // n_heads // 2, 2, dim2).transpose(1, 2).reshape(dim1, dim2)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
print(f"Fetching all parameters from the checkpoint at {input_base_path}.")
|
| 118 |
+
# Load weights
|
| 119 |
+
loaded = [
|
| 120 |
+
torch.load(os.path.join(input_base_path, f"consolidated.{i:02d}.pth"), map_location="cpu")
|
| 121 |
+
for i in range(num_shards)
|
| 122 |
+
]
|
| 123 |
+
param_count = 0
|
| 124 |
+
index_dict = {"weight_map": {}}
|
| 125 |
+
for layer_i in range(n_layers):
|
| 126 |
+
filename = f"pytorch_model-{layer_i + 1}-of-{n_layers + 1}.bin"
|
| 127 |
+
|
| 128 |
+
# Sharded
|
| 129 |
+
# Note that attention.w{q,k,v,o}, feed_fordward.w[1,2,3], attention_norm.weight and ffn_norm.weight share
|
| 130 |
+
# the same storage object, saving attention_norm and ffn_norm will save other weights too, which is
|
| 131 |
+
# redundant as other weights will be stitched from multiple shards. To avoid that, they are cloned.
|
| 132 |
+
|
| 133 |
+
state_dict = {
|
| 134 |
+
f"model.layers.{layer_i}.input_layernorm.weight": loaded[0][
|
| 135 |
+
f"layers.{layer_i}.attention_norm.weight"
|
| 136 |
+
].clone(),
|
| 137 |
+
f"model.layers.{layer_i}.post_attention_layernorm.weight": loaded[0][
|
| 138 |
+
f"layers.{layer_i}.ffn_norm.weight"
|
| 139 |
+
].clone(),
|
| 140 |
+
}
|
| 141 |
+
state_dict[f"model.layers.{layer_i}.self_attn.q_proj.weight"] = permute(
|
| 142 |
+
torch.cat(
|
| 143 |
+
[
|
| 144 |
+
loaded[i][f"layers.{layer_i}.attention.wq.weight"].view(n_heads_per_shard, dims_per_head, dim)
|
| 145 |
+
for i in range(num_shards)
|
| 146 |
+
],
|
| 147 |
+
dim=0,
|
| 148 |
+
).reshape(dim, dim)
|
| 149 |
+
)
|
| 150 |
+
state_dict[f"model.layers.{layer_i}.self_attn.k_proj.weight"] = permute(
|
| 151 |
+
torch.cat(
|
| 152 |
+
[
|
| 153 |
+
loaded[i][f"layers.{layer_i}.attention.wk.weight"].view(
|
| 154 |
+
num_local_key_value_heads, dims_per_head, dim
|
| 155 |
+
)
|
| 156 |
+
for i in range(num_shards)
|
| 157 |
+
],
|
| 158 |
+
dim=0,
|
| 159 |
+
).reshape(key_value_dim, dim),
|
| 160 |
+
num_key_value_heads,
|
| 161 |
+
key_value_dim,
|
| 162 |
+
dim,
|
| 163 |
+
)
|
| 164 |
+
state_dict[f"model.layers.{layer_i}.self_attn.v_proj.weight"] = torch.cat(
|
| 165 |
+
[
|
| 166 |
+
loaded[i][f"layers.{layer_i}.attention.wv.weight"].view(num_local_key_value_heads, dims_per_head, dim)
|
| 167 |
+
for i in range(num_shards)
|
| 168 |
+
],
|
| 169 |
+
dim=0,
|
| 170 |
+
).reshape(key_value_dim, dim)
|
| 171 |
+
|
| 172 |
+
state_dict[f"model.layers.{layer_i}.self_attn.o_proj.weight"] = torch.cat(
|
| 173 |
+
[loaded[i][f"layers.{layer_i}.attention.wo.weight"] for i in range(num_shards)], dim=1
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
for expert in range(num_experts):
|
| 177 |
+
state_dict[f"model.layers.{layer_i}.mlp.experts.{expert}.w1.weight"] = loaded[0][f"layers.{layer_i}.feed_forward.experts.{expert}.w1.weight"]
|
| 178 |
+
state_dict[f"model.layers.{layer_i}.mlp.experts.{expert}.w2.weight"] = loaded[0][f"layers.{layer_i}.feed_forward.experts.{expert}.w2.weight"]
|
| 179 |
+
state_dict[f"model.layers.{layer_i}.mlp.experts.{expert}.w3.weight"] = loaded[0][f"layers.{layer_i}.feed_forward.experts.{expert}.w3.weight"]
|
| 180 |
+
|
| 181 |
+
state_dict[f"model.layers.{layer_i}.mlp.gate.weight"] = loaded[0][f"layers.{layer_i}.feed_forward.gate.weight"]
|
| 182 |
+
|
| 183 |
+
state_dict[f"model.layers.{layer_i}.self_attn.rotary_emb.inv_freq"] = inv_freq
|
| 184 |
+
for k, v in state_dict.items():
|
| 185 |
+
index_dict["weight_map"][k] = filename
|
| 186 |
+
param_count += v.numel()
|
| 187 |
+
torch.save(state_dict, os.path.join(tmp_model_path, filename))
|
| 188 |
+
|
| 189 |
+
filename = f"pytorch_model-{n_layers + 1}-of-{n_layers + 1}.bin"
|
| 190 |
+
state_dict = {
|
| 191 |
+
"model.norm.weight": loaded[0]["norm.weight"],
|
| 192 |
+
"model.embed_tokens.weight": torch.cat([loaded[i]["tok_embeddings.weight"] for i in range(num_shards)], dim=1),
|
| 193 |
+
"lm_head.weight": torch.cat([loaded[i]["output.weight"] for i in range(num_shards)], dim=0),
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
for k, v in state_dict.items():
|
| 197 |
+
index_dict["weight_map"][k] = filename
|
| 198 |
+
param_count += v.numel()
|
| 199 |
+
print(param_count)
|
| 200 |
+
torch.save(state_dict, os.path.join(tmp_model_path, filename))
|
| 201 |
+
|
| 202 |
+
index_dict["metadata"] = {"total_size": param_count * 2}
|
| 203 |
+
write_json(index_dict, os.path.join(tmp_model_path, "pytorch_model.bin.index.json"))
|
| 204 |
+
config = MixtralConfig(
|
| 205 |
+
hidden_size=dim,
|
| 206 |
+
intermediate_size=params["hidden_dim"],
|
| 207 |
+
num_attention_heads=params["n_heads"],
|
| 208 |
+
num_hidden_layers=params["n_layers"],
|
| 209 |
+
rms_norm_eps=params["norm_eps"],
|
| 210 |
+
num_key_value_heads=num_key_value_heads,
|
| 211 |
+
vocab_size=vocab_size,
|
| 212 |
+
rope_theta=base,
|
| 213 |
+
max_position_embeddings=max_position_embeddings,
|
| 214 |
+
num_experts=num_experts,
|
| 215 |
+
num_experts_per_token=num_experts_per_token
|
| 216 |
+
)
|
| 217 |
+
config.save_pretrained(tmp_model_path)
|
| 218 |
+
|
| 219 |
+
del state_dict
|
| 220 |
+
del loaded
|
| 221 |
+
gc.collect()
|
| 222 |
+
|
| 223 |
+
print("Loading the checkpoint in a Mistral model.")
|
| 224 |
+
model = MixtralForCausalLM.from_pretrained(tmp_model_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
|
| 225 |
+
# Avoid saving this as part of the config.
|
| 226 |
+
del model.config._name_or_path
|
| 227 |
+
model.config.torch_dtype = torch.float16
|
| 228 |
+
print("Saving in the Transformers format.")
|
| 229 |
+
model.save_pretrained(model_path, safe_serialization=safe_serialization)
|
| 230 |
+
shutil.rmtree(tmp_model_path)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def write_tokenizer(tokenizer_path, input_tokenizer_path):
|
| 234 |
+
# Initialize the tokenizer based on the `spm` model
|
| 235 |
+
print(f"Saving a {tokenizer_class.__name__} to {tokenizer_path}.")
|
| 236 |
+
tokenizer = tokenizer_class(input_tokenizer_path)
|
| 237 |
+
tokenizer.save_pretrained(tokenizer_path)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def main():
|
| 241 |
+
parser = argparse.ArgumentParser()
|
| 242 |
+
parser.add_argument(
|
| 243 |
+
"--input_dir",
|
| 244 |
+
help="Location of Mistral weights, which contains tokenizer.model and model folders",
|
| 245 |
+
)
|
| 246 |
+
parser.add_argument(
|
| 247 |
+
"--model_size",
|
| 248 |
+
choices=["7B", "tokenizer_only"],
|
| 249 |
+
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",
|
| 250 |
+
)
|
| 251 |
+
parser.add_argument(
|
| 252 |
+
"--output_dir",
|
| 253 |
+
help="Location to write HF model and tokenizer",
|
| 254 |
+
)
|
| 255 |
+
parser.add_argument("--safe_serialization", type=bool, help="Whether or not to save using `safetensors`.")
|
| 256 |
+
args = parser.parse_args()
|
| 257 |
+
spm_path = os.path.join(args.input_dir, "tokenizer.model")
|
| 258 |
+
if args.model_size != "tokenizer_only":
|
| 259 |
+
write_model(
|
| 260 |
+
model_path=args.output_dir,
|
| 261 |
+
input_base_path=args.input_dir,
|
| 262 |
+
model_size=args.model_size,
|
| 263 |
+
safe_serialization=args.safe_serialization,
|
| 264 |
+
tokenizer_path=spm_path,
|
| 265 |
+
)
|
| 266 |
+
else:
|
| 267 |
+
write_tokenizer(args.output_dir, spm_path)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
if __name__ == "__main__":
|
| 271 |
+
main()
|