llama-factory

Форк
0
/
llamafy_baichuan2.py 
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

7
import json
8
import os
9
from collections import OrderedDict
10
from typing import Any, Dict, Optional
11

12
import fire
13
import torch
14
from safetensors.torch import save_file
15
from tqdm import tqdm
16
from transformers.modeling_utils import (
17
    SAFE_WEIGHTS_INDEX_NAME,
18
    SAFE_WEIGHTS_NAME,
19
    WEIGHTS_INDEX_NAME,
20
    WEIGHTS_NAME,
21
    shard_checkpoint,
22
)
23

24

25
CONFIG_NAME = "config.json"
26

27

28
def save_weight(input_dir: str, output_dir: str, shard_size: str, save_safetensors: bool):
29
    baichuan2_state_dict: Dict[str, torch.Tensor] = OrderedDict()
30
    for filepath in tqdm(os.listdir(input_dir), desc="Load weights"):
31
        if os.path.isfile(os.path.join(input_dir, filepath)) and filepath.endswith(".bin"):
32
            shard_weight = torch.load(os.path.join(input_dir, filepath), map_location="cpu")
33
            baichuan2_state_dict.update(shard_weight)
34

35
    llama2_state_dict: Dict[str, torch.Tensor] = OrderedDict()
36
    for key, value in tqdm(baichuan2_state_dict.items(), desc="Convert format"):
37
        if "W_pack" in key:
38
            proj_size = value.size(0) // 3
39
            llama2_state_dict[key.replace("W_pack", "q_proj")] = value[:proj_size, :]
40
            llama2_state_dict[key.replace("W_pack", "k_proj")] = value[proj_size : 2 * proj_size, :]
41
            llama2_state_dict[key.replace("W_pack", "v_proj")] = value[2 * proj_size :, :]
42
        elif "lm_head" in key:
43
            llama2_state_dict[key] = torch.nn.functional.normalize(value)
44
        else:
45
            llama2_state_dict[key] = value
46

47
    weights_name = SAFE_WEIGHTS_NAME if save_safetensors else WEIGHTS_NAME
48
    shards, index = shard_checkpoint(llama2_state_dict, max_shard_size=shard_size, weights_name=weights_name)
49

50
    for shard_file, shard in tqdm(shards.items(), desc="Save weights"):
51
        if save_safetensors:
52
            save_file(shard, os.path.join(output_dir, shard_file), metadata={"format": "pt"})
53
        else:
54
            torch.save(shard, os.path.join(output_dir, shard_file))
55

56
    if index is None:
57
        print("Model weights saved in {}".format(os.path.join(output_dir, WEIGHTS_NAME)))
58
    else:
59
        index_name = SAFE_WEIGHTS_INDEX_NAME if save_safetensors else WEIGHTS_INDEX_NAME
60
        with open(os.path.join(output_dir, index_name), "w", encoding="utf-8") as f:
61
            json.dump(index, f, indent=2, sort_keys=True)
62
        print("Model weights saved in {}".format(output_dir))
63

64

65
def save_config(input_dir: str, output_dir: str):
66
    with open(os.path.join(input_dir, CONFIG_NAME), "r", encoding="utf-8") as f:
67
        llama2_config_dict: Dict[str, Any] = json.load(f)
68

69
    llama2_config_dict["architectures"] = ["LlamaForCausalLM"]
70
    llama2_config_dict.pop("auto_map", None)
71
    llama2_config_dict.pop("tokenizer_class", None)
72
    llama2_config_dict["model_type"] = "llama"
73

74
    with open(os.path.join(output_dir, CONFIG_NAME), "w", encoding="utf-8") as f:
75
        json.dump(llama2_config_dict, f, indent=2)
76
    print("Model config saved in {}".format(os.path.join(output_dir, CONFIG_NAME)))
77

78

79
def llamafy_baichuan2(
80
    input_dir: str, output_dir: str, shard_size: Optional[str] = "2GB", save_safetensors: Optional[bool] = False
81
):
82
    try:
83
        os.makedirs(output_dir, exist_ok=False)
84
    except Exception as e:
85
        raise print("Output dir already exists", e)
86

87
    save_weight(input_dir, output_dir, shard_size, save_safetensors)
88
    save_config(input_dir, output_dir)
89

90

91
if __name__ == "__main__":
92
    fire.Fire(llamafy_baichuan2)
93

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.