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: merge LoRA and LoKR adapters into ComfyUI-quantized weights (#16874)
oobabooga61f2c06f54a2
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 4d901baf443..71ea713545b 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -395,6 +395,7 @@ from .diffusion_precision import ()from .diffusion_te_prequant import supplied_component_pipe_kwargs, te_prequant_pipe_kwargsfrom . import diffusion_lora_files as lora_files+from . import diffusion_lora_quant_merge as lora_quant_mergefrom .diffusion_fast_load import _snapshot_dir as _load_snapshot_dirfrom .diffusion_fast_load import start_load_prefetch, stop_prefetch, te_precast_componentsfrom .diffusion_hosted_vae import hosted_vae_pipe_kwargs, hosted_vae_plan_files@@ -585,6 +586,30 @@ def _lora_weights_only_change(state: Any, pipe: Any, current: Any, desired: Any)return not any(getattr(getattr(h, "placement", None), "mode", None) == "group" for h in handles)+def _remerge_quant_loras(state: Any, pipe: Any, updated: tuple) -> bool:+ """Re-merges adapters merged into a quantized file's weights in place (no recompile, no recapture). False when+ nothing was merged."""+ if not lora_quant_merge.merged(pipe):+ return False+ if getattr(state, "offload_policy", OFFLOAD_NONE) != OFFLOAD_NONE:+ raise ValueError(+ "This load's LoRA adapters are merged into weights that are now offloaded, so their weights are fixed "+ "until the model is reloaded. Reload the model with the new adapter weights."+ )+ try:+ lora_quant_merge.set_weights(pipe, {n: w for (n, _p, w) in updated})+ except Exception as exc:+ # set_weights left the base weights: record that, so the next request merges again.+ pipe._unsloth_loras = tuple((n, p, 0.0) for (n, p, _w) in updated)+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)+ raise ValueError(+ f"Could not apply the new LoRA weights ({exc}); the adapters are off until the next change."+ ) from exc+ pipe._unsloth_loras = updated+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)+ return True++def _refuse_weight_change_on_streamed_graph(state: Any) -> None:"""Recapturing a block-streamed graph after a LoRA weight change fails, and the eager fallback then fails everylater generate, so such a load keeps its baked weights until a reload."""@@ -10451,11 +10476,23 @@ class DiffusionBackend:pipe._unsloth_loras = bakedpipe._unsloth_loras_baked = Truesetattr(pipe, _QUANT_FILE_LORA_BAKE_ATTR, True)- logger.info(- "diffusion.lora_bake: %d adapter(s) attached to the ComfyUI-quantized transformer "- "before the compile",- len(baked),+ # Resident loads merge them into the quantized weights; offloaded ones keep the adapter layers.+ quant_merged = (+ plan.offload_policy == OFFLOAD_NONE+ and lora_quant_merge.merge(+ pipe,+ _lora_fuse_dits(pipe),+ {n: w for (n, _p, w) in baked},+ getattr(target, "device", "cuda"),+ logger,+ ))+ if not quant_merged:+ logger.info(+ "diffusion.lora_bake: %d adapter(s) attached to the ComfyUI-quantized transformer "+ "before the compile",+ len(baked),+ )quant_forces_compile = (transformer_quant_engaged is not None or comfy_compile) and (@@ -13713,6 +13750,8 @@ class DiffusionBackend:if any(w != 0 for (_n, _p, w) in current):_refuse_weight_change_on_streamed_graph(state)disabled = tuple((n, p, 0.0) for (n, p, _w) in current)+ if _remerge_quant_loras(state, pipe, disabled):+ return# Pinned scales are tensors the compiled code and the graphs read at run time: no recompile, no recapture.if _set_pinned_lora_scales(pipe, {}):pipe._unsloth_loras = disabled@@ -13746,6 +13785,8 @@ class DiffusionBackend:if updated == current:return_refuse_weight_change_on_streamed_graph(state)+ if _remerge_quant_loras(state, pipe, updated):+ returnif _set_pinned_lora_scales(pipe, {n: w for (n, _p, w) in updated}):pipe._unsloth_loras = updatedreturndiff --git a/studio/backend/core/inference/diffusion_lora_quant_merge.py b/studio/backend/core/inference/diffusion_lora_quant_merge.pynew file mode 100644index 00000000000..f4c142b20dd--- /dev/null+++ b/studio/backend/core/inference/diffusion_lora_quant_merge.py@@ -0,0 +1,359 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Merges LoRA / LoKR adapters of a ComfyUI-quantized single file into its fp8 / int8 (ConvRot) / float weights, as+ComfyUI patches them, and removes the adapter layers. Originals are backed up on the host; a weight change restores+them into the same tensors and merges again, so compiled code and captured graphs stay valid."""++from __future__ import annotations++import os+from dataclasses import dataclass, field+from typing import Any, Optional++MERGE_ENV = "UNSLOTH_DIFFUSION_LORA_QUANT_MERGE"+_MERGED_ATTR = "_unsloth_lora_quant_merged"+_HOST_RESERVE = 8 << 30+_FP8_MAX = 448.0+_INT8_MAX = 127.0+++def enabled() -> bool:+ return (os.environ.get(MERGE_ENV) or "").strip().lower() not in ("0", "off", "false", "no")+++def merged(pipe: Any) -> bool:+ return getattr(pipe, _MERGED_ATTR, None) is not None+++@dataclass+class _Term:+ """``scale * weight * delta`` on one layer, delta = ``B @ A`` or ``kron(w1, w2)``."""++ adapter: str+ kind: str # "lora" or "lokr"+ a: Any # A (r, in) or w1+ b: Any # B (out, r) or w2+ scale: float+ rows: Optional[tuple[int, int]] = None+++@dataclass+class _Layer:+ module: Any+ group: int # ConvRot group, 0 for none+ backup: dict = field(default_factory = dict)+ terms: list = field(default_factory = list)+++def _weight_kind(weight: Any) -> Optional[str]:+ import torch++ name = type(weight).__name__+ if name in ("Float8Tensor", "Int8Tensor"):+ qdata, scale = getattr(weight, "qdata", None), getattr(weight, "scale", None)+ # Per-row symmetric (ComfyUI fp8 / int8 layout); anything else keeps its adapters.+ if (+ qdata is None+ or scale is None+ or qdata.dim() != 2+ or tuple(scale.shape) != (qdata.shape[0], 1)+ ):+ return None+ zero = getattr(weight, "zero_point", None)+ if zero is not None and bool(torch.count_nonzero(zero)):+ return None+ return "fp8" if name == "Float8Tensor" else "int8"+ if type(weight) is torch.Tensor or (+ isinstance(weight, torch.nn.Parameter) and type(weight.data) is torch.Tensor+ ):+ return "dense" if weight.is_floating_point() else None+ return None+++def _tensors(weight: Any, kind: str) -> dict:+ if kind == "dense":+ return {"data": weight.data}+ return {"qdata": weight.qdata, "scale": weight.scale}+++def _group(module: Any) -> int:+ from .diffusion_convrot import is_rotated_linear+ return int(module.convrot_groupsize) if is_rotated_linear(module) else 0+++def _mergeable_module(module: Any) -> bool:+ """A plain or ConvRot Linear whose weight is a registered Parameter: a wrapper or native twin can expose ``weight``+ as a computed view, where a write would not reach the forward."""+ import torch++ from .diffusion_convrot import is_rotated_linear++ return (+ isinstance(module, torch.nn.Linear)+ and (type(module) is torch.nn.Linear or is_rotated_linear(module))+ and isinstance(module._parameters.get("weight"), torch.nn.Parameter)+ )+++def _dequant(module: Any, kind: str, group: int, device: Any) -> Any:+ """The layer's float32 weight (ConvRot rotation undone)."""+ import torch++ weight = module.weight+ if kind == "dense":+ return weight.data.to(device = device, dtype = torch.float32)+ w = weight.qdata.to(device = device, dtype = torch.float32) * weight.scale.to(+ device = device, dtype = torch.float32+ )+ if group:+ from .diffusion_convrot import build_convrot_hadamard++ # Stored as W @ blockdiag(H).T; H is symmetric and orthogonal, so W = that @ H.+ h = build_convrot_hadamard(group, device = device, dtype = torch.float32)+ rows, cols = w.shape+ w = (w.reshape(rows, cols // group, group) @ h).reshape(rows, cols)+ return w+++def _stochastic_fp8(x: Any, dtype: Any, generator: Any) -> Any:+ """Stochastic rounding of ``x`` (float32, in range) to e4m3, as ComfyUI rounds a patched fp8 weight: round to+ nearest drops every delta below half a step."""+ import torch++ mag = x.abs()+ # e4m3: 3 mantissa bits, smallest normal exponent -6 (the subnormal step below it is 2^-9).+ exponent = torch.floor(torch.log2(mag.clamp(min = 2.0**-6))).clamp(max = 8)+ step = torch.exp2(exponent - 3)+ noise = torch.rand(x.shape, device = x.device, generator = generator)+ rounded = torch.floor(x / step + noise) * step+ return rounded.clamp(-_FP8_MAX, _FP8_MAX).to(dtype)+++def _requant_(module: Any, kind: str, group: int, w: Any, seed: int) -> None:+ """Writes ``w`` (float32) into the layer's own tensors: per-row scale recomputed, seeded stochastic rounding."""+ import torch++ weight = module.weight+ if kind == "dense":+ weight.data.copy_(w.to(weight.dtype))+ return+ if group:+ from .diffusion_convrot import build_convrot_hadamard++ h = build_convrot_hadamard(group, device = w.device, dtype = torch.float32)+ rows, cols = w.shape+ w = (w.reshape(rows, cols // group, group) @ h.T).reshape(rows, cols)+ amax = w.abs().amax(dim = -1, keepdim = True)+ top = _FP8_MAX if kind == "fp8" else _INT8_MAX+ scale = (amax / top).clamp(min = 1e-12)+ generator = torch.Generator(device = w.device)+ generator.manual_seed(seed)+ q = w / scale+ if kind == "fp8":+ codes = _stochastic_fp8(q, weight.qdata.dtype, generator)+ else:+ noise = torch.rand(q.shape, device = q.device, generator = generator)+ codes = torch.floor(q + noise).clamp(-128.0, 127.0).to(torch.int8)+ weight.qdata.copy_(codes.to(weight.qdata.device))+ weight.scale.copy_(scale.to(weight.scale))+++def _delta(term: _Term, device: Any) -> Any:+ import torch++ a = term.a.to(device = device, dtype = torch.float32)+ b = term.b.to(device = device, dtype = torch.float32)+ if term.kind == "lora":+ out = b @ a+ else:+ out = torch.kron(a, b)+ if term.rows is not None:+ out = out[term.rows[0] : term.rows[1]]+ return out+++def _peft_terms(layer: Any) -> Optional[list]:+ """The active adapters of a PEFT Linear LoRA layer at weight 1, or None when one cannot merge exactly."""+ import torch++ base = layer.get_base_layer()+ if not isinstance(base, torch.nn.Linear) or getattr(layer, "fan_in_fan_out", False):+ return None+ out = []+ for adapter in getattr(layer, "active_adapters", None) or ():+ if adapter not in getattr(layer, "lora_A", {}):+ continue+ if (getattr(layer, "use_dora", {}) or {}).get(adapter) or (+ getattr(layer, "lora_bias", {}) or {}+ ).get(adapter):+ return None+ a = layer.lora_A[adapter].weight.detach()+ b = layer.lora_B[adapter].weight.detach()+ # set_adapter_weights ran at weight 1 before this read: scaling is the adapter's own alpha / r.+ out.append(_Term(adapter, "lora", a.cpu(), b.cpu(), float(layer.scaling[adapter])))+ return out+++def plan(pipe: Any, denoisers: list) -> Optional[list]:+ """Every adapted layer of ``denoisers`` with its adapter terms, or None when anything cannot merge: an adapter+ layer outside the denoisers, a non-Linear or DoRA layer, or a weight format with no requantizer here."""+ from . import diffusion_lora_files as lora_files++ ids = {id(m) for d in denoisers for m in d.modules()}+ layers: dict[int, _Layer] = {}+ for component in (getattr(pipe, "components", None) or {}).values():+ modules = getattr(component, "modules", None)+ if not callable(modules):+ continue+ for m in modules():+ if hasattr(m, "lora_A") and callable(getattr(m, "get_base_layer", None)):+ if id(m) not in ids:+ return None # a text encoder carries the adapter too+ terms = _peft_terms(m)+ if terms is None:+ return None+ if not terms:+ continue+ base = m.get_base_layer()+ entry = layers.setdefault(id(base), _Layer(base, _group(base)))+ entry.terms.extend(terms)+ for adapter_name, adapters in pipe.__dict__.get(lora_files.KRON_ATTR, {}).items():+ for adapter in adapters:+ base = adapter.wrapper.get_base_layer()+ if id(base) not in ids:+ return None+ w1 = getattr(adapter.wrapper, adapter.prefix + "_w1").detach()+ w2 = getattr(adapter.wrapper, adapter.prefix + "_w2").detach()+ rows = next((r for p, r in adapter.wrapper.slots if p == adapter.prefix), None)+ entry = layers.setdefault(id(base), _Layer(base, _group(base)))+ entry.terms.append(+ _Term(adapter_name, "lokr", w1.cpu(), w2.cpu(), float(adapter.alpha_scale), rows)+ )+ if not layers:+ return None+ for entry in layers.values():+ if not _mergeable_module(entry.module) or _weight_kind(entry.module.weight) is None:+ return None+ return list(layers.values())+++def _host_room(layers: list) -> bool:+ """Room for the backups in usable host RAM (capped by an enforcing cgroup), with a reserve left free."""+ nbytes = sum(+ t.numel() * t.element_size()+ for e in layers+ for t in _tensors(e.module.weight, _weight_kind(e.module.weight)).values()+ )+ from .diffusion_memory import _available_system_memory_mib++ available = _available_system_memory_mib()+ if available is None:+ return False+ return (int(available) << 20) - nbytes >= _HOST_RESERVE+++def _apply(layers: list, weights: dict, device: Any) -> None:+ import torch++ # No TF32: the same weights must merge to the same codes before and after a speed profile engages.+ tf32 = torch.backends.cuda.matmul.allow_tf32+ torch.backends.cuda.matmul.allow_tf32 = False+ try:+ with torch.no_grad():+ for index, entry in enumerate(layers):+ module = entry.module+ kind = _weight_kind(module.weight)+ live = [t for t in entry.terms if weights.get(t.adapter, 0.0)]+ if not live:+ continue+ w = _dequant(module, kind, entry.group, device)+ for term in live:+ w.add_(_delta(term, device), alpha = term.scale * float(weights[term.adapter]))+ _requant_(module, kind, entry.group, w, seed = index)+ del w+ finally:+ torch.backends.cuda.matmul.allow_tf32 = tf32+++def _restore(layers: list) -> None:+ import torch+ with torch.no_grad():+ for entry in layers:+ kind = _weight_kind(entry.module.weight)+ for key, live in _tensors(entry.module.weight, kind).items():+ live.copy_(entry.backup[key])+++def merge(+ pipe: Any,+ denoisers: list,+ weights: dict,+ device: Any,+ logger: Any = None,+) -> bool:+ """Merges the attached adapters at ``weights`` (name -> weight) and removes the adapter layers. False, with the+ adapters left attached, when they cannot all be merged or the host has no room for the backups."""+ if not enabled() or merged(pipe):+ return False+ from . import diffusion_lora_files as lora_files++ names = list(weights)+ try:+ lora_files.set_adapter_weights(pipe, names, [1.0] * len(names))+ layers = plan(pipe, denoisers)+ finally:+ lora_files.set_adapter_weights(pipe, names, [weights[n] for n in names])+ if layers is None or not _host_room(layers):+ return False+ try:+ for entry in layers:+ kind = _weight_kind(entry.module.weight)+ entry.backup = {+ k: t.detach().to("cpu", copy = True)+ for k, t in _tensors(entry.module.weight, kind).items()+ }+ _apply(layers, weights, device)+ except Exception as exc: # noqa: BLE001 - put the weights back, keep the adapters+ # A failed backup allocation leaves later layers without one, and their weights untouched.+ _restore([e for e in layers if e.backup])+ for entry in layers:+ entry.backup = {}+ if logger is not None:+ logger.warning(+ "diffusion.lora_merge: merge failed, keeping the adapter layers: %s", exc+ )+ return False+ lora_files.unload_adapters(pipe)+ setattr(pipe, _MERGED_ATTR, {"layers": layers, "weights": dict(weights), "device": device})+ if logger is not None:+ logger.info(+ "diffusion.lora_merge: %d adapter(s) merged into %d quantized layer(s); the adapter layers are removed",+ len(names),+ len(layers),+ )+ return True+++def set_weights(pipe: Any, weights: dict) -> bool:+ """Re-merges at new weights (an omitted name is 0) in place; False when nothing was merged."""+ state = getattr(pipe, _MERGED_ATTR, None)+ if state is None:+ return False+ layers = state["layers"]+ device = state["device"]+ for entry in layers:+ live = next(iter(_tensors(entry.module.weight, _weight_kind(entry.module.weight)).values()))+ if live.device.type != "meta":+ device = live.device+ break+ _restore(layers)+ try:+ _apply(layers, weights, device)+ except Exception:+ # Never leave half the layers merged: the base weights, then the error.+ _restore(layers)+ state["weights"] = {}+ raise+ state["weights"] = dict(weights)+ return Truediff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 9464c5e0134..2da47de952a 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -2059,6 +2059,13 @@ def _fuse_qkv(pipe: Any, logger: Any) -> bool:"diffusion.speed: fuse_qkv skipped (native quantised projections stay unfused)")return False+ from . import diffusion_lora_quant_merge as lora_quant_merge++ # A fused to_qkv copy would miss in-place re-merges of merged adapter weights.+ if lora_quant_merge.merged(pipe):+ if logger is not None:+ logger.info("diffusion.speed: fuse_qkv skipped (merged LoRA weights change in place)")+ return False# Prefer pipe-level fuse (covers every component); else fuse each DiT so dual-DiT families fuse both.fn = getattr(pipe, "fuse_qkv_projections", None)if callable(fn):diff --git a/studio/backend/tests/test_diffusion_lora.py b/studio/backend/tests/test_diffusion_lora.pyindex c4c03edd0f8..5dce118c98e 100644--- a/studio/backend/tests/test_diffusion_lora.py+++ b/studio/backend/tests/test_diffusion_lora.py@@ -1136,3 +1136,150 @@ def test_a_lokr_only_weight_change_keeps_the_cuda_graphs(monkeypatch, tmp_path,assert float(getattr(block["q"], adapter.prefix + "_scale")) == 0.0assert resets == []assert invalidated+++def _roomy_host(monkeypatch):+ from core.inference import diffusion_lora_files, diffusion_memory+ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 1 << 20)+ # No group offloading on a resident merge; the refresh imports diffusers, absent on CPU CI.+ monkeypatch.setattr(diffusion_lora_files, "_refresh_group_offload", lambda roots: None)+++def test_merged_quant_file_adapters_change_weight_in_place_with_no_recompile(monkeypatch):+ """A quantized single file's adapters merged into its weights at load: a weight change or switching the adapter off+ re-merges into the same tensors, so a compiled model reads the new weights with no recompile and no dropped graph,+ and weight 0 is the base weights exactly."""+ import threading++ import torch+ from torch._dynamo.testing import CompileCounter++ from core.inference import diffusion as diff+ from core.inference import diffusion_lora_files as lf+ from core.inference import diffusion_lora_quant_merge as qm++ monkeypatch.setattr(+ dl,+ "resolve_specs",+ lambda specs, **_: [+ dl.ResolvedLora(i, dl.sanitize_alias(i), f"/{i}.safetensors", "safetensors", w)+ for i, w in specs+ ],+ )+ resets = []+ monkeypatch.setattr(diff.cuda_graph, "reset_all", lambda handles: resets.append(handles))+ torch.manual_seed(0)+ net = torch.nn.Sequential(torch.nn.Linear(16, 8, bias = False)).requires_grad_(False)+ base = net[0].weight.detach().clone()++ class _Pipe:+ transformer = net+ components = {"transformer": net}++ def unload_lora_weights(self):+ pass++ pipe = _Pipe()+ w1, w2 = torch.randn(2, 2) * 0.1, torch.randn(4, 8) * 0.1+ pipe.__dict__[lf.KRON_ATTR] = {"a": [lf.KronAdapter(net, net[0], w1, w2, 1.0)]}+ pipe.__dict__[lf.KRON_ONLY_ATTR] = {"a"}+ b = _backend()+ state = _fake_state(pipe, quant = "int8")+ state.cuda_graphs = ()+ pipe._unsloth_loras = b._resolve_lora_set([("a", 1.0)], family = "flux.1", hf_token = None)+ pipe._unsloth_loras_baked = True+ _roomy_host(monkeypatch)+ assert qm.merge(pipe, [net], {"a": 1.0}, "cpu")+ assert type(net[0]) is torch.nn.Linear++ x = torch.randn(3, 16)+ torch._dynamo.reset()+ counter = CompileCounter()+ compiled = torch.compile(net, backend = counter)+ with torch.no_grad():+ torch.testing.assert_close(compiled(x), x @ (base + torch.kron(w1, w2)).T)+ for loras, w in (([("a", 0.4)], 0.4), ([], 0.0), ([("a", 1.0)], 1.0)):+ b._apply_loras(state, loras, threading.Event())+ with torch.no_grad():+ torch.testing.assert_close(compiled(x), x @ (base + w * torch.kron(w1, w2)).T)+ assert [wt for (_n, _p, wt) in pipe._unsloth_loras] == [w]+ if not w:+ assert torch.equal(net[0].weight, base)+ assert counter.frame_count == 1+ assert resets == []+ torch._dynamo.reset()+++def _merged_lokr_pipe(monkeypatch):+ from core.inference import diffusion_lora_files as lf+ from core.inference import diffusion_lora_quant_merge as qm++ monkeypatch.setattr(+ dl,+ "resolve_specs",+ lambda specs, **_: [+ dl.ResolvedLora(i, dl.sanitize_alias(i), f"/{i}.safetensors", "safetensors", w)+ for i, w in specs+ ],+ )+ torch = pytest.importorskip("torch")+ torch.manual_seed(0)+ net = torch.nn.Sequential(torch.nn.Linear(16, 8, bias = False)).requires_grad_(False)++ class _Pipe:+ transformer = net+ components = {"transformer": net}++ def unload_lora_weights(self):+ pass++ pipe = _Pipe()+ pipe.__dict__[lf.KRON_ATTR] = {+ "a": [lf.KronAdapter(net, net[0], torch.randn(2, 2), torch.randn(4, 8), 1.0)]+ }+ pipe.__dict__[lf.KRON_ONLY_ATTR] = {"a"}+ b = _backend()+ state = _fake_state(pipe, quant = "int8")+ state.cuda_graphs = ()+ pipe._unsloth_loras = b._resolve_lora_set([("a", 1.0)], family = "flux.1", hf_token = None)+ pipe._unsloth_loras_baked = True+ _roomy_host(monkeypatch)+ assert qm.merge(pipe, [net], {"a": 1.0}, "cpu")+ return b, state, pipe, net+++def test_a_failed_remerge_records_the_adapters_as_off(monkeypatch):+ """A re-merge that fails (an OOM) leaves the base weights: the recorded weights say so, the CFG replica is dropped,+ and asking for the old weight again merges again instead of matching a stale record."""+ import threading++ from core.inference import diffusion as diff+ from core.inference import diffusion_lora_quant_merge as qm++ b, state, pipe, net = _merged_lokr_pipe(monkeypatch)+ base = qm.set_weights(pipe, {}) and net[0].weight.detach().clone()+ qm.set_weights(pipe, {"a": 1.0})+ invalidated = []+ monkeypatch.setattr(diff, "invalidate_cfg_replica", lambda *a, **k: invalidated.append(a[1]))+ real = qm._requant_+ monkeypatch.setattr(+ qm, "_requant_", lambda *a, **k: (_ for _ in ()).throw(RuntimeError("CUDA out of memory"))+ )+ with pytest.raises(ValueError, match = "Could not apply the new LoRA weights"):+ b._apply_loras(state, [("a", 0.5)], threading.Event())+ assert [w for (_n, _p, w) in pipe._unsloth_loras] == [0.0]+ assert invalidated and __import__("torch").equal(net[0].weight, base)+ monkeypatch.setattr(qm, "_requant_", real)+ b._apply_loras(state, [("a", 1.0)], threading.Event())+ assert [w for (_n, _p, w) in pipe._unsloth_loras] == [1.0]+ assert not __import__("torch").equal(net[0].weight, base)+++def test_merged_adapters_on_an_offloaded_load_need_a_reload(monkeypatch):+ import threading++ b, state, pipe, _net = _merged_lokr_pipe(monkeypatch)+ state.offload_policy = "group"+ with pytest.raises(ValueError, match = "Reload the model with the new adapter weights"):+ b._apply_loras(state, [("a", 0.5)], threading.Event())+ assert [w for (_n, _p, w) in pipe._unsloth_loras] == [1.0]diff --git a/studio/backend/tests/test_diffusion_lora_quant_merge.py b/studio/backend/tests/test_diffusion_lora_quant_merge.pynew file mode 100644index 00000000000..32459887e1d--- /dev/null+++ b/studio/backend/tests/test_diffusion_lora_quant_merge.py@@ -0,0 +1,289 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Adapters merged into a ComfyUI-quantized file's weights: int8 ConvRot, fp8 per row / per tensor, dense."""++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):+ # The host's own free RAM can sit below the backup reserve (7 GB CI runners).+ from core.inference import diffusion_memory+ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 1 << 20)+ # Resident merges have no group offloading to re-apply; the refresh imports diffusers, absent on CPU CI.+ monkeypatch.setattr(lf, "_refresh_group_offload", lambda roots: None)+++class _Net(torch.nn.Module):+ def __init__(+ self,+ kind: str,+ out_features = 32,+ in_features = 64,+ ):+ super().__init__()+ torch.manual_seed(0)+ dense = torch.randn(out_features, in_features) * 0.05+ self.dense = dense+ self.proj = torch.nn.ModuleDict(+ {"q": torch.nn.Linear(in_features, out_features, bias = False)}+ )+ layer = self.proj["q"]+ if kind == "int8":+ codes, scale = quantize_convrot_int8_weight(dense, GROUP)+ weight = cq._int8_tensor("proj.q.weight", codes, scale, torch.bfloat16)+ _install_rotation(layer, GROUP)+ elif kind == "fp8":+ scale = dense.abs().amax() / 448.0+ codes = (dense / scale).to(torch.float8_e4m3fn)+ weight = cq._fp8_tensor("proj.q.weight", codes, scale.reshape(()), torch.bfloat16)+ else:+ weight = dense.to(torch.bfloat16)+ layer.weight = torch.nn.Parameter(weight, requires_grad = False)+++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+++def _lokr(+ net,+ pipe,+ name = "k",+ rows = None,+):+ torch.manual_seed(1)+ w1, w2 = torch.randn(4, 4) * 0.1, torch.randn(8, 16) * 0.1+ adapter = lf.KronAdapter(net, net.proj["q"], w1, w2, 1.0, rows)+ pipe.__dict__.setdefault(lf.KRON_ATTR, {})[name] = [adapter]+ pipe.__dict__.setdefault(lf.KRON_ONLY_ATTR, set()).add(name)+ return w1, w2+++def _weight(net):+ return qm._dequant(+ net.proj["q"], qm._weight_kind(net.proj["q"].weight), qm._group(net.proj["q"]), "cpu"+ )+++def _codes(net):+ w = net.proj["q"].weight+ kind = qm._weight_kind(w)+ return {k: t.clone() for k, t in qm._tensors(w, kind).items()}++[email protected]("kind", ["int8", "fp8", "dense"])+def test_a_lokr_merges_into_the_weight_and_its_layer_is_removed(kind):+ net = _Net(kind)+ pipe = _Pipe(net)+ base = _weight(net)+ w1, w2 = _lokr(net, pipe)+ assert qm.merge(pipe, [net], {"k": 0.7}, "cpu")+ assert isinstance(net.proj["q"], torch.nn.Linear) and not isinstance(+ net.proj["q"], lf.kron_linear_class()+ )+ assert not pipe.__dict__.get(lf.KRON_ATTR) and pipe.unloaded == 1+ want = base + 0.7 * torch.kron(w1, w2)+ assert (_weight(net) - want).norm() / want.norm() < {"int8": 0.02, "fp8": 0.05, "dense": 0.01}[+ kind+ ]++[email protected]("kind", ["int8", "fp8", "dense"])+def test_weight_zero_restores_the_original_codes_and_a_weight_merges_the_same_twice(kind):+ net = _Net(kind)+ pipe = _Pipe(net)+ original = _codes(net)+ _lokr(net, pipe)+ assert qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ once = _codes(net)+ assert any(not torch.equal(once[k], original[k]) for k in once)+ assert qm.set_weights(pipe, {})+ assert all(torch.equal(_codes(net)[k], original[k]) for k in original)+ assert qm.set_weights(pipe, {"k": 1.0})+ assert all(torch.equal(_codes(net)[k], once[k]) for k in once)+++def test_the_merge_keeps_each_layers_tensors_in_place():+ """Compiled code and captured graphs read the qdata / scale tensors: a weight change must write into them."""+ net = _Net("int8")+ pipe = _Pipe(net)+ _lokr(net, pipe)+ qdata, scale = net.proj["q"].weight.qdata, net.proj["q"].weight.scale+ ptrs = (qdata.data_ptr(), scale.data_ptr())+ assert qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ assert qm.set_weights(pipe, {"k": 0.3})+ w = net.proj["q"].weight+ assert w.qdata is qdata and w.scale is scale and (qdata.data_ptr(), scale.data_ptr()) == ptrs+++def test_a_row_slice_lokr_merges_only_its_rows():+ """MOSS-Image's fused qkv LoKR: each of q / k / v takes its own rows of the Kronecker product."""+ net = _Net("dense", out_features = 16)+ pipe = _Pipe(net)+ base = _weight(net)+ w1, w2 = _lokr(net, pipe, rows = (16, 32))+ assert qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ want = base + torch.kron(w1, w2)[16:32]+ assert (_weight(net) - want).abs().max() <= want.abs().max() / 128+++def test_an_adapter_outside_the_denoisers_keeps_the_adapter_layers():+ net = _Net("int8")+ pipe = _Pipe(net)+ _lokr(net, pipe)+ other = torch.nn.Linear(4, 4)+ assert not qm.merge(pipe, [other], {"k": 1.0}, "cpu")+ assert isinstance(net.proj["q"], lf.kron_linear_class())+++def test_an_unsupported_weight_format_keeps_the_adapter_layers():+ net = _Net("dense")+ pipe = _Pipe(net)+ _lokr(net, pipe)+ net.proj["q"].get_base_layer().weight = torch.nn.Parameter(+ torch.zeros(32, 64, dtype = torch.int32), requires_grad = False+ )+ assert not qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ assert isinstance(net.proj["q"], lf.kron_linear_class())+++def test_the_kill_switch_keeps_the_adapter_layers(monkeypatch):+ monkeypatch.setenv(qm.MERGE_ENV, "0")+ net = _Net("int8")+ pipe = _Pipe(net)+ _lokr(net, pipe)+ assert not qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ assert not qm.set_weights(pipe, {"k": 1.0})+++def test_a_peft_lora_merges_at_its_alpha_scale():+ peft = pytest.importorskip("peft")+ net = _Net("int8")+ base = _weight(net)++ class _PeftPipe(_Pipe):+ def set_adapters(+ self,+ names,+ adapter_weights = None,+ ):+ for m in net.modules():+ if hasattr(m, "set_scale"):+ for n, w in zip(names, adapter_weights):+ m.set_scale(n, w)++ def unload_lora_weights(self):+ super().unload_lora_weights()+ from peft.tuners.tuners_utils import BaseTunerLayer+ for parent in list(net.modules()):+ for attr, child in list(parent.named_children()):+ if isinstance(child, BaseTunerLayer):+ setattr(parent, attr, child.get_base_layer())++ pipe = _PeftPipe(net)+ peft.inject_adapter_in_model(+ peft.LoraConfig(r = 2, lora_alpha = 4, target_modules = ["q"], init_lora_weights = False), net, "l"+ )+ layer = net.proj["q"]+ a, b = layer.lora_A["l"].weight.detach().clone(), layer.lora_B["l"].weight.detach().clone()+ assert qm.merge(pipe, [net], {"l": 0.5}, "cpu")+ assert not hasattr(net.proj["q"], "lora_A")+ want = base + 0.5 * 2.0 * (b @ a)+ assert (_weight(net) - want).norm() / want.norm() < 0.02+++def test_a_wrapped_linear_keeps_its_adapter_layers():+ """A wrapper exposing ``weight`` as a computed view: a write there would never reach the forward."""+ net = _Net("dense")+ pipe = _Pipe(net)+ inner = net.proj["q"]++ class _Wrapper(torch.nn.Module):+ def __init__(self, layer):+ super().__init__()+ self.layer = layer++ @property+ def weight(self):+ return self.layer.weight.detach().clone()++ def forward(self, x):+ return self.layer(x)++ net.proj["q"] = _Wrapper(inner)+ adapter = lf.KronAdapter(net, net.proj["q"], torch.randn(4, 4), torch.randn(8, 16), 1.0)+ pipe.__dict__[lf.KRON_ATTR] = {"k": [adapter]}+ assert qm.plan(pipe, [net]) is None+++def test_no_room_for_the_backups_keeps_the_adapter_layers(monkeypatch):+ from core.inference import diffusion_memory++ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 1024)+ net = _Net("int8")+ pipe = _Pipe(net)+ _lokr(net, pipe)+ assert not qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ assert isinstance(net.proj["q"], lf.kron_linear_class())+++def test_max_speed_never_fuses_qkv_over_merged_weights():+ """A fused to_qkv is a copy of to_q / to_k / to_v: a weight change re-merges those, and the copy would keep the old+ adapter weight (at weight 0 the adapter would still run)."""+ from core.inference import diffusion_speed as ds++ net = _Net("int8")+ calls = []++ class _FusingPipe(_Pipe):+ def fuse_qkv_projections(self):+ calls.append("pipe")++ net.fuse_qkv_projections = lambda: calls.append("dit")+ pipe = _FusingPipe(net)+ _lokr(net, pipe)+ assert qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ assert ds._fuse_qkv(pipe, None) is False and calls == []+++def test_a_failed_backup_allocation_keeps_the_adapter_layers(monkeypatch):+ net = _Net("int8")+ pipe = _Pipe(net)+ original = _codes(net)+ _lokr(net, pipe)+ real_to = torch.Tensor.to++ def to(self, *args, **kwargs):+ if args and args[0] == "cpu" and kwargs.get("copy"):+ raise RuntimeError("DefaultCPUAllocator: not enough memory")+ return real_to(self, *args, **kwargs)++ monkeypatch.setattr(torch.Tensor, "to", to)+ assert not qm.merge(pipe, [net], {"k": 1.0}, "cpu")+ monkeypatch.undo()+ assert isinstance(net.proj["q"], lf.kron_linear_class()) and pipe.unloaded == 0+ assert all(torch.equal(_codes(net)[k], original[k]) for k in original)+ assert not qm.merged(pipe)