Skip to content

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.

Studio: list third-party image LoRAs from model folders (#16483)

Nilay4d85a6a9a1d1
diff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.py
index bd1365588a2..57a0b35cb65 100644
--- a/studio/backend/core/inference/diffusion_lora.py
+++ b/studio/backend/core/inference/diffusion_lora.py
@@ -18,6 +18,7 @@ from typing import Optional
from utils.hf_xet_fallback import hf_hub_download_with_xet_fallback
from utils.paths.storage_roots import account_path
+from .diffusion_content import ROLE_LORA, inspect_checkpoint
from .diffusion_families import DIFFUSION_CANCELLED_MSG
from utils.paths.path_utils import is_appledouble_metadata
@@ -25,6 +26,7 @@ _ALL_EXTS = (".safetensors", ".gguf")
# ``kind`` in a ``<stem>.json`` sidecar marking the weight beside it as an image LoRA, not model weights.
LORA_SIDECAR_KIND = "diffusion-lora"
_MAX_SCAN_FOLDER_SUBDIRS = 200
+_HUB_REPO_PREFIXES = ("models--", "datasets--", "spaces--")
_EXPORT_LOCK = threading.Lock()
# ``<stem>.json`` with these stems marks a model or pipeline folder to the model scanners.
_MODEL_SENTINEL_STEMS = frozenset(
@@ -134,24 +136,36 @@ def _is_dir(p: Path) -> bool:
def _scan_folder_roots() -> list[Path]:
- """Registered custom model folders plus their direct sub-folders (where an export lands)."""
+ """The Models folder, its cache home and registered custom folders, each with its direct
+ sub-folders (where an export lands; hub repo folders skipped) and any ComfyUI ``loras`` folders."""
+ from hub.utils.comfy_models import comfy_lora_scan_roots
+ from utils.hf_cache_settings import get_hf_cache_paths
+
+ cache = get_hf_cache_paths()
try:
from storage.studio_db import list_scan_folders
folders = list_scan_folders()
except Exception: # noqa: BLE001 -- discovery never fails on the scan-folder table
- return []
+ folders = []
roots: list[Path] = []
- for folder in folders:
- root = Path(folder.get("path") or "")
+ for path in (
+ cache.hub_cache,
+ cache.cache_home,
+ *(folder.get("path") or "" for folder in folders),
+ ):
+ root = Path(path)
if not _is_dir(root):
continue
try:
children = list(root.iterdir())
except OSError:
children = []
- subdirs = sorted(c for c in children if not c.name.startswith(".") and _is_dir(c))
+ subdirs = sorted(
+ c for c in children if not c.name.startswith((".", *_HUB_REPO_PREFIXES)) and _is_dir(c)
+ )
roots.append(root)
roots.extend(subdirs[:_MAX_SCAN_FOLDER_SUBDIRS])
+ roots.extend(comfy_lora_scan_roots(root))
return roots
@@ -208,7 +222,7 @@ def _scan_local() -> list[LoraCatalogEntry]:
found = [(p, p.name if stem_counts.get(p.stem, 0) > 1 else p.stem) for p in files]
used = {entry_id for _, entry_id in found}
seen = {os.path.normcase(os.path.realpath(p)) for p in files}
- # Custom models folders contribute only sidecar-marked image LoRAs, so model weights never show up here.
+ # Custom models folders contribute only image LoRAs, so model weights never show up here.
for root in _scan_folder_roots():
for p in _weight_files(root):
key = os.path.normcase(os.path.realpath(p))
@@ -286,17 +300,29 @@ def _sidecar_data(weight_path: Path) -> Optional[dict]:
return data if isinstance(data, dict) else None
-def is_image_lora_file(path: Path) -> bool:
- """A .safetensors/.gguf whose sidecar marks it as an image LoRA (``kind``, or a trainer sidecar
- from before the marker). Model scanners use this to keep image LoRAs out of model listings."""
- if path.suffix.lower() not in _ALL_EXTS:
- return False
+def _has_lora_sidecar(path: Path) -> bool:
data = _sidecar_data(path)
return data is not None and (
data.get("kind") == LORA_SIDECAR_KIND or data.get("source") == "studio-trained"
)
+def is_image_lora_file(path: Path) -> bool:
+ """Sidecar-marked image LoRA, or a .safetensors of LoRA tensors not beside a model marker (a chat
+ adapter has the same keys). Model scanners use this to keep image LoRAs out of model listings."""
+ if path.suffix.lower() not in _ALL_EXTS:
+ return False
+ if _has_lora_sidecar(path):
+ return True
+ return (
+ path.suffix.lower() == ".safetensors"
+ and not any(
+ os.path.lexists(path.with_name(f"{stem}.json")) for stem in _MODEL_SENTINEL_STEMS
+ )
+ and inspect_checkpoint(str(path)).role == ROLE_LORA
+ )
+
+
def _read_lora_sidecar(weight_path: Path) -> tuple[tuple[str, ...], float]:
"""Read the ``<stem>.json`` sidecar next to a local adapter -> ``(families, weight_default)``.
Returns ``((), 1.0)`` when absent or unreadable, so discovery never fails on a bad file."""
@@ -375,7 +401,7 @@ def export_local_lora(lora_id: str, dest_dir: Path) -> Path:
if not out.exists():
return not out.with_suffix(".json").exists()
return filecmp.cmp(src, out, shallow = False) and (
- not out.with_suffix(".json").exists() or is_image_lora_file(out)
+ not out.with_suffix(".json").exists() or _has_lora_sidecar(out)
)
with _EXPORT_LOCK:
diff --git a/studio/backend/hub/utils/comfy_models.py b/studio/backend/hub/utils/comfy_models.py
index a299c3c389a..35ccdb0a8ef 100644
--- a/studio/backend/hub/utils/comfy_models.py
+++ b/studio/backend/hub/utils/comfy_models.py
@@ -17,11 +17,11 @@ from utils.paths.path_utils import is_appledouble_metadata
DIT_FOLDERS = ("diffusion_models", "unet", "checkpoints")
TEXT_ENCODER_FOLDERS = ("text_encoders", "clip")
VAE_FOLDERS = ("vae",)
-_ROLE_FOLDERS = DIT_FOLDERS + TEXT_ENCODER_FOLDERS + VAE_FOLDERS
+LORA_FOLDERS = ("loras",)
+_ROLE_FOLDERS = DIT_FOLDERS + TEXT_ENCODER_FOLDERS + VAE_FOLDERS + LORA_FOLDERS
_COMFY_ONLY_FOLDERS = frozenset(
{
*_ROLE_FOLDERS,
- "loras",
"clip_vision",
"controlnet",
"upscale_models",
@@ -44,6 +44,7 @@ class ComfyLayout:
dit_dirs: tuple[Path, ...] = ()
text_encoder_dirs: tuple[Path, ...] = ()
vae_dirs: tuple[Path, ...] = ()
+ lora_dirs: tuple[Path, ...] = ()
def _is_dir(path: Path) -> bool:
@@ -166,8 +167,9 @@ def comfy_layout(folder: Path) -> Optional[ComfyLayout]:
dit_dirs = _role(DIT_FOLDERS),
text_encoder_dirs = _role(TEXT_ENCODER_FOLDERS),
vae_dirs = _role(VAE_FOLDERS),
+ lora_dirs = _role(LORA_FOLDERS),
)
- if not (layout.dit_dirs or layout.text_encoder_dirs or layout.vae_dirs):
+ if not (layout.dit_dirs or layout.text_encoder_dirs or layout.vae_dirs or layout.lora_dirs):
return None
return layout
@@ -211,6 +213,13 @@ def comfy_dit_scan_roots(folder: Path) -> tuple[Path, ...]:
return tuple(roots)
+def comfy_lora_scan_roots(folder: Path) -> tuple[Path, ...]:
+ layout = comfy_layout(folder)
+ if layout is None:
+ return ()
+ return tuple(p for root in layout.lora_dirs for p in (root, *_plain_subdirs(root)))
+
+
# models/<dit folder>/ plus the scanner's subfolder depth, then the ComfyUI root above models/.
_MAX_LAYOUT_ANCESTORS = _MAX_SUBDIR_DEPTH + 3
_MAX_COMPONENT_FILES = 64
diff --git a/studio/backend/tests/test_comfy_scan_folders.py b/studio/backend/tests/test_comfy_scan_folders.py
index 7a22e713c4f..5dedde225b6 100644
--- a/studio/backend/tests/test_comfy_scan_folders.py
+++ b/studio/backend/tests/test_comfy_scan_folders.py
@@ -266,7 +266,7 @@ def test_extra_model_paths_yaml(tmp_path, monkeypatch):
shared / "missing_dir",
]
assert extra["unet"] == [no_base]
- assert "loras" not in extra
+ assert extra["loras"] == [shared / "loras"]
layout = comfy_models.comfy_layout(root)
assert layout is not None and layout.models_dir is None
diff --git a/studio/backend/tests/test_diffusion_lora_scan_folders.py b/studio/backend/tests/test_diffusion_lora_scan_folders.py
index 13d931ede8c..114336bb34e 100644
--- a/studio/backend/tests/test_diffusion_lora_scan_folders.py
+++ b/studio/backend/tests/test_diffusion_lora_scan_folders.py
@@ -17,13 +17,17 @@ from core.inference import diffusion_lora as dl
import storage.studio_db as studio_db
_MARK = {"kind": "diffusion-lora"}
+_LORA_KEY = "unet.down.0.lora_A.weight"
+_MODEL_KEY = "model.layers.0.self_attn.q_proj.weight"
-def _safetensors(path, sidecar = None):
+def _safetensors(
+ path,
+ sidecar = None,
+ key = _LORA_KEY,
+):
path.parent.mkdir(parents = True, exist_ok = True)
- header = json.dumps(
- {"unet.down.0.lora_A.weight": {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]}}
- ).encode()
+ header = json.dumps({key: {"dtype": "F32", "shape": [1], "data_offsets": [0, 4]}}).encode()
path.write_bytes(struct.pack("<Q", len(header)) + header + b"\0\0\0\0")
if sidecar is not None:
path.with_suffix(".json").write_text(json.dumps(sidecar))
@@ -80,12 +84,99 @@ def test_an_export_in_a_custom_folder_is_listed(catalog, tmp_path):
def test_unmarked_weights_in_a_custom_folder_are_ignored(catalog, tmp_path):
folder = tmp_path / "my-models"
- _safetensors(folder / "model.safetensors")
- _safetensors(folder / "notes.safetensors", sidecar = {"family": "sdxl"})
+ _safetensors(folder / "model.safetensors", key = _MODEL_KEY)
+ _safetensors(folder / "notes.safetensors", sidecar = {"family": "sdxl"}, key = _MODEL_KEY)
register(str(folder))
assert _local() == {}
+def test_a_third_party_lora_without_a_sidecar_is_listed(catalog, tmp_path):
+ folder = tmp_path / "my-models"
+ lora = _safetensors(folder / "pixel-art" / "style.safetensors", key = "lora_unet_down.alpha")
+ register(folder)
+ entry = _by_path(lora)
+ assert entry.display_name == "style" and entry.families == () and not entry.fine_tuned
+ assert dl.resolve_one(entry.id, 1.0).path == str(lora)
+
+
+ "drop",
+ [
+ "style.safetensors",
+ "hub/style.safetensors",
+ "hub/loras/style.safetensors",
+ "loras/style.safetensors",
+ ],
+)
+def test_a_lora_dropped_in_the_models_folder_is_listed(catalog, tmp_path, monkeypatch, drop):
+ import utils.hf_cache_settings as settings
+
+ home = tmp_path / "models"
+ paths = type("Paths", (), {"cache_home": home, "hub_cache": home / "hub"})()
+ monkeypatch.setattr(settings, "get_hf_cache_paths", lambda: paths)
+ lora = _safetensors(home / drop)
+ _safetensors(home / "hub" / "models--a--b" / "snapshots" / "c" / "deep.safetensors")
+ assert [e.local_path for e in _local().values()] == [str(lora)]
+
+
[email protected]("registered", ["ComfyUI", "ComfyUI/models"])
+def test_loras_under_a_comfyui_folder_are_listed(catalog, tmp_path, registered):
+ models = tmp_path / "ComfyUI" / "models"
+ (models / "checkpoints").mkdir(parents = True)
+ lora = _safetensors(models / "loras" / "flux" / "style.safetensors")
+ register(tmp_path / registered)
+ assert [e.local_path for e in _local().values()] == [str(lora)]
+
+
+def test_loras_listed_in_extra_model_paths_yaml_are_listed(catalog, tmp_path, monkeypatch):
+ from hub.storage import scan_folders
+
+ monkeypatch.setattr(scan_folders, "_denied_path_prefixes", lambda: [])
+ root = tmp_path / "ComfyUI"
+ (root / "models" / "checkpoints").mkdir(parents = True)
+ lora = _safetensors(tmp_path / "shared" / "Lora" / "style.safetensors")
+ (root / "extra_model_paths.yaml").write_text(
+ f"a111:\n base_path: {tmp_path / 'shared'}\n loras: Lora\n"
+ )
+ register(root)
+ assert [e.local_path for e in _local().values()] == [str(lora)]
+
+
+def test_a_chat_adapter_in_a_custom_folder_stays_out_of_the_picker(catalog, tmp_path):
+ from hub.services.models.local_inventory import _scan_models_dir
+
+ folder = tmp_path / "my-models"
+ adapter = folder / "chat-lora"
+ _safetensors(adapter / "adapter_model.safetensors")
+ (adapter / "adapter_config.json").write_text(json.dumps({"peft_type": "LORA"}))
+ register(folder)
+ assert _local() == {}
+ assert [row.display_name for row in _scan_models_dir(folder)] == ["chat-lora"]
+
+
+def test_header_of_an_unchanged_lora_is_read_once(catalog, tmp_path, monkeypatch):
+ from core.inference import diffusion_content
+
+ folder = tmp_path / "my-models"
+ lora = _safetensors(folder / "style.safetensors")
+ register(folder)
+ reads = []
+ real = diffusion_content._read_safetensors_header
+ monkeypatch.setattr(
+ diffusion_content, "_read_safetensors_header", lambda p: reads.append(p) or real(p)
+ )
+ assert len(_local()) == len(_local()) == 1
+ assert reads == [str(lora)]
+
+
+def test_an_export_keeps_a_foreign_json_beside_an_identical_lora(catalog, tmp_path):
+ _safetensors(catalog / "style.safetensors")
+ dest = tmp_path / "out"
+ _safetensors(dest / "style.safetensors", sidecar = {"note": "mine"})
+ assert dl.export_local_lora("style", dest).name == "style-2.safetensors"
+ assert json.loads((dest / "style.json").read_text()) == {"note": "mine"}
+
+
def test_custom_folder_ids_stay_stable_when_folders_change(catalog, tmp_path):
(catalog / "style.safetensors").write_bytes(b"catalog")
folders = [tmp_path / name for name in ("a", "b", "c")]
@@ -121,7 +212,10 @@ def test_marked_loras_are_not_listed_as_models(tmp_path, scanner):
assert _scan_models_dir(folder) == []
assert _scan_models_dir(tmp_path) == []
- _safetensors(tmp_path / "checkpoint" / "model.safetensors")
+ _safetensors(tmp_path / "plain" / "style.safetensors")
+ assert _scan_models_dir(tmp_path) == []
+
+ _safetensors(tmp_path / "checkpoint" / "model.safetensors", key = _MODEL_KEY)
assert [row.display_name for row in _scan_models_dir(tmp_path)] == ["checkpoint"]
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index bbb564ef768..9d4fdb955bd 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -6754,7 +6754,7 @@ export function ImagesPage({
{loraCapable && (
<Field
label="LoRAs"
- hint="Style or character adapters applied on top of the model. Enter a Hugging Face repo id (or pick a suggestion) and set the strength (1.0 = full effect, 0 disables). Stack several."
+ hint="Style or character adapters applied on top of the model. Enter a Hugging Face repo id, pick a suggestion, or add a folder of LoRA files, then set the strength (1.0 = full effect, 0 disables). Stack several."
>
<div className="space-y-2">
{availableLoras.length > 0 && (
@@ -6836,7 +6836,7 @@ export function ImagesPage({
type="button"
variant="ghost"
size="sm"
- title="Add a custom models folder. Image LoRAs exported from Unsloth in it show up here."
+ title="Add a custom models folder. Image LoRA .safetensors files in it show up here."
onClick={() => setLoraFoldersOpen(true)}
>
<HugeiconsIcon icon={FolderAddIcon} className="size-3.5" />