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 diffusion: change baked LoRA subsets and weights without recompiling or recapturing (#14692)
Daniel Han38a3a34d3905
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex d694ba57b65..6a3b7e8c0ee 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -790,6 +790,124 @@ def _baked_lora_names(pipe: Any) -> list:return names+# ``(module, adapter, base)`` for every baked LoRA scale held as a device tensor; ``base`` is lora_alpha / r.+_PINNED_LORA_SCALES_ATTR = "_unsloth_pinned_lora_scales"+# ``(module, adapter)`` for the baked LoRA layers OUTSIDE the denoisers (a text encoder carrying the same file's+# adapter): their scales stay floats and are set the way set_adapters would set them.+_PINNED_LORA_SIDE_ATTR = "_unsloth_pinned_lora_side"+++def _side_lora_layers(pipe: Any) -> list:+ """``(module, adapter)`` for every PEFT LoRA layer on a pipeline component that is not a denoiser."""+ import torch++ skip = {id(m) for _a, m in denoiser_modules(pipe)}+ components = getattr(pipe, "components", None)+ if not isinstance(components, dict):+ components = dict(vars(pipe))+ out = []+ seen: set[int] = set()+ for value in components.values():+ if not isinstance(value, torch.nn.Module) or id(value) in skip or id(value) in seen:+ continue+ seen.add(id(value))+ for module in value.modules():+ scaling = module.__dict__.get("scaling")+ lora_b = getattr(module, "lora_B", None)+ if not isinstance(scaling, dict) or lora_b is None or not hasattr(module, "set_scale"):+ continue+ # Every scaled adapter, an Embedding's (factors in lora_embedding_A/B, not lora_B) included.+ out.extend((module, adapter) for adapter in scaling)+ return out+++def _pin_baked_lora_scales(pipe: Any, target_device: Any) -> int:+ """Hold each baked adapter's PEFT scale as a 0-d tensor on its LoRA weights' device, so a later weight change or+ subset switch is an in-place write instead of a new Python float.++ PEFT keeps ``scaling[adapter]`` as a float and multiplies by it inside the LoRA forward. torch.compile guards on+ that float (``self.scaling['b'] == 1.0``), and a CUDA graph records it as a kernel argument, so every new weight+ vector recompiled and recaptured. The adapters and their shapes never change on a baked load, only the scale,+ so a tensor read at run time serves every selection with the first prompt's graphs. Call before compile and+ graph capture. Skipped (floats kept, the reset path stays) on an offloaded denoiser, where the LoRA weights move+ off the scale's device, and when any LoRA weight is not yet on the target device type. Returns the count."""+ if not getattr(pipe, "_unsloth_loras_baked", False) or getattr(+ pipe, _PINNED_LORA_SCALES_ATTR, None+ ):+ return 0+ if _denoiser_hooked(pipe):+ return 0+ import math++ import torch++ # The type off the string form ("cuda:0" -> "cuda"), as torch.device(...).type gives, without a torch.device.+ want = str(target_device).split(":", 1)[0]+ found = []+ for _attr, root in denoiser_modules(pipe):+ modules = getattr(root, "modules", None)+ if not callable(modules):+ continue+ for module in modules():+ scaling = module.__dict__.get("scaling")+ lora_b = getattr(module, "lora_B", None)+ if not isinstance(scaling, dict) or lora_b is None:+ continue+ for adapter, value in scaling.items():+ if isinstance(value, torch.Tensor):+ continue+ if adapter not in lora_b:+ # A scale with no lora_B entry (a PEFT Embedding keeps lora_embedding_A/B): pinning the rest+ # would skip set_adapters and leave this one at its bake-time weight, so keep the float path.+ return 0+ weight = lora_b[adapter].weight+ if weight.device.type != want:+ return 0+ r = module.r[adapter]+ alpha = module.lora_alpha[adapter]+ rslora = bool(getattr(module, "use_rslora", {}).get(adapter, False))+ base = alpha / (math.sqrt(r) if rslora else r)+ found.append((module, adapter, base, float(value), weight.device))+ if not found:+ return 0+ pinned = []+ # A normal tensor even when the load runs under inference_mode: an inference tensor refuses the later fill_.+ with torch.inference_mode(False):+ for module, adapter, base, value, device in found:+ module.scaling[adapter] = torch.tensor(value, dtype = torch.float32, device = device)+ pinned.append((module, adapter, base))+ setattr(pipe, _PINNED_LORA_SIDE_ATTR, tuple(_side_lora_layers(pipe)))+ setattr(pipe, _PINNED_LORA_SCALES_ATTR, tuple(pinned))+ return len(pinned)+++def _set_pinned_lora_scales(pipe: Any, weights: dict) -> bool:+ """Write ``weights`` (adapter name -> weight, omitted = 0) into the pinned scale tensors in place. False, with the+ pin dropped, when there is none or it no longer holds (something rewrote a scale as a float or moved the+ weights): the caller then takes the set_adapters + graph reset path."""+ pinned = getattr(pipe, _PINNED_LORA_SCALES_ATTR, None)+ if not pinned:+ return False+ import torch++ for module, adapter, _base in pinned:+ value = module.scaling.get(adapter)+ if (+ not isinstance(value, torch.Tensor)+ or value.device != module.lora_B[adapter].weight.device+ ):+ setattr(pipe, _PINNED_LORA_SCALES_ATTR, None)+ return False+ with torch.no_grad():+ for module, adapter, base in pinned:+ module.scaling[adapter].fill_(float(weights.get(adapter, 0.0)) * base)+ # The same adapter on a text encoder (SD / SDXL / SD3 / FLUX files can carry one): set_adapters is skipped, so+ # set its scale here, or prompt encoding keeps the bake-time weight while the marker names the new one.+ for module, adapter in getattr(pipe, _PINNED_LORA_SIDE_ATTR, None) or ():+ module.set_scale(adapter, float(weights.get(adapter, 0.0)))+ return True++def resolve_local_single_file(model_path: str) -> Optional[str]:"""The sole single-file checkpoint basename in a local ``model_path`` directory that is NOT adiffusers pipeline (no ``model_index.json`` or FLUX.3 ``modular_model_index.json``) and holds exactly one ``.safetensors`` file, else@@ -9803,6 +9921,14 @@ class DiffusionBackend:)# streams the whole-resident denoiser back to the flat room while the encoders runinstall_encode_release(pipe, plan, logger)+ # Placed, not yet compiled or captured: a later LoRA weight / subset change then writes in place.+ pinned_scales = _pin_baked_lora_scales(pipe, target.device)+ if pinned_scales:+ logger.info(+ "diffusion.lora_bake: %d adapter scale(s) held as device tensors (weight changes "+ "keep the compiled graphs)",+ pinned_scales,+ )# the speed layer saw only the plan; placement may have pinned every denoiser group sinceif (denoisers_pinned_resident(pipe)@@ -11980,8 +12106,13 @@ class DiffusionBackend:names = [n for (n, _p, _w) in current]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)+ # 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+ returnpipe.set_adapters(names, adapter_weights = [0.0] * len(names))- pipe._unsloth_loras = tuple((n, p, 0.0) for (n, p, _w) in current)+ pipe._unsloth_loras = disabled# Adapter scales are Python values read inside the LoRA forward, so a graph bakes them in.cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))return@@ -12008,6 +12139,9 @@ class DiffusionBackend:if updated == current:return_refuse_weight_change_on_streamed_graph(state)+ if _set_pinned_lora_scales(pipe, {n: w for (n, _p, w) in updated}):+ pipe._unsloth_loras = updated+ returnpipe.set_adapters([n for (n, _p, _w) in updated],adapter_weights = [w for (_n, _p, w) in updated],diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex c4828900b03..f4b38589698 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -1306,6 +1306,15 @@ def build_replica(module: Any, device: Any) -> Any:guard = module.__dict__.get("_unsloth_compile_guard")if guard is not None:memo[id(guard)] = _DROP+ # A baked LoRA's scale pinned as a 0-d device tensor (diffusion._pin_baked_lora_scales) lives in a plain dict,+ # not a buffer: the copy needs its own on ``device``.+ for sub in module.modules():+ scaling = sub.__dict__.get("scaling")+ if isinstance(scaling, dict):+ for value in scaling.values():+ if isinstance(value, torch.Tensor) and id(value) not in memo:+ memo[id(value)] = value.detach().to(device)+ keep.append(value)memo[id(memo)] = keepreplica = copy.deepcopy(module, memo)router = module.__dict__.get("forward")@@ -1399,6 +1408,12 @@ def weights_fingerprint(module: Any) -> int:for name, sub in module.named_modules():for attr in _ADAPTER_ATTRS:value = sub.__dict__.get(attr)+ if isinstance(value, dict):+ # A pinned scale tensor: identity + version (an in-place write bumps it), no device read per call.+ value = {+ k: (id(v), v._version) if hasattr(v, "_version") else v+ for k, v in value.items()+ }if value is not None and not callable(value):parts.append((name, attr, repr(value)))return hash(tuple(parts))diff --git a/studio/backend/tests/test_diffusion_lora.py b/studio/backend/tests/test_diffusion_lora.pyindex f9ed5a5ecaa..5b1edba809c 100644--- a/studio/backend/tests/test_diffusion_lora.py+++ b/studio/backend/tests/test_diffusion_lora.py@@ -497,3 +497,271 @@ def test_scan_local_tolerates_bad_sidecar(tmp_path, monkeypatch):monkeypatch.setattr(dl, "loras_dir", lambda: d)entry = next(e for e in dl.list_loras() if e.id == "a")assert entry.families == () and entry.weight_default == 1.0+++def _peft_add_adapter(layer, name, config):+ # PEFT >= 0.19 takes ``config``; 0.18 takes every option positionally (``use_rslora`` required). Pass by keyword+ # what the installed signature names, read off ``config``, so the helper holds across PEFT 0.18.0 -> 0.20.0.+ import inspect++ known = {"r": config.r, "lora_alpha": config.lora_alpha, "config": config}+ kwargs = {}+ for param in list(inspect.signature(layer.update_layer).parameters.values())[1:]:+ if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):+ continue+ if param.name in known:+ kwargs[param.name] = known[param.name]+ elif hasattr(config, param.name):+ kwargs[param.name] = getattr(config, param.name)+ layer.update_layer(name, **kwargs)+++def _peft_two_adapter_pipe():+ # A real PEFT LoRA Linear carrying two baked adapters, behind a pipe whose set_adapters does what diffusers does.+ import torch+ from peft import LoraConfig+ from peft.tuners.lora.layer import Linear++ torch.manual_seed(0)+ config = LoraConfig(r = 2, lora_alpha = 4, lora_dropout = 0.0, init_lora_weights = False)+ layer = Linear(+ torch.nn.Linear(8, 8, bias = False),+ "a",+ config = config,+ r = 2,+ lora_alpha = 4,+ init_lora_weights = False,+ )+ _peft_add_adapter(layer, "b", config)+ layer.set_adapter(["a", "b"])+ layer.eval()++ class _Pipe:+ transformer = torch.nn.Sequential(layer)++ def set_adapters(+ self,+ names,+ adapter_weights = None,+ ):+ layer.set_adapter(list(names))+ for name, weight in zip(names, adapter_weights):+ layer.set_scale(name, weight)++ return _Pipe(), layer+++def test_baked_lora_subset_and_weight_changes_keep_compiled_graphs(monkeypatch):+ # A baked int8/fp8 load keeps its adapters, so a subset / weight change only moves scales. PEFT's float scale is+ # a Dynamo guard (self.scaling['b'] == 1.0) and a CUDA-graph kernel argument: each change recompiled and dropped+ # every captured graph. Pinned as device tensors, the first prompt's graph serves every selection.+ import threading++ import torch+ from torch._dynamo.testing import CompileCounter++ from core.inference import diffusion as diff++ 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))+ b = _backend()+ pipe, layer = _peft_two_adapter_pipe()+ state = _fake_state(pipe, quant = "int8")+ state.cuda_graphs = ()+ pipe._unsloth_loras = b._resolve_lora_set(+ [("a", 1.0), ("b", 1.0)], family = "flux.1", hf_token = None+ )+ pipe._unsloth_loras_baked = True+ # What the load does once the denoiser is placed (absent before the fix: the floats stay).+ getattr(diff, "_pin_baked_lora_scales", lambda *_: 0)(pipe, "cpu")++ x = torch.randn(3, 8)++ def expected(wa, wb):+ with torch.no_grad():+ out = layer.base_layer(x)+ for name, w in (("a", wa), ("b", wb)):+ out = out + layer.lora_B[name](layer.lora_A[name](x)) * (w * 4 / 2)+ return out++ torch._dynamo.reset()+ counter = CompileCounter()+ compiled = torch.compile(pipe.transformer, backend = counter)+ with torch.no_grad():+ torch.testing.assert_close(compiled(x), expected(1.0, 1.0))+ compiled(x)+ assert counter.frame_count == 1++ for loras, wa, wb in (+ ([("a", 1.0)], 1.0, 0.0), # subset: b omitted+ ([("a", 1.0), ("b", 1.0)], 1.0, 1.0), # back+ ([("b", 0.5)], 0.0, 0.5), # the other subset, new weight+ ([("a", 0.7), ("b", 1.0)], 0.7, 1.0), # weight tweak+ ([], 0.0, 0.0), # every adapter off+ ([("a", 1.0), ("b", 1.0)], 1.0, 1.0),+ ):+ b._apply_loras(state, loras, threading.Event())+ with torch.no_grad():+ torch.testing.assert_close(compiled(x), expected(wa, wb))+ assert [w for (_n, _p, w) in pipe._unsloth_loras] == [wa, wb]+ assert counter.frame_count == 1 # no recompile+ assert resets == [] # no captured graph dropped+ torch._dynamo.reset()+++def test_pinned_lora_scale_falls_back_when_a_scale_is_rewritten(monkeypatch):+ # Something rewriting a pinned scale as a float (a direct set_adapters) drops the pin: the next change takes the+ # set_adapters + graph reset path again instead of writing into a tensor the forward no longer reads.+ import threading++ from core.inference import diffusion as diff++ 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))+ b = _backend()+ pipe, layer = _peft_two_adapter_pipe()+ state = _fake_state(pipe, quant = "int8")+ state.cuda_graphs = ()+ pipe._unsloth_loras = b._resolve_lora_set(+ [("a", 1.0), ("b", 1.0)], family = "flux.1", hf_token = None+ )+ pipe._unsloth_loras_baked = True+ assert diff._pin_baked_lora_scales(pipe, "cpu") == 2+ # Idempotent: a second call pins nothing.+ assert diff._pin_baked_lora_scales(pipe, "cpu") == 0+ layer.set_scale("b", 1.0)+ b._apply_loras(state, [("a", 1.0)], threading.Event())+ assert layer.scaling["b"] == 0.0+ assert len(resets) == 1+++def test_pin_declines_weights_off_the_target_device():+ from core.inference import diffusion as diff++ pipe, layer = _peft_two_adapter_pipe()+ pipe._unsloth_loras = (("a", "/a", 1.0), ("b", "/b", 1.0))+ pipe._unsloth_loras_baked = True+ assert diff._pin_baked_lora_scales(pipe, "cuda") == 0+ assert isinstance(layer.scaling["a"], float)+++def test_replica_fingerprint_sees_an_in_place_scale_write():+ from core.inference import diffusion as diff+ from core.inference.diffusion_multigpu import weights_fingerprint++ pipe, _layer = _peft_two_adapter_pipe()+ pipe._unsloth_loras = (("a", "/a", 1.0), ("b", "/b", 1.0))+ pipe._unsloth_loras_baked = True+ assert diff._pin_baked_lora_scales(pipe, "cpu") == 2+ before = weights_fingerprint(pipe.transformer)+ assert weights_fingerprint(pipe.transformer) == before+ assert diff._set_pinned_lora_scales(pipe, {"a": 1.0})+ assert weights_fingerprint(pipe.transformer) != before+++def test_pinned_lora_change_also_sets_the_text_encoder_scales(monkeypatch):+ # A LoRA file can carry text-encoder weights too. The pinned path skips set_adapters, so it has to set the text+ # encoder's scales itself, or prompts encode with the bake-time weight while the marker names the new one.+ import threading++ import torch+ from peft import LoraConfig+ from peft.tuners.lora.layer import Linear++ from core.inference import diffusion as diff++ monkeypatch.setattr(+ dl,+ "resolve_specs",+ lambda specs, **_: [+ dl.ResolvedLora(i, dl.sanitize_alias(i), f"/{i}.safetensors", "safetensors", w)+ for i, w in specs+ ],+ )+ monkeypatch.setattr(diff.cuda_graph, "reset_all", lambda handles: None)+ pipe, _layer = _peft_two_adapter_pipe()+ config = LoraConfig(r = 2, lora_alpha = 4, lora_dropout = 0.0, init_lora_weights = False)+ te = Linear(+ torch.nn.Linear(8, 8, bias = False),+ "a",+ config = config,+ r = 2,+ lora_alpha = 4,+ init_lora_weights = False,+ )+ _peft_add_adapter(te, "b", config)+ pipe.components = {"transformer": pipe.transformer, "text_encoder": torch.nn.Sequential(te)}+ b = _backend()+ state = _fake_state(pipe, quant = "int8")+ state.cuda_graphs = ()+ pipe._unsloth_loras = b._resolve_lora_set(+ [("a", 1.0), ("b", 1.0)], family = "flux.1", hf_token = None+ )+ pipe._unsloth_loras_baked = True+ assert diff._pin_baked_lora_scales(pipe, "cpu") == 2+ b._apply_loras(state, [("a", 0.5)], threading.Event())+ assert te.scaling == {"a": 1.0, "b": 0.0} # 0.5 * alpha / r, and the omitted adapter off+++def _peft_embedding(name = "a"):+ import torch+ from peft import LoraConfig+ from peft.tuners.lora.layer import Embedding++ config = LoraConfig(r = 2, lora_alpha = 4, lora_dropout = 0.0, init_lora_weights = False)+ return Embedding(+ torch.nn.Embedding(10, 8),+ name,+ config = config,+ r = 2,+ lora_alpha = 4,+ init_lora_weights = False,+ )+++def test_pin_declines_a_denoiser_lora_it_cannot_pin(monkeypatch):+ # A PEFT Embedding keeps its factors in lora_embedding_A/B, not lora_B. Pinning only the Linear would make a+ # weight change skip set_adapters and leave the embedding at its bake-time scale: decline, keep floats.+ import torch++ from core.inference import diffusion as diff++ pipe, layer = _peft_two_adapter_pipe()+ emb = _peft_embedding()+ pipe.transformer = torch.nn.Sequential(layer, emb)+ pipe._unsloth_loras_baked = True+ assert diff._pin_baked_lora_scales(pipe, "cpu") == 0+ assert not getattr(pipe, diff._PINNED_LORA_SCALES_ATTR, None)+ assert all(not isinstance(v, torch.Tensor) for v in layer.scaling.values())+ assert diff._set_pinned_lora_scales(pipe, {"a": 0.5}) is False+++def test_pinned_lora_change_also_sets_a_text_encoder_embedding_scale(monkeypatch):+ # The side layers include a text encoder's PEFT Embedding (no lora_B entry), so its scale follows the change.+ import torch++ from core.inference import diffusion as diff++ pipe, _layer = _peft_two_adapter_pipe()+ emb = _peft_embedding()+ pipe.components = {"transformer": pipe.transformer, "text_encoder": torch.nn.Sequential(emb)}+ pipe._unsloth_loras_baked = True+ assert diff._pin_baked_lora_scales(pipe, "cpu") == 2+ assert diff._set_pinned_lora_scales(pipe, {"a": 0.5}) is True+ assert emb.scaling == {"a": 1.0} # 0.5 * alpha / r