File size: 3,608 Bytes
7e91f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Build a single PEFT output-head adapter from the tagged Cybermodels specialists."""

import argparse
import hashlib
import json
from pathlib import Path

import numpy as np
from safetensors.numpy import load_file, save_file

BASE = "HyperionGrayAI/qwennifer-flash-bf16"
PREFIX = "base_model.model.lm_head.lora_"


def build(sources, output, revision):
    catalog = json.loads((sources / "catalog.json").read_text())
    a_blocks, b_blocks, members = [], [], []
    reference = None
    for member in catalog["models"]:
        model = member["model"]
        folder = sources / model / member["revision"]
        path = folder / "adapter_model.safetensors"
        digest = hashlib.sha256(path.read_bytes()).hexdigest()
        if digest != member["adapter_sha256"]:
            raise ValueError(f"Unexpected source weights for {model}")
        config = json.loads((folder / "adapter_config.json").read_text())
        if (
            config["target_modules"] != ["lm_head"]
            or config["bias"] != "none"
            or config["use_rslora"]
            or config["use_dora"]
            or config["fan_in_fan_out"]
            or config.get("modules_to_save")
            or config.get("rank_pattern")
            or config.get("alpha_pattern")
        ):
            raise ValueError(f"Unsupported source adapter configuration for {model}")
        if reference is None:
            reference = config
        for key in ("base_model_name_or_path", "revision"):
            if reference[key] != config[key]:
                raise ValueError(f"Source bases differ for {model}")
        weights = load_file(str(path))
        a, b = (weights[PREFIX + key + ".weight"] for key in ("A", "B"))
        if (
            set(weights) != {PREFIX + k + ".weight" for k in ("A", "B")}
            or a.shape[0] != config["r"]
            or b.shape[1] != config["r"]
        ):
            raise ValueError(f"Unexpected source structure for {model}")
        a_blocks.append(a)
        b_blocks.append(b * (config["lora_alpha"] / config["r"]))
        members.append(
            {
                "model": model,
                "revision": member["revision"],
                "sha256": digest,
                "weight": 1.0,
            }
        )
    a = np.concatenate(a_blocks, axis=0)
    b = np.concatenate(b_blocks, axis=1)
    output.mkdir(parents=True, exist_ok=False)
    config = dict(
        reference,
        base_model_name_or_path=BASE,
        revision=revision,
        r=a.shape[0],
        lora_alpha=a.shape[0],
    )
    (output / "adapter_config.json").write_text(json.dumps(config, indent=2) + "\n")
    save_file(
        {PREFIX + "A.weight": a, PREFIX + "B.weight": b},
        str(output / "adapter_model.safetensors"),
        metadata={"format": "pt"},
    )
    provenance = {
        "base": BASE,
        "base_revision": revision,
        "members": members,
        "method": "Equal-weight sum of output-head deltas via rank concatenation",
        "rank": a.shape[0],
        "changed_vocabulary_rows": int(np.any(b, axis=1).sum()),
    }
    (output / "fusion.json").write_text(json.dumps(provenance, indent=2) + "\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "sources",
        type=Path,
        help="Directory containing catalog.json and the output of the team dataset's download_team.py",
    )
    parser.add_argument("output", type=Path)
    parser.add_argument("--revision", default="v0.1")
    args = parser.parse_args()
    build(args.sources, args.output, args.revision)