File size: 9,354 Bytes
48441eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Add LoRA side inputs to an exported Solstice ONNX model, so the browser can apply any LoRA at run time.

    python tools/add_lora_inputs.py IN.onnx OUT.onnx [--layers attn+mlp] [--check LORA.safetensors]

Solstice LoRAs (loras/r80-1202/*/lora.safetensors) are trained as W += strength * alpha/rank * B @ A on the
linears of every DiT block. ONNX Runtime Web cannot rewrite initializers after a session is created, so instead of
merging, this script finds each target linear's MatMul (by the `pkg.torch.onnx.name_scopes` metadata the dynamo
exporter writes) and adds a low-rank branch after it:

    y = x @ Wt (+ bias)  ->  y = x @ Wt (+ bias) + (x @ At[i]) @ Bt[i]

One pair of inputs per (stack, layer), stacked over the blocks of that stack, with a dynamic rank R:

    lora_<stack>_<layer>_A   [blocks, in, R]   = A.T for each block
    lora_<stack>_<layer>_B   [blocks, R, out]  = (scale * B).T for each block, scale = strength * alpha / rank

Several LoRAs are applied together by concatenating along R. With no LoRA, feed R = 1 zeros. The added work is
small (rank 16 on 384-wide layers).

--check merges a LoRA into the weights of a second copy (numpy) and compares one forward of the two models.
"""
import argparse
import ast
import json
import re
import struct
from pathlib import Path

import numpy as np
import onnx
from onnx import TensorProto, helper, numpy_helper

STACKS = ("outer_encoder", "bottleneck", "outer_decoder")
LAYERS = {
    "attn+mlp": ("self_attn.qkv", "self_attn.proj", "cross_attn.q", "cross_attn.k", "cross_attn.v",
                 "cross_attn.proj", "mlp.w12", "mlp.w3"),
}
RANK = "lora_rank"


def module_of(node):
    """The torch module path of a linear's MatMul / Gemm, without the export wrapper's prefix."""
    for p in node.metadata_props:
        if p.key == "pkg.torch.onnx.name_scopes":
            scopes = ast.literal_eval(p.value) if p.value.startswith("[") else p.value.split("/")
            for s in reversed(scopes):
                m = re.search(r"(?:^|\.)((?:%s)\.\d+\..+)$" % "|".join(STACKS), s)
                if m:
                    return m.group(1)
    return None


def find_targets(model, layers):
    inits = {i.name: i for i in model.graph.initializer}
    found = {}
    for idx, n in enumerate(model.graph.node):
        if n.op_type != "MatMul" or len(n.input) != 2 or n.input[1] not in inits:
            continue
        mod = module_of(n)
        if not mod:
            continue
        stack, block, layer = re.match(r"(\w+)\.(\d+)\.(.+)$", mod).groups()
        if layer not in layers:
            continue
        dims = list(inits[n.input[1]].dims)      # [in, out]: the exporter pre-transposes linear weights
        if len(dims) != 2:
            continue
        key = f"{stack}.{block}.{layer}"
        if key in found:
            raise SystemExit(f"two MatMuls for {key}")
        found[key] = (idx, stack, int(block), layer, dims)
    return found


def rewrite(model, layers):
    targets = find_targets(model, layers)
    if not targets:
        raise SystemExit("no target linears found (was the model exported with dynamo=True?)")
    groups = {}
    for key, (idx, stack, block, layer, dims) in targets.items():
        g = groups.setdefault((stack, layer), {"blocks": set(), "in": dims[0], "out": dims[1]})
        g["blocks"].add(block)
        assert g["in"] == dims[0] and g["out"] == dims[1], key
    spec = []
    for (stack, layer), g in sorted(groups.items(), key=lambda kv: (STACKS.index(kv[0][0]), layers.index(kv[0][1]))):
        n = len(g["blocks"])
        assert g["blocks"] == set(range(n)), (stack, layer, g["blocks"])
        base = f"lora_{stack}_{layer.replace('.', '_')}"
        spec.append({"stack": stack, "layer": layer, "blocks": n, "in": g["in"], "out": g["out"],
                     "A": base + "_A", "B": base + "_B"})
        model.graph.input.append(helper.make_tensor_value_info(base + "_A", TensorProto.FLOAT, [n, g["in"], RANK]))
        model.graph.input.append(helper.make_tensor_value_info(base + "_B", TensorProto.FLOAT, [n, RANK, g["out"]]))

    by_idx = {v[0]: v for v in targets.values()}
    idx_consts = {}
    new_nodes = []
    for idx, node in enumerate(model.graph.node):
        new_nodes.append(node)
        if idx not in by_idx:
            continue
        _, stack, block, layer, _ = by_idx[idx]
        base = f"lora_{stack}_{layer.replace('.', '_')}"
        tag = f"{base}_{block}"
        if block not in idx_consts:
            name = f"lora_index_{block}"
            model.graph.initializer.append(numpy_helper.from_array(np.array(block, np.int64), name))
            idx_consts[block] = name
        y = node.output[0]
        node.output[0] = y + "_lorabase"
        new_nodes += [
            helper.make_node("Gather", [base + "_A", idx_consts[block]], [tag + "_a"], axis=0, name=tag + "_gA"),
            helper.make_node("Gather", [base + "_B", idx_consts[block]], [tag + "_b"], axis=0, name=tag + "_gB"),
            helper.make_node("MatMul", [node.input[0], tag + "_a"], [tag + "_xa"], name=tag + "_mmA"),
            helper.make_node("MatMul", [tag + "_xa", tag + "_b"], [tag + "_d"], name=tag + "_mmB"),
            helper.make_node("Add", [y + "_lorabase", tag + "_d"], [y], name=tag + "_add"),
        ]
    del model.graph.node[:]
    model.graph.node.extend(new_nodes)
    model.metadata_props.append(onnx.StringStringEntryProto(key="solstice_lora", value=json.dumps(spec)))
    return spec, targets


def read_safetensors(path):
    raw = Path(path).read_bytes()
    n = struct.unpack("<Q", raw[:8])[0]
    header = json.loads(raw[8:8 + n])
    meta = header.pop("__metadata__", {})
    out = {}
    for k, v in header.items():
        assert v["dtype"] == "F32", v["dtype"]
        a, b = v["data_offsets"]
        out[k] = np.frombuffer(raw[8 + n + a:8 + n + b], np.float32).reshape(v["shape"])
    return out, meta


def lora_feeds(spec, tensors, scale):
    feeds = {}
    for s in spec:
        As, Bs = [], []
        for b in range(s["blocks"]):
            key = f"{s['stack']}.{b}.{s['layer']}"
            As.append(tensors[key + ".A"].T)             # [in, R]
            Bs.append((scale * tensors[key + ".B"]).T)   # [R, out]
        feeds[s["A"]] = np.ascontiguousarray(np.stack(As), np.float32)
        feeds[s["B"]] = np.ascontiguousarray(np.stack(Bs), np.float32)
    return feeds


def zero_feeds(spec):
    return {**{s["A"]: np.zeros((s["blocks"], s["in"], 1), np.float32) for s in spec},
            **{s["B"]: np.zeros((s["blocks"], 1, s["out"]), np.float32) for s in spec}}


def check(src, dst, spec, targets, lora_path):
    import onnxruntime as ort
    tensors, meta = read_safetensors(lora_path)
    scale = float(meta.get("alpha", 16)) / float(meta.get("rank", 16))

    merged = onnx.load(src)
    inits = {i.name: i for i in merged.graph.initializer}
    for key, (idx, *_rest) in targets.items():
        w = inits[merged.graph.node[idx].input[1]]
        W = numpy_helper.to_array(w).copy()             # [in, out]
        W += (scale * tensors[key + ".B"] @ tensors[key + ".A"]).T
        w.CopyFrom(numpy_helper.from_array(W.astype(np.float32), w.name))
    so = ort.SessionOptions()
    so.log_severity_level = 3
    s_merged = ort.InferenceSession(merged.SerializeToString(), so, providers=["CPUExecutionProvider"])
    s_plain = ort.InferenceSession(str(src), so, providers=["CPUExecutionProvider"])
    s_lora = ort.InferenceSession(str(dst), so, providers=["CPUExecutionProvider"])

    rng = np.random.default_rng(0)
    B = 2
    feeds = {}
    for i in s_plain.get_inputs():
        shape = [B if not isinstance(d, int) else d for d in i.shape]
        if i.type == "tensor(bool)":
            m = np.zeros(shape, bool)
            m[:, :12] = True
            feeds[i.name] = m
        elif i.name == "t":
            feeds[i.name] = np.array([0.7, 0.3], np.float32)
        elif i.name == "w":
            feeds[i.name] = np.full(shape, 4.0, np.float32)
        else:
            feeds[i.name] = rng.standard_normal(shape).astype(np.float32)
    plain = s_plain.run(None, feeds)[0]
    merged_out = s_merged.run(None, feeds)[0]
    zero = s_lora.run(None, {**feeds, **zero_feeds(spec)})[0]
    lora = s_lora.run(None, {**feeds, **lora_feeds(spec, tensors, scale)})[0]
    print(f"LoRA inputs, zero rank-1 vs original:  max |diff| {np.abs(zero - plain).max():.2e}")
    print(f"LoRA inputs vs merged weights:         max |diff| {np.abs(lora - merged_out).max():.2e}")
    print(f"merged vs original (the LoRA's effect): max |diff| {np.abs(merged_out - plain).max():.2e}")


def main():
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("src", type=Path)
    p.add_argument("dst", type=Path)
    p.add_argument("--layers", default="attn+mlp", choices=sorted(LAYERS))
    p.add_argument("--check", type=Path, help="a LoRA .safetensors to verify against weight merging")
    a = p.parse_args()
    model = onnx.load(a.src)
    spec, targets = rewrite(model, LAYERS[a.layers])
    onnx.checker.check_model(model, full_check=False)
    onnx.save(model, a.dst)
    print(f"{a.dst}: {len(targets)} linears in {len(spec)} groups, {2 * len(spec)} LoRA inputs")
    if a.check:
        check(a.src, a.dst, spec, targets, a.check)


if __name__ == "__main__":
    main()