File size: 4,862 Bytes
15c46ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
"""Download pinned weights and restore the exact Vicuna v0 base on a GPU host."""
import argparse
import gc
import hashlib
import json
import os
import sys
import urllib.request
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from settings import IMAGEBIND_URL, MODELS, WEIGHTS, missing_weights, weight_paths


def download_model(key, target, patterns=None):
    from huggingface_hub import snapshot_download
    repo, revision = MODELS[key]
    snapshot_download(repo, revision=revision, local_dir=str(target),
                      allow_patterns=patterns, max_workers=2,
                      token=os.getenv("HF_TOKEN") or None)


def restore_vicuna():
    # Algorithm follows FastChat v0.1.10 apply_delta.py (Apache-2.0):
    # https://github.com/lm-sys/FastChat/blob/v0.1.10/fastchat/model/apply_delta.py
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer
    target = weight_paths()["vicuna"]
    if (target / "merge_complete.json").is_file():
        return
    base_path, delta_path = WEIGHTS / "sources" / "llama", WEIGHTS / "sources" / "vicuna_delta"
    patterns = ["*.json", "*.model", "pytorch_model*.bin"]
    download_model("llama", base_path, patterns)
    download_model("vicuna_delta", delta_path, patterns)
    base = AutoModelForCausalLM.from_pretrained(str(base_path), torch_dtype=torch.float16, low_cpu_mem_usage=True)
    delta = AutoModelForCausalLM.from_pretrained(str(delta_path), torch_dtype=torch.float16, low_cpu_mem_usage=True)
    tokenizer = AutoTokenizer.from_pretrained(str(base_path), use_fast=False)
    added = tokenizer.add_special_tokens({"pad_token": "[PAD]"})
    base.resize_token_embeddings(len(tokenizer))
    if added:
        base.get_input_embeddings().weight.data[-added:] = 0
        base.get_output_embeddings().weight.data[-added:] = 0
    base_state, delta_state = base.state_dict(), delta.state_dict()
    if set(base_state) != set(delta_state):
        raise RuntimeError("LLaMA 与 Vicuna v0 参数名不一致,停止合并。")
    with torch.no_grad():
        for name, parameter in base_state.items():
            if parameter.shape != delta_state[name].shape:
                raise RuntimeError("权重尺寸不一致:" + name)
            parameter.add_(delta_state[name])
    target.mkdir(parents=True, exist_ok=True)
    base.save_pretrained(str(target), max_shard_size="2GB", safe_serialization=False)
    AutoTokenizer.from_pretrained(str(delta_path), use_fast=False).save_pretrained(str(target))
    (target / "merge_complete.json").write_text(json.dumps({
        "base": MODELS["llama"], "delta": MODELS["vicuna_delta"],
        "method": "FastChat v0.1.10: pad-token resize, zero new embeddings, add delta",
    }, indent=2), encoding="utf-8")
    del base, delta, base_state, delta_state
    gc.collect()


def prepare(merge=False):
    WEIGHTS.mkdir(parents=True, exist_ok=True)
    bind = weight_paths()["imagebind"]
    if not bind.is_file():
        bind.parent.mkdir(parents=True, exist_ok=True)
        temporary = bind.with_suffix(".part")
        print("Downloading ImageBind huge", flush=True)
        urllib.request.urlretrieve(IMAGEBIND_URL, temporary)
        if temporary.stat().st_size < 1_000_000_000:
            raise RuntimeError("ImageBind 下载文件大小异常,未标记为完成。")
        temporary.replace(bind)
    download_model("nextgpt", WEIGHTS / "nextgpt", ["*.json", "*.model", "pytorch_model.pt"])
    for key in ("image", "video", "audio"):
        # Use the original float32 .bin format; skip duplicate fp16/Flax/ONNX files.
        from huggingface_hub import snapshot_download
        repo, revision = MODELS[key]
        snapshot_download(repo, revision=revision, local_dir=str(WEIGHTS / key),
                          allow_patterns=["*.json", "*.txt", "*.bin"],
                          ignore_patterns=["*.fp16.*", "zs2_576w/*"], max_workers=2,
                          token=os.getenv("HF_TOKEN") or None)
    if merge:
        restore_vicuna()
    manifest = {"models": MODELS, "imagebind_url": IMAGEBIND_URL,
                "imagebind_sha256": sha256(bind), "missing_weights": missing_weights()}
    (WEIGHTS / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
    print(json.dumps(manifest, ensure_ascii=False, indent=2))


def sha256(path):
    digest = hashlib.sha256()
    with path.open("rb") as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--merge-vicuna", action="store_true",
                        help="Also download LLaMA-7B + Vicuna v0 delta and restore the base (~30GB RAM peak)")
    args = parser.parse_args()
    prepare(args.merge_vicuna)