{"record":{"id":"60a5d486b74036ad","repo":"unslothai/unsloth","slug":"failed-to-apply-lora-exc","errorCode":null,"errorMessage":"Failed to apply LoRA: {exc}","messagePattern":"Failed to apply LoRA: (.+?)","errorType":"validation","errorClass":"ValueError","httpStatus":400,"severity":"error","filePath":"studio/backend/core/inference/diffusion.py","lineNumber":5081,"sourceCode":"        )\n        uniq = list(desired)\n        if desired == current:\n            return\n        try:\n            if current:\n                pipe.unload_lora_weights()\n            for name, path, _weight in uniq:\n                pipe.load_lora_weights(path, adapter_name = name)\n            pipe.set_adapters(\n                [name for name, _p, _w in uniq], adapter_weights = [w for _n, _p, w in uniq]\n            )\n        except Exception as exc:  # noqa: BLE001 -- surface as a clean 400\n            try:\n                pipe.unload_lora_weights()\n            except Exception:  # noqa: BLE001\n                pass\n            pipe._unsloth_loras = ()\n            raise ValueError(f\"Failed to apply LoRA: {exc}\") from exc\n        pipe._unsloth_loras = desired\n\n    def _adjust_baked_loras(\n        self,\n        state: Any,\n        pipe: Any,\n        specs: list[tuple[str, float]],\n        current: tuple,\n        quant_baked: bool,\n        cancel: threading.Event,\n    ) -> None:\n        \"\"\"Generation-time LoRA handling for a torchao-quantized pipe.\n\n        The adapters (if any) were baked at load time, before quantize_ + compile, so the\n        module topology is immutable here. Allowed without a reload: weight tweaks on the\n        baked set and disabling everything (scale 0 reproduces the quantized base exactly;\n        set_adapters is value-level, so torch.compile guards absorb it). Anything that would\n        change topology (adding adapters to a bake-less load, or a different adapter set)","sourceCodeStart":5063,"sourceCodeEnd":5099,"githubUrl":"https://github.com/unslothai/unsloth/blob/203007d19051dcd2ae33876786d117c99f6b0368/studio/backend/core/inference/diffusion.py#L5063-L5099","documentation":"Catch-all wrapper around the actual diffusers LoRA application sequence (`unload_lora_weights`, `load_lora_weights` per adapter, `set_adapters` with weights). Any exception from diffusers during loading or activation is cleaned up after -- the pipe's LoRA weights are unloaded (best-effort) and `pipe._unsloth_loras` reset to empty -- then re-raised as a clean ValueError with the underlying exception chained. This guarantees the pipeline is left in a coherent, adapter-free state rather than half-loaded.","triggerScenarios":"An adapter file that fails to parse in `load_lora_weights` (corrupt safetensors, mismatched layer shapes for this family), an invalid adapter_name collision handling, or `set_adapters` rejecting the weights list -- any Exception inside the try block triggers the cleanup and the wrapped raise.","commonSituations":"LoRA trained for a different base model architecture (key mismatch on load); truncated/corrupt adapter downloads; floating adapter weight lists whose length differs from the adapter list; version drift between diffusers and the adapter's serialization format.","solutions":["Read the chained original exception (`__cause__`) -- it names the real failure (shape mismatch, corrupt file, bad key).","Verify the LoRA was trained for the loaded model family/base checkpoint and re-download the adapter.","Retry without the failing adapter to isolate which one in the set breaks.","Upgrade diffusers to match the adapter's serialization format."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"# Sanity-check adapter files before generate\nfor path in adapter_paths:\n    with safe_open(path, framework=\"pt\") as f:  # safetensors\n        keys = list(f.keys())\n    assert any(k.startswith(arch_prefix) for k in keys), f\"{path} not for this family\"","typeGuard":"def adapter_parses(path: str) -> bool:\n    try:\n        with safe_open(path, framework=\"pt\"):\n            return True\n    except Exception:\n        return False","tryCatchPattern":"try:\n    diffusion.generate(prompt=p, loras=loras)\nexcept ValueError as e:\n    if str(e).startswith(\"Failed to apply LoRA:\"):\n        cause = e.__cause__  # real diffusers failure: shape mismatch, corrupt file, bad keys\n        log.warning(\"LoRA apply failed: %s\", cause)\n        return diffusion.generate(prompt=p, loras=[])  # adapter-free fallback\n    raise","preventionTips":["Always inspect the chained __cause__; the wrapper hides the real reason in its text.","Verify adapters were trained against the same base architecture before queuing them.","The pipeline self-cleans (unload_lora_weights + reset) on failure -- safe to continue without adapters."],"tags":["diffusion","lora","diffusers","error-handling","cleanup"],"backgroundTag":null,"analyzedSha":"203007d19051dcd2ae33876786d117c99f6b0368","analyzedAt":"2026-08-15T02:48:39.846Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}