llama-factory
92 строки · 3.7 Кб
1# coding=utf-8
2# Converts the Baichuan2-7B model in the same format as LLaMA2-7B.
3# Usage: python llamafy_baichuan2.py --input_dir input --output_dir output
4# Inspired by: https://huggingface.co/fireballoon/baichuan-llama-7b/blob/main/convert_baichuan_to_llama.py
5# Converted model: https://huggingface.co/hiyouga/Baichuan2-7B-Base-LLaMAfied
6
7import json8import os9from collections import OrderedDict10from typing import Any, Dict, Optional11
12import fire13import torch14from safetensors.torch import save_file15from tqdm import tqdm16from transformers.modeling_utils import (17SAFE_WEIGHTS_INDEX_NAME,18SAFE_WEIGHTS_NAME,19WEIGHTS_INDEX_NAME,20WEIGHTS_NAME,21shard_checkpoint,22)
23
24
25CONFIG_NAME = "config.json"26
27
28def save_weight(input_dir: str, output_dir: str, shard_size: str, save_safetensors: bool):29baichuan2_state_dict: Dict[str, torch.Tensor] = OrderedDict()30for filepath in tqdm(os.listdir(input_dir), desc="Load weights"):31if os.path.isfile(os.path.join(input_dir, filepath)) and filepath.endswith(".bin"):32shard_weight = torch.load(os.path.join(input_dir, filepath), map_location="cpu")33baichuan2_state_dict.update(shard_weight)34
35llama2_state_dict: Dict[str, torch.Tensor] = OrderedDict()36for key, value in tqdm(baichuan2_state_dict.items(), desc="Convert format"):37if "W_pack" in key:38proj_size = value.size(0) // 339llama2_state_dict[key.replace("W_pack", "q_proj")] = value[:proj_size, :]40llama2_state_dict[key.replace("W_pack", "k_proj")] = value[proj_size : 2 * proj_size, :]41llama2_state_dict[key.replace("W_pack", "v_proj")] = value[2 * proj_size :, :]42elif "lm_head" in key:43llama2_state_dict[key] = torch.nn.functional.normalize(value)44else:45llama2_state_dict[key] = value46
47weights_name = SAFE_WEIGHTS_NAME if save_safetensors else WEIGHTS_NAME48shards, index = shard_checkpoint(llama2_state_dict, max_shard_size=shard_size, weights_name=weights_name)49
50for shard_file, shard in tqdm(shards.items(), desc="Save weights"):51if save_safetensors:52save_file(shard, os.path.join(output_dir, shard_file), metadata={"format": "pt"})53else:54torch.save(shard, os.path.join(output_dir, shard_file))55
56if index is None:57print("Model weights saved in {}".format(os.path.join(output_dir, WEIGHTS_NAME)))58else:59index_name = SAFE_WEIGHTS_INDEX_NAME if save_safetensors else WEIGHTS_INDEX_NAME60with open(os.path.join(output_dir, index_name), "w", encoding="utf-8") as f:61json.dump(index, f, indent=2, sort_keys=True)62print("Model weights saved in {}".format(output_dir))63
64
65def save_config(input_dir: str, output_dir: str):66with open(os.path.join(input_dir, CONFIG_NAME), "r", encoding="utf-8") as f:67llama2_config_dict: Dict[str, Any] = json.load(f)68
69llama2_config_dict["architectures"] = ["LlamaForCausalLM"]70llama2_config_dict.pop("auto_map", None)71llama2_config_dict.pop("tokenizer_class", None)72llama2_config_dict["model_type"] = "llama"73
74with open(os.path.join(output_dir, CONFIG_NAME), "w", encoding="utf-8") as f:75json.dump(llama2_config_dict, f, indent=2)76print("Model config saved in {}".format(os.path.join(output_dir, CONFIG_NAME)))77
78
79def llamafy_baichuan2(80input_dir: str, output_dir: str, shard_size: Optional[str] = "2GB", save_safetensors: Optional[bool] = False81):82try:83os.makedirs(output_dir, exist_ok=False)84except Exception as e:85raise print("Output dir already exists", e)86
87save_weight(input_dir, output_dir, shard_size, save_safetensors)88save_config(input_dir, output_dir)89
90
91if __name__ == "__main__":92fire.Fire(llamafy_baichuan2)93