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: a denoiser-only LoRA change keeps the cached text embeddings (#17105)
Daniel Han4db4ac05c5b5
diff --git a/studio/backend/core/inference/diffusion_prompt_cache.py b/studio/backend/core/inference/diffusion_prompt_cache.pyindex df9076a1d26..482409ccc28 100644--- a/studio/backend/core/inference/diffusion_prompt_cache.py+++ b/studio/backend/core/inference/diffusion_prompt_cache.py@@ -212,9 +212,186 @@ def _encoder_identity(pipe: Any) -> list:return ident-def _lora_state(pipe: Any) -> Any:+# "0": every attached LoRA keys the text embeddings, including adapters only the denoiser carries.+_ENV_SCOPED_LORA_KEY = "UNSLOTH_DIFFUSION_TE_SCOPED_LORA_KEY"+_DENOISER_ATTRS = (+ "transformer",+ "transformer_2",+ "transformer_3",+ "unconditional_transformer",+ "unet",+ "prior",+ "decoder",+)+# Reading these off a denoiser runs none of its layers.+_INERT_MODULE_ATTRS = frozenset({"dtype", "device", "config"})+_MAX_FOLLOWED_METHODS = 64+++def _scoped_lora_key() -> bool:+ return (os.environ.get(_ENV_SCOPED_LORA_KEY) or "").strip().lower() not in _FALSE_TOKENS+++def _inert_base_property(cls: Any, attr: str, prop: Any) -> bool:+ """``prop`` is ``DiffusionPipeline``'s own (``_execution_device``, ``device``, ``dtype``): no layer runs."""try:- return _plain(tuple(getattr(pipe, "_unsloth_loras", ()) or ()))+ from diffusers import DiffusionPipeline+ except Exception: # noqa: BLE001 - no base to compare against: follow the getter instead+ return False+ return cls is not DiffusionPipeline and prop is inspect.getattr_static(+ DiffusionPipeline, attr, None+ )+++def _encode_skips_denoisers(+ cls: Any,+ name: str,+ instance: Any = None,+) -> bool:+ """True only when ``cls.<name>`` and the ``self`` methods / properties it reads provably run no denoiser."""+ import ast+ import textwrap++ own = getattr(instance, "__dict__", None) or {}+ seen: set = set()+ todo = [name]+ while todo:+ method = todo.pop()+ if method in seen:+ continue+ seen.add(method)+ if len(seen) > _MAX_FOLLOWED_METHODS:+ return False+ if method in own:+ return False+ func = inspect.getattr_static(cls, method, None)+ if func is None:+ continue+ if isinstance(func, property):+ if _inert_base_property(cls, method, func):+ continue+ func = func.fget+ if func is None:+ return False+ elif isinstance(func, (staticmethod, classmethod)):+ func = func.__func__+ if not inspect.isfunction(inspect.unwrap(func)):+ return False # a descriptor or callable object whose reads this walk cannot see+ try:+ tree = ast.parse(textwrap.dedent(inspect.getsource(inspect.unwrap(func))))+ except (OSError, TypeError, SyntaxError, ValueError):+ return False+ fn = tree.body[0] if tree.body else None+ if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)) or not fn.args.args:+ return False+ me = fn.args.args[0].arg+ parents = {id(c): n for n in ast.walk(fn) for c in ast.iter_child_nodes(n)}+ for node in ast.walk(fn):+ if isinstance(node, ast.Name) and node.id == "super":+ return False+ if isinstance(node, ast.Call):+ callee = node.func.id if isinstance(node.func, ast.Name) else None+ if callee in ("isinstance", "issubclass", "type", "id"):+ continue+ if (+ callee in ("getattr", "hasattr", "vars", "setattr", "delattr")+ and node.args+ and isinstance(node.args[0], ast.Name)+ and node.args[0].id == me+ ):+ return False+ if any(+ isinstance(arg, ast.Name) and arg.id == me+ for arg in [*node.args, *(k.value for k in node.keywords)]+ ):+ return False # self handed to a helper: what it reads is unknown+ if not (+ isinstance(node, ast.Attribute)+ and isinstance(node.value, ast.Name)+ and node.value.id == me+ ):+ continue+ if node.attr in _DENOISER_ATTRS:+ parent = parents.get(id(node))+ if not (+ isinstance(parent, ast.Attribute)+ and parent.value is node+ and parent.attr in _INERT_MODULE_ATTRS+ ):+ return False+ elif node.attr in own:+ if _bound_code(own[node.attr]):+ return False+ elif _followable(inspect.getattr_static(cls, node.attr, None)):+ todo.append(node.attr)+ return True+++def _bound_code(value: Any) -> bool:+ import functools+ import types+ return isinstance(value, (types.FunctionType, types.MethodType, functools.partial))+++def _followable(value: Any) -> bool:+ return value is not None and (callable(value) or hasattr(type(value), "__get__"))+++def _adapter_components(owner: Any) -> Optional[dict]:+ """Adapter name -> the components it patches, or None when the owner cannot say."""+ out: dict = {}+ try:+ listed = (+ owner.get_list_adapters() if callable(getattr(owner, "get_list_adapters", None)) else {}+ )+ for component, names in (listed or {}).items():+ for n in names or ():+ out.setdefault(n, set()).add(str(component))+ except Exception: # noqa: BLE001 - unclassifiable+ return None+ try:+ from .diffusion_lora_files import KRON_ATTR++ roots = {}+ for attr in (*_DENOISER_ATTRS, *_TEXT_ENCODER_ATTRS):+ module = getattr(owner, attr, None)+ if module is not None:+ roots[id(module)] = attr+ for n, adapters in (owner.__dict__.get(KRON_ATTR, {}) or {}).items():+ for adapter in adapters:+ out.setdefault(n, set()).add(roots.get(id(getattr(adapter, "root", None)), "?"))+ from .diffusion_lora_quant_merge import _MERGED_ATTR++ merged = getattr(owner, _MERGED_ATTR, None)+ if merged:+ # merge() refuses unless every merged layer sits inside the denoisers+ for n in merged.get("weights", {}) or {}:+ out.setdefault(n, set()).add("transformer")+ except Exception: # noqa: BLE001 - unclassifiable+ return None+ return out+++def _lora_state(pipe: Any, skips_denoisers: bool = False) -> Any:+ try:+ loras = tuple(getattr(pipe, "_unsloth_loras", ()) or ())+ except TypeError:+ return None+ if skips_denoisers and loras and _scoped_lora_key():+ components = _adapter_components(pipe)+ if components is not None:+ loras = tuple(+ entry+ for entry in loras+ if not (+ isinstance(entry, (tuple, list))+ and entry+ and components.get(entry[0])+ and components[entry[0]] <= set(_DENOISER_ATTRS)+ )+ )+ try:+ return _plain(loras)except TypeError:return None@@ -310,6 +487,10 @@ def _wrap_encode_prompt(signature = inspect.signature(encode)except (TypeError, ValueError):return False+ try:+ skips_denoisers = _encode_skips_denoisers(type(pipe), name, pipe)+ except Exception: # noqa: BLE001 - unprovable: the full LoRA key+ skips_denoisers = Falsedef cached_encode_prompt(*args: Any, **kwargs: Any) -> Any:key = None@@ -322,7 +503,7 @@ def _wrap_encode_prompt(payload = {"load": load_fp,"encoders": _encoder_identity(pipe),- "loras": _lora_state(lora_owner),+ "loras": _lora_state(lora_owner, skips_denoisers),"args": keyed,}if name != "encode_prompt":diff --git a/studio/backend/tests/test_diffusion_prompt_cache.py b/studio/backend/tests/test_diffusion_prompt_cache.pyindex b30bb726a84..606850b7804 100644--- a/studio/backend/tests/test_diffusion_prompt_cache.py+++ b/studio/backend/tests/test_diffusion_prompt_cache.py@@ -732,3 +732,250 @@ def test_cfg_negative_per_text_kill_switch(monkeypatch):for text in ("a cat", "a dog"):pipe.encode_prompt(text, negative_prompt = "blurry")assert [c[0] for c in pipe.calls] == ["a cat", "blurry", "a dog", "blurry"]+++SCOPED_ENV = "UNSLOTH_DIFFUSION_TE_SCOPED_LORA_KEY"+++class _AdapterPipe(_EncodePipe):+ def __init__(self, listed = None):+ super().__init__()+ self.transformer = torch.nn.Linear(2, 2)+ self.listed = listed or {}++ def get_list_adapters(self):+ return self.listed+++class _DenoiserReadingPipe(_AdapterPipe):+ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ self.calls += 1+ return (self.transformer(torch.ones(1, 2)) + float(len(prompt)),)+++class _DtypeOnlyPipe(_AdapterPipe):+ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ self.calls += 1+ dtype = (+ self.text_encoder.weight.dtype+ if self.text_encoder is not None+ else self.transformer.dtype+ )+ return (torch.full((1, 2), float(len(prompt)), dtype = dtype),)+++def _sweep(pipe, *entries):+ for entry in entries:+ pipe._unsloth_loras = entry+ pipe.encode_prompt("a cat")+ return pipe.calls+++def test_a_denoiser_only_strength_sweep_reuses_the_text_embeddings(monkeypatch):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _AdapterPipe({"transformer": ["style"]})+ prompt_cache.install(pipe)+ first = pipe.encode_prompt("a cat")+ calls = _sweep(pipe, *((("style", "/x/style.safetensors", w),) for w in (0.25, 0.5, 0.75, 1.0)))+ assert calls == 1+ pipe._unsloth_loras = ()+ assert torch.equal(pipe.encode_prompt("a cat")[0], first[0]) and pipe.calls == 1+++ "listed",+ [+ {"text_encoder": ["style"]},+ {"transformer": ["style"], "text_encoder": ["style"]}, # one file patching both+ {}, # nothing says where it sits: the conservative key+ ],+)+def test_an_adapter_that_may_reach_the_text_encoder_still_misses(monkeypatch, listed):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _AdapterPipe(listed)+ prompt_cache.install(pipe)+ assert _sweep(pipe, (("style", "/x", 0.5),), (("style", "/x", 0.7),)) == 2+++def test_an_encode_that_runs_the_denoiser_keys_its_adapters(monkeypatch):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _DenoiserReadingPipe({"transformer": ["style"]})+ prompt_cache.install(pipe)+ assert _sweep(pipe, (("style", "/x", 0.5),), (("style", "/x", 0.7),)) == 2+++def test_a_denoiser_dtype_read_runs_no_layer(monkeypatch):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _DtypeOnlyPipe({"transformer": ["style"]})+ prompt_cache.install(pipe)+ assert _sweep(pipe, (("style", "/x", 0.5),), (("style", "/x", 0.7),)) == 1+++def test_the_scoped_key_switch_keys_every_adapter(monkeypatch):+ monkeypatch.setenv(SCOPED_ENV, "0")+ pipe = _AdapterPipe({"transformer": ["style"]})+ prompt_cache.install(pipe)+ assert _sweep(pipe, (("style", "/x", 0.5),), (("style", "/x", 0.7),)) == 2+ assert prompt_cache._ENV_SCOPED_LORA_KEY == SCOPED_ENV+++def test_adapters_merged_into_quantized_denoiser_weights_are_denoiser_only(monkeypatch):+ from core.inference import diffusion_lora_quant_merge as qm++ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _AdapterPipe({}) # merged adapters leave PEFT: only the merge state names them+ prompt_cache.install(pipe)+ setattr(pipe, qm._MERGED_ATTR, {"layers": [], "weights": {"style": 0.5}, "device": "cpu"})+ assert _sweep(pipe, (("style", "/x", 0.5),), (("style", "/x", 0.7),)) == 1+++def test_an_instance_level_encode_override_keeps_the_full_key(monkeypatch):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _AdapterPipe({"transformer": ["style"]})+ original = pipe.encode_prompt++ def encode_prompt(prompt, device = None):+ return original(prompt, device = device)++ pipe.encode_prompt = encode_prompt+ prompt_cache.install(pipe)+ assert _sweep(pipe, (("style", "/x", 0.5),), (("style", "/x", 0.7),)) == 2+++def test_the_static_check_on_real_pipelines():+ diffusers = pytest.importorskip("diffusers")+ qwen = getattr(diffusers, "QwenImagePipeline", None)+ if qwen is not None:+ assert prompt_cache._encode_skips_denoisers(qwen, "encode_prompt")++ def _run(pipe, prompt):+ return pipe.transformer(prompt)++ class _Helper:+ def encode_prompt(self, prompt):+ return _run(+ self, prompt+ ) # self handed to a function the check does not follow: unprovable++ class _Inherited(_AdapterPipe):+ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ return super().encode_prompt(prompt, device = device)++ class _Dynamic(_AdapterPipe):+ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ return getattr(self, "transformer")(torch.ones(1, 2))++ class _Indirect(_AdapterPipe):+ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ return self._inner(prompt)++ def _inner(self, prompt):+ return self.unet(prompt)++ for cls in (_Helper, _Inherited, _Dynamic, _Indirect):+ assert not prompt_cache._encode_skips_denoisers(cls, "encode_prompt"), cls+++class _HelperPipe(_AdapterPipe):+ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ self.calls += 1+ return (self._embed(prompt),)++ def _embed(self, prompt):+ return torch.full((1, 2), float(len(prompt)))+++class _PropertyPipe(_AdapterPipe):+ @property+ def conditioning(self):+ return self.transformer.weight.detach().clone()++ def encode_prompt(+ self,+ prompt,+ device = None,+ ):+ self.calls += 1+ return (self.conditioning,)+++class _CleanPropertyPipe(_PropertyPipe):+ @property+ def conditioning(self):+ return torch.ones(1, 2)+++class _Reads:+ def __get__(+ self,+ obj,+ owner = None,+ ):+ return obj.transformer.weight.detach().clone()+++class _DescriptorPipe(_PropertyPipe):+ conditioning = _Reads()+++def _strength_sweep(pipe):+ out = []+ for strength in (0.25, 0.75):+ pipe._unsloth_loras = (("style", "/x/style.safetensors", strength),)+ with torch.no_grad():+ pipe.transformer.weight.fill_(strength)+ out.append(pipe.encode_prompt("same")[0].flatten()[0].item())+ return out+++def test_an_instance_override_of_a_followed_helper_keeps_the_full_key(monkeypatch):+ import types++ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _HelperPipe({"transformer": ["style"]})+ assert prompt_cache._encode_skips_denoisers(_HelperPipe, "encode_prompt")+ pipe._embed = types.MethodType(+ lambda self, prompt: self.transformer.weight.detach().clone(), pipe+ )+ prompt_cache.install(pipe)+ assert _strength_sweep(pipe) == [0.25, 0.75] and pipe.calls == 2++[email protected]("cls", [_PropertyPipe, _DescriptorPipe])+def test_a_property_or_descriptor_reading_the_denoiser_keeps_the_full_key(monkeypatch, cls):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = cls({"transformer": ["style"]})+ assert not prompt_cache._encode_skips_denoisers(cls, "encode_prompt")+ prompt_cache.install(pipe)+ assert _strength_sweep(pipe) == [0.25, 0.75] and pipe.calls == 2+++def test_a_property_running_no_denoiser_still_reuses_the_embeddings(monkeypatch):+ monkeypatch.delenv(SCOPED_ENV, raising = False)+ pipe = _CleanPropertyPipe({"transformer": ["style"]})+ prompt_cache.install(pipe)+ assert _strength_sweep(pipe) == [1.0, 1.0] and pipe.calls == 1