"""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___A [blocks, in, R] = A.T for each block lora___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("