File size: 14,110 Bytes
9fae48b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""Merge a LoRA adapter (an adapter folder in the usual layout) into the FP32 master weights, then export.

A small low-rank update added to BF16 weights is mostly lost: each element moves by a fraction of a BF16 step and
rounds back. Added to the FP32 masters and rounded once, it survives. This script writes a new FP32
master-weights folder; masters_to_bf16.py and to_fp8.py then turn it into servable folders (--bf16, --fp8 run
them for you).

THE ARITHMETIC, exactly (so that the same adapter gives the same bytes everywhere):
  For a target matrix W [out, in] (FP32) with adapter matrices A [r, in] and B [out, r]:
    s          = lora_alpha / r            (lora_alpha / sqrt(r) with use_rslora), an IEEE double
    acc[i, j]  = sum over k = 0 .. r-1, in this order, of double(B[i, k]) * double(A[k, j])
                 (each product is exact in double; each addition is one IEEE double addition, starting from 0.0)
    W'[i, j]   = fp32( double(W[i, j]) + s * acc[i, j] )
                 (one double multiplication, one double addition, one rounding to FP32; all round to nearest even)
  No matrix-multiply routine is used, because those sum in an order that depends on the machine.
  Every tensor that is not a target is copied byte for byte.

  --round-bf16: each merged matrix is then rounded to BF16 (to nearest, ties to even) and stored as FP32:
    W''[i, j]  = fp32( bf16( W'[i, j] ) )
  Those values are exactly representable in BF16, so masters_to_bf16.py on the result changes nothing in them and
  to_fp8.py quantizes the BF16-rounded merge directly. This is the merge for adapters that were trained against
  BF16-rounded weights, round_bf16(master + update), with a straight-through estimator. Tensors that are not
  targets stay as in SRC (FP32 masters) in this mode too.

ADAPTER
  ADAPTER/adapter_config.json   "peft_type": "LORA"; r, lora_alpha, use_rslora are read. Refused: use_dora, fan_in_fan_out,
                                rank_pattern / alpha_pattern, bias other than "none", modules_to_save, lora_bias.
  ADAPTER/adapter_model.safetensors
                                keys base_model.model.<MODULE>.lora_A.weight [r, in] and .lora_B.weight [out, r],
                                FP32 or BF16; <MODULE>.weight must be a matrix [out, in] in the masters folder.
                                The draft head (a separate file) cannot be a target.

usage: merge_lora.py SRC ADAPTER_DIR DST [--round-bf16] [--bf16 DIR] [--fp8 DIR] [--mtp FILE | --no-mtp]
                     [--check --sums FILE] [--sums-bf16 FILE] [--sums-fp8 FILE]
                     [--workers 8] [--threads 4] [--exact-rounding]

  SRC           the FP32 master-weights folder (the release folder)
  DST           the merged FP32 master-weights folder to write: the same layout, mtp.safetensors copied unchanged,
                its own SHA256SUMS, the merge recorded in lora-merge.json (mode, the adapter's sha256, scaling,
                targets) and in fp32-release.json. The exports' lists of SRC (SHA256SUMS.bf16, SHA256SUMS.fp8)
                do not apply to merged weights and are not copied.
  --bf16 DIR    then run masters_to_bf16.py DST DIR         --fp8 DIR    then run to_fp8.py DST DIR
  --check --sums FILE            compare DST with a list published for this merge
  --sums-bf16 / --sums-fp8 FILE  compare the BF16 / FP8 folder with a list published for this merge

Needs python >= 3.9 and torch (CPU).
"""
import argparse
import json
import math
import os
import shutil
import subprocess
import sys

import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))    # the tools find each other in any python mode
import fp32_common as c

PREFIX = "base_model.model."
MERGE_NOTE = "lora-merge.json"
ROWS_AT_A_TIME = 1 << 24          # elements per row block of the double-precision work


def read_adapter(folder):
    """({target tensor name: (A, B)}, scaling, a record of the adapter for the manifest)."""
    config_path = os.path.join(folder, "adapter_config.json")
    weights_path = os.path.join(folder, "adapter_model.safetensors")
    for path in (config_path, weights_path):
        if not os.path.isfile(path):
            c.fail("the adapter folder lacks %s" % os.path.basename(path))
    with open(config_path) as f:
        config = json.load(f)
    if config.get("peft_type") != "LORA":
        c.fail("adapter_config.json: peft_type is %r, not LORA" % config.get("peft_type"))
    for key, harmless in (("use_dora", (None, False)), ("fan_in_fan_out", (None, False)), ("rank_pattern", (None, {})),
                          ("alpha_pattern", (None, {})), ("bias", (None, "none")), ("modules_to_save", (None, [])),
                          ("lora_bias", (None, False))):
        if config.get(key) not in harmless:
            c.fail("adapter_config.json: %s = %r is not handled" % (key, config.get(key)))
    r, alpha = config.get("r"), config.get("lora_alpha")
    if not isinstance(r, int) or isinstance(r, bool) or r < 1 or not isinstance(alpha, (int, float)) or isinstance(alpha, bool):
        c.fail("adapter_config.json: r = %r, lora_alpha = %r" % (r, alpha))
    rslora = config.get("use_rslora") or False
    if rslora is not True and rslora is not False:
        c.fail("adapter_config.json: use_rslora = %r" % (rslora,))
    scaling = float(alpha) / math.sqrt(r) if rslora else float(alpha) / r
    weights = c.TensorFile(weights_path)
    pairs = {}
    for key in weights.names():
        for part in ("lora_A", "lora_B"):
            if key.startswith(PREFIX) and key.endswith("." + part + ".weight"):
                module = key[len(PREFIX):-len("." + part + ".weight")]
                pairs.setdefault(module + ".weight", {})[part] = key
                break
        else:
            c.fail("adapter tensor %s is not a %s<MODULE>.lora_A.weight or .lora_B.weight" % (key, PREFIX))
    out = {}
    for name in sorted(pairs):
        if set(pairs[name]) != {"lora_A", "lora_B"}:
            c.fail("the adapter has only one of lora_A / lora_B for %s" % name)
        pair = []
        for part in ("lora_A", "lora_B"):
            key = pairs[name][part]
            if weights.dtype(key) not in ("F32", "BF16"):
                c.fail("adapter tensor %s is %s" % (key, weights.dtype(key)))
            tensor = weights.read(key).float()
            c.finite(key, tensor)
            pair.append(tensor)
        a, b = pair
        if a.dim() != 2 or b.dim() != 2 or a.shape[0] != r or b.shape[1] != r:
            c.fail("%s: lora_A %s and lora_B %s do not have rank r = %d" % (name, list(a.shape), list(b.shape), r))
        out[name] = (a, b)
    if not out:
        c.fail("the adapter holds no tensors")
    record = {"adapter_config_sha256": c.sha256_file(config_path), "adapter_model_sha256": c.sha256_file(weights_path),
              "r": r, "lora_alpha": alpha, "use_rslora": rslora, "scaling": scaling, "targets": sorted(out)}
    return out, scaling, record


def merged(weight, a, b, scaling, round_bf16=False, exact=False):
    """W' of the module text (W'' with ROUND_BF16); row blocks keep the double-precision work small.
    Returns (the merged FP32 matrix, the squared Frobenius size of the update)."""
    rows, cols = weight.shape
    result = torch.empty_like(weight)
    a64 = a.double()
    step = max(1, ROWS_AT_A_TIME // cols)
    change = 0.0
    for start in range(0, rows, step):
        b64 = b[start:start + step].double()
        acc = torch.zeros(b64.shape[0], cols, dtype=torch.float64)
        for k in range(a64.shape[0]):
            product = b64[:, k:k + 1] * a64[k:k + 1, :]
            acc = acc + product
        delta = acc * scaling
        change += float((delta * delta).sum())
        block = (weight[start:start + step].double() + delta).float()
        result[start:start + step] = c.to_bf16(block, exact).float() if round_bf16 else block
    return result, change


def merge_shard(job):
    shard, folder, partial, adapter, scaling, round_bf16, exact = job
    targets = [n for n in folder.names_in(shard) if n in adapter]
    if not targets:
        shutil.copyfile(os.path.join(folder.path, shard), os.path.join(partial, shard))
        return shard, c.sha256_file(os.path.join(partial, shard)), []
    tensors, notes = {}, []
    for name in folder.names_in(shard):
        x = folder.read(name)
        if name in adapter:
            a, b = adapter[name]
            y, change = merged(x, a, b, scaling, round_bf16, exact)
            c.finite(name + " after the merge", y)
            size = float(x.double().pow(2).sum())
            notes.append((name, math.sqrt(change / size) if size else float("nan"),
                          float((c.bits32(y) != c.bits32(x)).double().mean())))
            x = y
        tensors[name] = ("F32", x)
    digest, _ = c.write_shard(os.path.join(partial, shard), tensors)
    return shard, digest, notes


def main():
    parser = argparse.ArgumentParser(description=__doc__.split(c.NL)[0], allow_abbrev=False)
    parser.add_argument("masters")
    parser.add_argument("adapter")
    parser.add_argument("output")
    parser.add_argument("--round-bf16", action="store_true",
                        help="round each merged matrix to BF16 and store it as FP32 (for adapters trained against BF16-rounded weights)")
    parser.add_argument("--bf16", metavar="DIR")
    parser.add_argument("--fp8", metavar="DIR")
    parser.add_argument("--mtp", metavar="FILE")
    parser.add_argument("--no-mtp", action="store_true")
    parser.add_argument("--sums-bf16", metavar="FILE")
    parser.add_argument("--sums-fp8", metavar="FILE")
    c.add_common_arguments(parser)
    args = parser.parse_args()
    sums = c.published_sums(args, None)
    if args.check_only:
        sys.exit(0 if c.check_sums(args.output, sums, args.workers) else 1)
    if (args.sums_bf16 and not args.bf16) or (args.sums_fp8 and not args.fp8):
        parser.error("--sums-bf16 / --sums-fp8 need --bf16 / --fp8")
    for path in (args.sums_bf16, args.sums_fp8):
        if path and not os.path.isfile(path):
            c.fail("no list at %s" % path)
    torch.set_grad_enabled(False)
    torch.set_num_threads(args.threads)
    mode = "round-bf16" if args.round_bf16 else "fp32"
    c.say("merge_lora:", c.versions(), "| mode", mode)
    if not args.exact_rounding:
        c.self_test()
    folder, manifest = c.open_masters(args.masters)
    c.open_mtp(args.masters, manifest, args.mtp, args.no_mtp)          # fail early, before the long merge
    for target in (args.bf16, args.fp8):
        if target and os.path.exists(target):
            c.fail("%s exists; choose a new name" % target)
    adapter, scaling, record = read_adapter(args.adapter)
    for name, (a, b) in adapter.items():
        if name not in folder.weight_map:
            c.fail("the adapter targets %s, which the masters folder does not hold" % name)
        if folder.shape(name) != [b.shape[0], a.shape[1]]:
            c.fail("%s is %s but the adapter's update is %s" % (name, folder.shape(name), [b.shape[0], a.shape[1]]))
    c.say("adapter: %d target matrices, r = %d, scaling = %r" % (len(adapter), record["r"], scaling))
    out, partial = c.start_output(args.output)
    results = c.run_shards([(shard, folder, partial, adapter, scaling, args.round_bf16, args.exact_rounding)
                            for shard in folder.shards()], merge_shard, args.workers)
    digests = {shard: digest for shard, digest, _ in results}
    for _, _, notes in results:
        for name, relative, changed in notes:
            c.say("   merged %s: update / weight = %.3e (Frobenius), %.1f%% of its FP32 values changed" % (
                name, relative, 100 * changed))
    shutil.copyfile(os.path.join(args.masters, c.INDEX), os.path.join(partial, c.INDEX))
    c.copy_small_files(args.masters, manifest["small_files"], partial)
    for name in (c.MTP_FILE, c.MTP_NOTE):
        if os.path.isfile(os.path.join(args.masters, name)):
            shutil.copyfile(os.path.join(args.masters, name), os.path.join(partial, name))
    record = dict(record, mode=mode)
    earlier = list(manifest.get("lora_merges", []))
    manifest = dict(manifest, lora_merges=earlier + [record])
    with open(os.path.join(partial, c.MANIFEST), "w") as f:
        f.write(json.dumps(manifest, indent=1) + c.NL)
    note = {"mode": mode,
            "meaning": "merged = fp32(master + scaling * B A), the sum in double precision in a fixed order" + (
                ", then rounded to BF16 (nearest even) and stored as FP32" if args.round_bf16 else ""),
            "adapter_model_sha256": record["adapter_model_sha256"], "adapter_config_sha256": record["adapter_config_sha256"],
            "scaling": scaling, "r": record["r"], "lora_alpha": record["lora_alpha"], "use_rslora": record["use_rslora"],
            "targets": record["targets"], "merged_tensors": len(adapter), "earlier_merges_in_source": len(earlier),
            "source_optimizer_file_sha256": manifest.get("source", {}).get("optimizer_file_sha256")}
    with open(os.path.join(partial, MERGE_NOTE), "w") as f:
        f.write(json.dumps(note, indent=1) + c.NL)
    c.finish(partial, out, digests, sums, args.workers)
    c.say("MERGE DONE %s: %d matrices merged, mode %s" % (out, len(adapter), mode))
    here = os.path.dirname(os.path.abspath(__file__))
    for script, target, check in (("masters_to_bf16.py", args.bf16, args.sums_bf16), ("to_fp8.py", args.fp8, args.sums_fp8)):
        if not target:
            continue
        command = [sys.executable, os.path.join(here, script), out, target,
                   "--workers", str(args.workers), "--threads", str(args.threads)]
        if args.mtp:
            command += ["--mtp", args.mtp]
        if args.no_mtp:
            command += ["--no-mtp"]
        if args.exact_rounding:
            command += ["--exact-rounding"]
        if check:
            command += ["--check", "--sums", os.path.abspath(check)]
        c.say("running", " ".join(command))
        status = subprocess.call(command)
        if status:
            sys.exit(status)


if __name__ == "__main__":
    main()