2023-12-01 03:08:53 +08:00
|
|
|
# Copyright © 2023 Apple Inc.
|
|
|
|
|
2023-11-30 06:14:11 +08:00
|
|
|
import argparse
|
2023-12-10 06:13:55 +08:00
|
|
|
import json
|
2023-11-30 06:14:11 +08:00
|
|
|
import numpy as np
|
2023-12-10 06:13:55 +08:00
|
|
|
from pathlib import Path
|
|
|
|
import shutil
|
|
|
|
import os
|
2023-11-30 06:14:11 +08:00
|
|
|
import torch
|
|
|
|
|
|
|
|
|
2023-12-10 06:13:55 +08:00
|
|
|
if __name__ == "__main__":
|
|
|
|
parser = argparse.ArgumentParser(
|
|
|
|
description="Convert Mistral or Llama models to MLX.",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2023-12-16 02:06:14 +08:00
|
|
|
"--torch-model",
|
2023-12-10 06:13:55 +08:00
|
|
|
type=str,
|
|
|
|
default="mistral-7B-v0.1/",
|
|
|
|
help="The torch model directory",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
2023-12-16 02:06:14 +08:00
|
|
|
"--mlx-model",
|
2023-12-10 06:13:55 +08:00
|
|
|
type=str,
|
|
|
|
default="mlx-mistral-7B-v0.1/",
|
|
|
|
help="The directory to store the mlx model",
|
|
|
|
)
|
|
|
|
args = parser.parse_args()
|
2023-11-30 06:14:11 +08:00
|
|
|
|
2023-12-10 06:13:55 +08:00
|
|
|
torch_path = Path(args.torch_model)
|
|
|
|
if not os.path.exists(args.mlx_model):
|
|
|
|
os.makedirs(args.mlx_model)
|
2023-12-10 06:15:25 +08:00
|
|
|
mlx_path = Path(args.mlx_model)
|
2023-11-30 06:14:11 +08:00
|
|
|
|
2023-12-10 06:13:55 +08:00
|
|
|
state = torch.load(str(torch_path / "consolidated.00.pth"))
|
|
|
|
np.savez(
|
|
|
|
str(mlx_path / "weights.npz"),
|
|
|
|
**{k: v.to(torch.float16).numpy() for k, v in state.items()}
|
|
|
|
)
|
2023-11-30 06:14:11 +08:00
|
|
|
|
2023-12-10 06:13:55 +08:00
|
|
|
# Copy the tokenizer
|
|
|
|
shutil.copyfile(
|
|
|
|
str(torch_path / "tokenizer.model"),
|
|
|
|
str(mlx_path / "tokenizer.model"),
|
2023-12-08 16:19:35 +08:00
|
|
|
)
|
2023-11-30 06:14:11 +08:00
|
|
|
|
2023-12-10 06:13:55 +08:00
|
|
|
# Copy the params
|
|
|
|
with open(torch_path / "params.json", "r") as f:
|
|
|
|
config = json.loads(f.read())
|
2023-12-11 06:35:39 +08:00
|
|
|
n_heads = config["n_heads"]
|
2023-12-10 06:13:55 +08:00
|
|
|
if "sliding_window" in config:
|
|
|
|
config.pop("sliding_window")
|
|
|
|
if "n_kv_heads" not in config:
|
|
|
|
config["n_kv_heads"] = n_heads
|
|
|
|
if "head_dim" not in config:
|
|
|
|
config["head_dim"] = config["dim"] // n_heads
|
|
|
|
if "hidden_dim" not in config:
|
|
|
|
config["hidden_dim"] = state["layers.0.feed_forward.w1.weight"].shape
|
|
|
|
with open(mlx_path / "params.json", "w") as outfile:
|
|
|
|
json.dump(config, outfile)
|