Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: re-merge only the layers of the LoRA adapters whose weight changed (#17102)
Daniel Han1b1d91926985
diff --git a/studio/backend/core/inference/diffusion_lora_quant_merge.py b/studio/backend/core/inference/diffusion_lora_quant_merge.pyindex f4c142b20dd..bdec961cccf 100644--- a/studio/backend/core/inference/diffusion_lora_quant_merge.py+++ b/studio/backend/core/inference/diffusion_lora_quant_merge.py@@ -18,10 +18,23 @@ _FP8_MAX = 448.0_INT8_MAX = 127.0+# "0": a weight change restores and re-merges every merged layer, not only those of the adapters it changes.+INCREMENTAL_ENV = "UNSLOTH_DIFFUSION_LORA_INCREMENTAL_REMERGE"++def enabled() -> bool:return (os.environ.get(MERGE_ENV) or "").strip().lower() not in ("0", "off", "false", "no")+def _incremental() -> bool:+ return (os.environ.get(INCREMENTAL_ENV) or "").strip().lower() not in (+ "0",+ "off",+ "false",+ "no",+ )++def merged(pipe: Any) -> bool:return getattr(pipe, _MERGED_ATTR, None) is not None@@ -253,7 +266,13 @@ def _host_room(layers: list) -> bool:return (int(available) << 20) - nbytes >= _HOST_RESERVE-def _apply(layers: list, weights: dict, device: Any) -> None:+def _apply(+ layers: list,+ weights: dict,+ device: Any,+ only: Optional[set] = None,+) -> None:+ """``only``: layer indices to merge; seeds stay full-list indices, so a subset matches a full re-merge."""import torch# No TF32: the same weights must merge to the same codes before and after a speed profile engages.@@ -262,6 +281,8 @@ def _apply(layers: list, weights: dict, device: Any) -> None:try:with torch.no_grad():for index, entry in enumerate(layers):+ if only is not None and index not in only:+ continuemodule = entry.modulekind = _weight_kind(module.weight)live = [t for t in entry.terms if weights.get(t.adapter, 0.0)]@@ -276,10 +297,12 @@ def _apply(layers: list, weights: dict, device: Any) -> None:torch.backends.cuda.matmul.allow_tf32 = tf32-def _restore(layers: list) -> None:+def _restore(layers: list, only: Optional[set] = None) -> None:import torchwith torch.no_grad():- for entry in layers:+ for index, entry in enumerate(layers):+ if only is not None and index not in only:+ continuekind = _weight_kind(entry.module.weight)for key, live in _tensors(entry.module.weight, kind).items():live.copy_(entry.backup[key])@@ -347,9 +370,15 @@ def set_weights(pipe: Any, weights: dict) -> bool:if live.device.type != "meta":device = live.devicebreak- _restore(layers)+ only = None+ if _incremental():+ # a layer's codes depend only on its own adapters' weights+ old = state["weights"]+ changed = {n for n in set(old) | set(weights) if old.get(n, 0.0) != weights.get(n, 0.0)}+ only = {i for i, e in enumerate(layers) if any(t.adapter in changed for t in e.terms)}+ _restore(layers, only)try:- _apply(layers, weights, device)+ _apply(layers, weights, device, only)except Exception:# Never leave half the layers merged: the base weights, then the error._restore(layers)diff --git a/studio/backend/tests/test_diffusion_lora_incremental_remerge.py b/studio/backend/tests/test_diffusion_lora_incremental_remerge.pynew file mode 100644index 00000000000..871aa09758d--- /dev/null+++ b/studio/backend/tests/test_diffusion_lora_incremental_remerge.py@@ -0,0 +1,153 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A weight change re-merges only the quantised layers of the adapters it changes, bit-equal to a full re-merge."""++from __future__ import annotations++import pytest++torch = pytest.importorskip("torch")+pytest.importorskip("torchao")++import core.inference.diffusion_comfy_quant as cq # noqa: E402+from core.inference import diffusion_lora_files as lf # noqa: E402+from core.inference import diffusion_lora_quant_merge as qm # noqa: E402+from core.inference.diffusion_convrot import _install_rotation, quantize_convrot_int8_weight # noqa: E402++GROUP = 16++[email protected](autouse = True)+def _roomy_host(monkeypatch):+ from core.inference import diffusion_memory+ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 1 << 20)+ monkeypatch.setattr(lf, "_refresh_group_offload", lambda roots: None)+++class _Pipe:+ def __init__(self, net):+ self.transformer = net+ self.unloaded = 0++ @property+ def components(self):+ return {"transformer": self.transformer}++ def unload_lora_weights(self):+ self.unloaded += 1+++INCREMENTAL_ENV = "UNSLOTH_DIFFUSION_LORA_INCREMENTAL_REMERGE"+++class _TwoLayerNet(torch.nn.Module):+ """Two int8 ConvRot layers, each with its own LoKR: adapter "a" on q, "b" on k (and "c" on both)."""++ def __init__(self, shared = False):+ super().__init__()+ self.proj = torch.nn.ModuleDict()+ for i, name in enumerate(("q", "k")):+ torch.manual_seed(10 + i)+ dense = torch.randn(32, 64) * 0.05+ layer = torch.nn.Linear(64, 32, bias = False)+ codes, scale = quantize_convrot_int8_weight(dense, GROUP)+ layer.weight = torch.nn.Parameter(+ cq._int8_tensor(f"proj.{name}.weight", codes, scale, torch.bfloat16),+ requires_grad = False,+ )+ _install_rotation(layer, GROUP)+ self.proj[name] = layer+ self.pipe = _Pipe(self)+ reg = self.pipe.__dict__.setdefault(lf.KRON_ATTR, {})+ torch.manual_seed(3)+ for adapter, name in (("a", "q"), ("b", "k")) + (+ (("c", "q"), ("c", "k")) if shared else ()+ ):+ w1, w2 = torch.randn(4, 4) * 0.1, torch.randn(8, 16) * 0.1+ reg.setdefault(adapter, []).append(lf.KronAdapter(self, self.proj[name], w1, w2, 1.0))+ self.pipe.__dict__.setdefault(lf.KRON_ONLY_ATTR, set()).add(adapter)++ def codes(self):+ out = {}+ for name in ("q", "k"):+ w = self.proj[name].weight+ for k, t in qm._tensors(w, qm._weight_kind(w)).items():+ out[f"{name}.{k}"] = t.clone()+ return out+++def _count_dequant(monkeypatch):+ calls = []+ real = qm._dequant++ def counted(module, *a, **k):+ calls.append(module)+ return real(module, *a, **k)++ monkeypatch.setattr(qm, "_dequant", counted)+ return calls++[email protected]("shared", [False, True])+def test_a_weight_change_re_merges_only_the_layers_of_the_changed_adapters(monkeypatch, shared):+ monkeypatch.delenv(INCREMENTAL_ENV, raising = False)+ weights = {"a": 1.0, "b": 0.5, **({"c": 0.25} if shared else {})}+ net = _TwoLayerNet(shared)+ assert qm.merge(net.pipe, [net], weights, "cpu")+ k_layer = net.proj["k"]+ k_before = {k: t.clone() for k, t in qm._tensors(k_layer.weight, "int8").items()}+ calls = _count_dequant(monkeypatch)+ assert qm.set_weights(net.pipe, dict(weights, a = 0.3))+ assert calls == [net.proj["q"]] # b's layer is neither restored nor re-quantised+ assert all(torch.equal(t, k_before[k]) for k, t in qm._tensors(k_layer.weight, "int8").items())+ incremental = net.codes()++ # reference: a full re-merge+ monkeypatch.setenv(INCREMENTAL_ENV, "0")+ ref = _TwoLayerNet(shared)+ assert qm.merge(ref.pipe, [ref], weights, "cpu")+ assert qm.set_weights(ref.pipe, dict(weights, a = 0.3))+ full = ref.codes()+ assert incremental.keys() == full.keys()+ assert all(torch.equal(incremental[k], full[k]) for k in full)+++def test_a_change_to_a_shared_adapter_re_merges_every_layer_it_touches(monkeypatch):+ monkeypatch.delenv(INCREMENTAL_ENV, raising = False)+ net = _TwoLayerNet(shared = True)+ assert qm.merge(net.pipe, [net], {"a": 1.0, "b": 0.5, "c": 0.25}, "cpu")+ calls = _count_dequant(monkeypatch)+ assert qm.set_weights(net.pipe, {"a": 1.0, "b": 0.5}) # c omitted = 0+ assert calls == [net.proj["q"], net.proj["k"]]+++def test_the_incremental_switch_re_merges_every_layer(monkeypatch):+ net = _TwoLayerNet()+ assert qm.merge(net.pipe, [net], {"a": 1.0, "b": 0.5}, "cpu")+ monkeypatch.setenv(INCREMENTAL_ENV, "0")+ calls = _count_dequant(monkeypatch)+ assert qm.set_weights(net.pipe, {"a": 0.3, "b": 0.5})+ assert calls == [net.proj["q"], net.proj["k"]]+ assert qm.INCREMENTAL_ENV == INCREMENTAL_ENV+++def test_a_failed_incremental_re_merge_leaves_every_layer_at_its_base_codes(monkeypatch):+ monkeypatch.delenv(INCREMENTAL_ENV, raising = False)+ net = _TwoLayerNet()+ original = net.codes()+ assert qm.merge(net.pipe, [net], {"a": 1.0, "b": 0.5}, "cpu")++ def boom(*a, **k):+ raise RuntimeError("out of memory")++ monkeypatch.setattr(qm, "_requant_", boom)+ with pytest.raises(RuntimeError):+ qm.set_weights(net.pipe, {"a": 0.3, "b": 0.5})+ assert all(torch.equal(net.codes()[k], original[k]) for k in original)+ monkeypatch.undo()+ monkeypatch.delenv(INCREMENTAL_ENV, raising = False)+ # the next change merges both again from the base codes: b too, though its weight did not move+ calls = _count_dequant(monkeypatch)+ assert qm.set_weights(net.pipe, {"a": 0.3, "b": 0.5})+ assert len(calls) == 2