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.

Unsloth Studio / Desktop: export image LoRAs and pick them up again from a custom models folder (#13146)

Leo Borcherding6207fc81630e
diff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.py
index 8dcef80c416..ca487226666 100644
--- a/studio/backend/core/inference/diffusion_lora.py
+++ b/studio/backend/core/inference/diffusion_lora.py
@@ -15,9 +15,11 @@ validates the id against the catalog / local dir / HF hub before loading.
from __future__ import annotations
+import hashlib
import json
import os
import re
+import stat
import threading
from dataclasses import dataclass, field
from pathlib import Path
@@ -33,6 +35,14 @@ from utils.paths.path_utils import is_appledouble_metadata
_NATIVE_EXTS = (".safetensors", ".gguf")
_DIFFUSERS_EXTS = (".safetensors",)
_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
+_EXPORT_LOCK = threading.Lock()
+# ``<stem>.json`` with these stems marks a model or pipeline folder to the model scanners.
+_MODEL_SENTINEL_STEMS = frozenset(
+ {"config", "adapter_config", "model_index", "modular_model_index"}
+)
@dataclass(frozen = True)
@@ -48,6 +58,7 @@ class LoraCatalogEntry:
local_path: Optional[str] = None
size_bytes: int = 0
weight_default: float = 1.0
+ fine_tuned: bool = False
@dataclass(frozen = True)
@@ -112,58 +123,171 @@ def sanitize_alias(raw: str) -> str:
return stem or "lora"
-def _scan_local() -> list[LoraCatalogEntry]:
- root = loras_dir()
+def _weight_files(root: Path) -> list[Path]:
try:
children = sorted(root.iterdir())
except OSError:
return []
-
- files = [
+ return [
p
for p in children
- if p.is_file() and p.suffix.lower() in _ALL_EXTS and not is_appledouble_metadata(p)
+ if p.suffix.lower() in _ALL_EXTS and not is_appledouble_metadata(p) and _is_file(p)
]
+
+
+def _is_file(p: Path) -> bool:
+ # Path.is_file() re-raises EACCES before Python 3.14; one unreadable entry must not fail the catalog.
+ try:
+ return p.is_file()
+ except OSError:
+ return False
+
+
+def _is_dir(p: Path) -> bool:
+ try:
+ return p.is_dir()
+ except OSError:
+ return False
+
+
+def _scan_folder_roots() -> list[Path]:
+ """Registered custom model folders plus their direct sub-folders (where an export lands)."""
+ 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 []
+ roots: list[Path] = []
+ for folder in folders:
+ root = Path(folder.get("path") or "")
+ 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))
+ roots.append(root)
+ roots.extend(subdirs[:_MAX_SCAN_FOLDER_SUBDIRS])
+ return roots
+
+
+def _account_allows():
+ """Managed accounts only see adapters (and sidecars) resolving inside paths they may read, so a
+ symlink cannot pull another account's or the host's file into listing, generation or export."""
+ from hub.services.models import account_access
+
+ if not account_access.managed_account():
+ return lambda p: True
+
+ def allows(p: Path) -> bool:
+ sidecar = p.with_suffix(".json")
+ return account_access.model_visible(str(p)) and (
+ not os.path.lexists(sidecar) or account_access.model_visible(str(sidecar))
+ )
+
+ return allows
+
+
+def _open_pinned(path: Path):
+ """Open ``path`` and prove the handle is the file now at its resolved, account-readable location,
+ so swapping a link between the catalog scan and the copy cannot redirect the read."""
+ f = open(path, "rb")
+ try:
+ real = os.path.realpath(path)
+ st, now = os.fstat(f.fileno()), os.stat(real)
+ if (st.st_dev, st.st_ino) != (now.st_dev, now.st_ino) or not _account_allows()(Path(real)):
+ raise FileNotFoundError(f"LoRA file '{path.name}' is not readable here")
+ except BaseException:
+ f.close()
+ raise
+ return f
+
+
+def _pinned_sidecar(weight_path: Path) -> Optional[dict]:
+ try:
+ with _open_pinned(weight_path.with_suffix(".json")) as f:
+ data = json.loads(f.read().decode("utf-8"))
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _scan_local() -> list[LoraCatalogEntry]:
+ root_dir = loras_dir()
+ allows = _account_allows()
+ files = [p for p in _weight_files(root_dir) if allows(p)]
# Two files sharing a stem but differing in extension collide on id (== stem), so a colliding stem keeps the full
# filename.
stem_counts: dict[str, int] = {}
for p in files:
stem_counts[p.stem] = stem_counts.get(p.stem, 0) + 1
+ 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.
+ for root in _scan_folder_roots():
+ for p in _weight_files(root):
+ key = os.path.normcase(os.path.realpath(p))
+ if key in seen or not is_image_lora_file(p) or not allows(p):
+ continue
+ seen.add(key)
+ # Keyed on the path, not scan order, so saved recipes never drift to another folder's same-named file.
+ entry_id = f"{p.stem}-{hashlib.sha1(os.fsencode(key)).hexdigest()[:8]}"
+ if entry_id in used:
+ continue
+ used.add(entry_id)
+ found.append((p, entry_id))
+
entries: list[LoraCatalogEntry] = []
- for p in files:
- ext = p.suffix.lower()
+ for p, entry_id in found:
try:
size = p.stat().st_size
except OSError:
size = 0
- entry_id = p.name if stem_counts.get(p.stem, 0) > 1 else p.stem
# A ``<stem>.json`` sidecar (written by the trainer on publish) records the adapter's family + default weight so
# it is family-gated instead of "unknown". Best-effort.
families, weight_default = _read_lora_sidecar(p)
entries.append(
LoraCatalogEntry(
id = entry_id,
- display_name = entry_id,
+ display_name = entry_id if p.parent == root_dir else p.stem,
source = "local",
- fmt = "gguf" if ext == ".gguf" else "safetensors",
+ fmt = "gguf" if p.suffix.lower() == ".gguf" else "safetensors",
local_path = str(p),
size_bytes = size,
families = families,
weight_default = weight_default,
+ fine_tuned = (_sidecar_data(p) or {}).get("source") == "studio-trained",
)
)
return entries
+def _sidecar_data(weight_path: Path) -> Optional[dict]:
+ try:
+ data = json.loads(weight_path.with_suffix(".json").read_text(encoding = "utf-8"))
+ except (OSError, ValueError):
+ return None
+ 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
+ data = _sidecar_data(path)
+ return data is not None and (
+ data.get("kind") == LORA_SIDECAR_KIND or data.get("source") == "studio-trained"
+ )
+
+
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."""
- sidecar = weight_path.with_suffix(".json")
- try:
- data = json.loads(sidecar.read_text(encoding = "utf-8"))
- except (OSError, ValueError):
- return (), 1.0
- if not isinstance(data, dict):
+ data = _sidecar_data(weight_path)
+ if data is None:
return (), 1.0
raw_family = data.get("family")
raw_families = data.get("families")
@@ -198,6 +322,80 @@ def _catalog_by_id() -> dict[str, LoraCatalogEntry]:
return {e.id: e for e in (list(_CURATED) + _scan_local())}
+def _staging_name(dest_dir: Path, stem: str) -> str:
+ # Not mkstemp: its 0600 file would publish an owner-only marker; a fresh open() honours the umask.
+ import secrets
+ return str(dest_dir / f".lora-export.{secrets.token_hex(8)}.part")
+
+
+def export_local_lora(lora_id: str, dest_dir: Path) -> Path:
+ """Copy a local adapter into ``dest_dir`` with a ``<stem>.json`` sidecar carrying the image LoRA marker.
+
+ Takes a catalog id, never a path, so only listed image LoRAs can be read. Returns the copied weight
+ file; a stem already used by other bytes, another weight format or a foreign ``.json`` gets a suffix.
+ """
+ import filecmp
+ import shutil
+
+ entry = next((e for e in _scan_local() if e.id == lora_id), None)
+ if entry is None or not entry.local_path:
+ raise FileNotFoundError(f"no local image LoRA named '{lora_id}'")
+ src = Path(entry.local_path)
+ dest_dir.mkdir(parents = True, exist_ok = True)
+
+ def _free(out: Path) -> bool:
+ if out.stem.lower() in _MODEL_SENTINEL_STEMS:
+ return False
+ if out.exists() and os.path.samefile(src, out):
+ return True
+ # The sidecar is per stem, so a sibling weight of another format would share it (case-insensitive FS too).
+ if any(
+ c.name != out.name
+ and c.stem.casefold() == out.stem.casefold()
+ and c.suffix.lower() in _ALL_EXTS
+ for c in dest_dir.iterdir()
+ ):
+ return False
+ 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)
+ )
+
+ with _EXPORT_LOCK:
+ out, n = dest_dir / src.name, 2
+ while not _free(out):
+ out = dest_dir / f"{src.stem}-{n}{src.suffix}"
+ n += 1
+ meta = json.dumps({**(_pinned_sidecar(src) or {}), "kind": LORA_SIDECAR_KIND}, indent = 2)
+ copy = not (out.exists() and os.path.samefile(src, out))
+ # Both files are staged under names no scanner reads, so a failed export leaves nothing behind.
+ sidecar = out.with_suffix(".json")
+ staged: list[str] = []
+ new_sidecar = not sidecar.exists()
+ try:
+ if copy:
+ staged.append(_staging_name(dest_dir, src.stem))
+ with _open_pinned(src) as fsrc, open(staged[-1], "xb") as fdst:
+ shutil.copyfileobj(fsrc, fdst)
+ st = os.fstat(fsrc.fileno())
+ os.chmod(staged[-1], stat.S_IMODE(st.st_mode))
+ os.utime(staged[-1], ns = (st.st_atime_ns, st.st_mtime_ns))
+ staged.append(_staging_name(dest_dir, src.stem))
+ Path(staged[-1]).write_text(meta, encoding = "utf-8")
+ # Marker first: a scanner must never see the weight unmarked.
+ os.replace(staged[-1], sidecar)
+ if copy:
+ os.replace(staged[0], out)
+ except BaseException:
+ for tmp in staged:
+ Path(tmp).unlink(missing_ok = True)
+ if new_sidecar and not out.exists():
+ sidecar.unlink(missing_ok = True)
+ raise
+ return out
+
+
def resolve_one(
spec_id: str,
weight: float,
@@ -205,6 +403,7 @@ def resolve_one(
family: Optional[str] = None,
hf_token: Optional[str] = None,
cancel_event: Optional[threading.Event] = None,
+ catalog: Optional[dict[str, LoraCatalogEntry]] = None,
) -> ResolvedLora:
"""Resolve a request LoRA id + weight to a concrete local file.
@@ -218,7 +417,7 @@ def resolve_one(
"""
# An empty token triggers an auth error instead of anonymous access; normalise to None.
hf_token = hf_token.strip() if hf_token and hf_token.strip() else None
- entry = _catalog_by_id().get(spec_id)
+ entry = (_catalog_by_id() if catalog is None else catalog).get(spec_id)
if entry is not None:
req_fam = (family or "").strip().lower()
if entry.families and req_fam and req_fam not in {f.lower() for f in entry.families}:
@@ -230,6 +429,9 @@ def resolve_one(
path = entry.local_path or ""
if not path or not os.path.exists(path):
raise FileNotFoundError(f"LoRA '{spec_id}' is no longer present on disk")
+ # Re-checked here: a catalog can be built well before an earlier stacked LoRA finishes downloading.
+ if not _account_allows()(Path(path)):
+ raise FileNotFoundError(f"LoRA '{spec_id}' is no longer present on disk")
return ResolvedLora(spec_id, sanitize_alias(spec_id), path, entry.fmt, weight)
if not entry.repo_id or not entry.weight_name:
raise ValueError(f"LoRA '{spec_id}' has no downloadable weight")
@@ -322,13 +524,20 @@ def resolve_specs(
)
out: list[ResolvedLora] = []
+ # One custom-folder scan per request, not one per stacked LoRA.
+ catalog = _catalog_by_id() if any(weight != 0 for _, weight in specs) else {}
try:
for spec_id, weight in specs:
if weight == 0:
continue
out.append(
resolve_one(
- spec_id, weight, family = family, hf_token = hf_token, cancel_event = cancel_event
+ spec_id,
+ weight,
+ family = family,
+ hf_token = hf_token,
+ cancel_event = cancel_event,
+ catalog = catalog,
)
)
except (
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index 142734ff949..09f9eee3ec9 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -2166,6 +2166,8 @@ def _write_lora_sidecar(
"trigger_prompt": cfg.instance_prompt,
"created_at": time.time(),
"source": "studio-trained",
+ # diffusion_lora.LORA_SIDECAR_KIND: marks the adapter as an image LoRA wherever it is copied.
+ "kind": "diffusion-lora",
}
sidecar_path.write_text(json.dumps(meta, indent = 2), encoding = "utf-8")
diff --git a/studio/backend/hub/services/models/common.py b/studio/backend/hub/services/models/common.py
index 2de6dacf60a..54ecfc0f69c 100644
--- a/studio/backend/hub/services/models/common.py
+++ b/studio/backend/hub/services/models/common.py
@@ -742,10 +742,13 @@ def _sum_file_sizes(paths) -> int:
def _main_gguf_files(path: Path, *, include_symlinks: bool = False) -> list[Path]:
+ from core.inference.diffusion_lora import is_image_lora_file
return [
entry
for entry in _iter_immediate_files(path, include_symlinks = include_symlinks)
- if _is_main_gguf_filename(entry.name) and not is_appledouble_metadata(entry)
+ if _is_main_gguf_filename(entry.name)
+ and not is_appledouble_metadata(entry)
+ and not is_image_lora_file(entry)
]
@@ -922,6 +925,13 @@ def _classify_local_path(
)
)
+ if source != "hf_cache":
+ from core.inference.diffusion_lora import is_image_lora_file
+
+ # An image LoRA beside a config is an Images-page add-on, not this folder's weights.
+ files = [
+ f for f in files if f.suffix.lower() != ".safetensors" or not is_image_lora_file(f)
+ ]
has_config = (scan_path / "config.json").is_file() if scan_path.is_dir() else False
has_adapter_config = (
(scan_path / "adapter_config.json").is_file() if scan_path.is_dir() else False
diff --git a/studio/backend/hub/services/models/local_inventory.py b/studio/backend/hub/services/models/local_inventory.py
index edd158a74e5..1d37e9765ad 100644
--- a/studio/backend/hub/services/models/local_inventory.py
+++ b/studio/backend/hub/services/models/local_inventory.py
@@ -109,10 +109,17 @@ def _http_error(status_code: int, detail: str):
return HTTPException(status_code = status_code, detail = detail)
+def _is_image_lora_file(path: Path) -> bool:
+ from core.inference.diffusion_lora import is_image_lora_file
+ return is_image_lora_file(path)
+
+
def _is_immediate_model_weight_file(path: Path) -> bool:
if is_appledouble_metadata(path):
return False
suffix = path.suffix.lower()
+ if suffix in (".safetensors", ".gguf") and _is_image_lora_file(path):
+ return False
if suffix == ".safetensors":
return True
if suffix == ".gguf":
@@ -389,6 +396,7 @@ def _scan_models_dir(
and child.suffix.lower() == ".gguf"
and child.is_file()
and not is_appledouble_metadata(child)
+ and not _is_image_lora_file(child)
)
if not is_dir and not is_gguf_file:
continue
@@ -754,6 +762,7 @@ def _scan_lmstudio_dir(
child.suffix.lower() == ".gguf"
and child.is_file()
and not is_appledouble_metadata(child)
+ and not _is_image_lora_file(child)
):
try:
updated_at = child.stat().st_mtime
@@ -808,6 +817,7 @@ def _scan_lmstudio_dir(
model_dir.suffix.lower() == ".gguf"
and model_dir.is_file()
and not is_appledouble_metadata(model_dir)
+ and not _is_image_lora_file(model_dir)
):
try:
updated_at = model_dir.stat().st_mtime
diff --git a/studio/backend/models/__init__.py b/studio/backend/models/__init__.py
index abae5d76b30..370db920a21 100644
--- a/studio/backend/models/__init__.py
+++ b/studio/backend/models/__init__.py
@@ -41,6 +41,7 @@ from .export import (
ExportBaseModelRequest,
ExportGGUFRequest,
ConvertQ4NXRequest,
+ ExportDiffusionLoRARequest,
ExportLoRAAdapterRequest,
LlmCompressorExportProbeResponse,
DecisionExportInfo,
@@ -102,6 +103,7 @@ __all__ = [
"ExportBaseModelRequest",
"ExportGGUFRequest",
"ConvertQ4NXRequest",
+ "ExportDiffusionLoRARequest",
"ExportLoRAAdapterRequest",
"LlmCompressorExportProbeResponse",
"DecisionExportInfo",
diff --git a/studio/backend/models/export.py b/studio/backend/models/export.py
index 1de309cedf3..0c30acd8e2d 100644
--- a/studio/backend/models/export.py
+++ b/studio/backend/models/export.py
@@ -292,6 +292,20 @@ class ConvertQ4NXRequest(BaseModel):
hf_token: Optional[str] = Field(None, description = "Hugging Face token for gated repos")
+class ExportDiffusionLoRARequest(BaseModel):
+ """Copy an image-generation LoRA from the Images catalog into an export folder."""
+
+ lora_id: str = Field(
+ ..., description = "Local adapter id as listed by /api/models/diffusion-loras"
+ )
+ save_directory: str = Field(..., description = "Directory the adapter is copied into")
+
+ @field_validator("save_directory", mode = "before")
+ @classmethod
+ def _check_save_directory(cls, v):
+ return _validate_save_directory(v)
+
+
class ExportLoRAAdapterRequest(ExportCommonOptions):
"""Request for exporting only the LoRA adapter (not merged)."""
diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.py
index 4e713371709..357c6231cda 100644
--- a/studio/backend/routes/export.py
+++ b/studio/backend/routes/export.py
@@ -51,6 +51,7 @@ from models import (
ExportGGUFRequest,
ExportLoRAAdapterRequest,
ConvertQ4NXRequest,
+ ExportDiffusionLoRARequest,
LlmCompressorExportProbeResponse,
ExportDecisionInfoResponse,
)
@@ -619,6 +620,51 @@ async def convert_q4nx(
)
[email protected]("/export/diffusion-lora", response_model = ExportOperationResponse)
+async def export_diffusion_lora(
+ request: ExportDiffusionLoRARequest, current_subject: str = Depends(get_current_subject)
+):
+ """Save a copy of an image-generation LoRA (weights plus metadata sidecar) to a folder.
+
+ A plain file copy out of the Images LoRA catalog: no loaded model, GPU or export worker.
+ """
+ validate_job_paths(request.model_dump())
+
+ def run() -> str:
+ from core.inference.diffusion_lora import export_local_lora
+ from utils.paths import resolve_export_write_dir
+
+ out = export_local_lora(
+ request.lora_id, Path(resolve_export_write_dir(request.save_directory))
+ )
+ return str(out.resolve())
+
+ try:
+ output_path = await asyncio.to_thread(run)
+ except FileNotFoundError as e:
+ raise HTTPException(status_code = 404, detail = str(e))
+ except ValueError as e:
+ raise HTTPException(status_code = 400, detail = str(e))
+ except OSError as e:
+ logger.error(f"Image LoRA export failed: {e}", exc_info = True)
+ raise HTTPException(status_code = 500, detail = "Failed to export image LoRA")
+
+ # Not routed through _export_details: a LoRA folder is not a chat model scan folder.
+ from utils.paths.storage_roots import exports_root
+
+ try:
+ shown = os.path.relpath(output_path, exports_root().resolve())
+ if shown.startswith(".."):
+ shown = output_path
+ except ValueError:
+ shown = output_path
+ return ExportOperationResponse(
+ success = True,
+ message = "Image LoRA exported",
+ details = {"output_path": shown},
+ )
+
+
@router.post("/export/lora", response_model = ExportOperationResponse)
async def export_lora_adapter(
request: ExportLoRAAdapterRequest,
diff --git a/studio/backend/routes/models.py b/studio/backend/routes/models.py
index ae69d27e95a..d27633242c0 100644
--- a/studio/backend/routes/models.py
+++ b/studio/backend/routes/models.py
@@ -417,7 +417,11 @@ def _has_non_gguf_weights(path: Path) -> bool:
try:
# Only the safetensors arm needs the check: a weight ".bin" is recognised by its name prefix, which a
# "._" already fails.
- if any(not is_appledouble_metadata(f) for f in path.glob("*.safetensors")):
+ from core.inference.diffusion_lora import is_image_lora_file
+ if any(
+ not is_appledouble_metadata(f) and not is_image_lora_file(f)
+ for f in path.glob("*.safetensors")
+ ):
return True
return any(_is_weight_bin(f.name) for f in path.glob("*.bin"))
except OSError:
@@ -433,10 +437,13 @@ def _servable_gguf_names(directory: Path) -> list[str]:
"""The ``.gguf`` names in *directory* that count as a model being present there. An imatrix is
calibration data, not a model artifact; mmproj and MTP drafters DO count, since they are
companions of a real model and presence is all they decide."""
+ from core.inference.diffusion_lora import is_image_lora_file
return [
p.name
for p in directory.glob("*.gguf")
- if not is_appledouble_metadata(p) and not _is_imatrix_path(p.name)
+ if not is_appledouble_metadata(p)
+ and not _is_imatrix_path(p.name)
+ and not is_image_lora_file(p)
]
@@ -524,6 +531,7 @@ def _scan_models_dir(
),
)
if limit is None or len(found) < limit:
+ from core.inference.diffusion_lora import is_image_lora_file
for gguf_file in models_dir.glob("*.gguf"):
if limit is not None and len(found) >= limit:
break
@@ -532,6 +540,7 @@ def _scan_models_dir(
gguf_file.is_file()
and _is_main_gguf_filename(gguf_file.name)
and not is_appledouble_metadata(gguf_file)
+ and not is_image_lora_file(gguf_file)
):
try:
updated_at = gguf_file.stat().st_mtime
@@ -712,6 +721,8 @@ def _scan_lmstudio_dir(
),
]
+ from core.inference.diffusion_lora import is_image_lora_file
+
found: List[LocalModelInfo] = []
for child in lm_dir.iterdir():
try:
@@ -720,6 +731,7 @@ def _scan_lmstudio_dir(
_is_main_gguf_filename(child.name)
and child.is_file()
and not is_appledouble_metadata(child)
+ and not is_image_lora_file(child)
):
try:
updated_at = child.stat().st_mtime
@@ -762,7 +774,7 @@ def _scan_lmstudio_dir(
bool(_servable_gguf_names(model_dir))
or (model_dir / "config.json").exists()
or any(
- not is_appledouble_metadata(p)
+ not is_appledouble_metadata(p) and not is_image_lora_file(p)
for p in model_dir.glob("*.safetensors")
)
)
@@ -788,6 +800,7 @@ def _scan_lmstudio_dir(
_is_main_gguf_filename(model_dir.name)
and model_dir.is_file()
and not is_appledouble_metadata(model_dir)
+ and not is_image_lora_file(model_dir)
):
try:
updated_at = model_dir.stat().st_mtime
@@ -3181,7 +3194,7 @@ async def scan_diffusion_loras(
"""
from core.inference import diffusion_lora
- entries = diffusion_lora.list_loras(family = family)
+ entries = await asyncio.to_thread(diffusion_lora.list_loras, family = family)
if account_access.managed_account():
entries = await asyncio.to_thread(account_access.filter_model_rows, entries)
return {
@@ -3194,6 +3207,7 @@ async def scan_diffusion_loras(
"families": list(e.families),
"size_bytes": e.size_bytes,
"weight_default": e.weight_default,
+ "fine_tuned": e.fine_tuned,
}
for e in entries
],
diff --git a/studio/backend/tests/test_diffusion_lora_scan_folders.py b/studio/backend/tests/test_diffusion_lora_scan_folders.py
new file mode 100644
index 00000000000..2c4cde6dbb8
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_lora_scan_folders.py
@@ -0,0 +1,294 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""An exported image LoRA dropped into a custom models folder shows up in the Images LoRA picker, and
+never as a model in the model pickers."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import struct
+
+import pytest
+
+from core.inference import diffusion_lora as dl
+import storage.studio_db as studio_db
+
+_MARK = {"kind": "diffusion-lora"}
+
+
+def _safetensors(path, sidecar = None):
+ 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()
+ 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))
+ return path
+
+
+# The registered-folder table itself (normalisation, denylist) is covered elsewhere; macOS tmp_path
+# lives under /private/var, which registration refuses, so the rows are faked here.
+_FOLDERS: list = []
+
+
+def register(folder):
+ _FOLDERS.append({"path": str(folder)})
+
+
[email protected](autouse = True)
+def _folders(monkeypatch):
+ _FOLDERS.clear()
+ monkeypatch.setattr(studio_db, "list_scan_folders", lambda: list(_FOLDERS))
+
+
+def catalog(tmp_path, monkeypatch):
+ d = tmp_path / "loras"
+ d.mkdir()
+ monkeypatch.setattr(dl, "loras_dir", lambda: d)
+ return d
+
+
+def _local():
+ return {e.id: e for e in dl.list_loras() if e.source == "local"}
+
+
+def _by_path(path):
+ return next(e for e in _local().values() if e.local_path == str(path))
+
+
+def test_an_export_in_a_custom_folder_is_listed(catalog, tmp_path):
+ (catalog / "mystyle.safetensors").write_bytes(b"w")
+ (catalog / "mystyle.json").write_text(
+ json.dumps({"family": "sdxl", "source": "studio-trained"})
+ )
+ folder = tmp_path / "my-models"
+ dl.export_local_lora("mystyle", folder / "image-loras")
+ (catalog / "mystyle.safetensors").unlink()
+ (catalog / "mystyle.json").unlink()
+ register(str(folder))
+
+ entry = _by_path(folder / "image-loras" / "mystyle.safetensors")
+ assert entry.display_name == "mystyle" and entry.id.startswith("mystyle-")
+ assert entry.families == ("sdxl",) and entry.fine_tuned
+ assert dl.resolve_one(entry.id, 1.0).path == entry.local_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"})
+ register(str(folder))
+ assert _local() == {}
+
+
+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")]
+ for folder in folders:
+ _safetensors(folder / "style.safetensors", sidecar = _MARK)
+ register(str(folder))
+ assert _local()["style"].local_path == str(catalog / "style.safetensors")
+ ids = {str(f): _by_path(f / "style.safetensors").id for f in folders}
+ assert len(set(ids.values())) == 3 and not _by_path(folders[2] / "style.safetensors").fine_tuned
+
+ _FOLDERS.pop(0)
+ for folder in folders[1:]:
+ assert _by_path(folder / "style.safetensors").id == ids[str(folder)]
+ assert ids[str(folders[0])] not in _local()
+
+
+def test_the_catalog_registered_as_a_custom_folder_is_not_listed_twice(catalog, tmp_path):
+ _safetensors(catalog / "style.safetensors", sidecar = _MARK)
+ register(str(catalog))
+ assert list(_local()) == ["style"]
+
+
[email protected]("scanner", ["routes", "inventory"])
+def test_marked_loras_are_not_listed_as_models(tmp_path, scanner):
+ if scanner == "routes":
+ from routes.models import _scan_models_dir
+ else:
+ from hub.services.models.local_inventory import _scan_models_dir
+
+ folder = tmp_path / "image-loras"
+ _safetensors(folder / "a.safetensors", sidecar = _MARK)
+ _safetensors(folder / "b.safetensors", sidecar = {"source": "studio-trained"})
+ assert _scan_models_dir(folder) == []
+ assert _scan_models_dir(tmp_path) == []
+
+ _safetensors(tmp_path / "checkpoint" / "model.safetensors")
+ assert [row.display_name for row in _scan_models_dir(tmp_path)] == ["checkpoint"]
+
+
+def test_the_picker_route_reports_fine_tuned(catalog):
+ from routes.models import scan_diffusion_loras
+
+ _safetensors(catalog / "trained.safetensors", sidecar = {"source": "studio-trained", **_MARK})
+ _safetensors(catalog / "downloaded.safetensors")
+ rows = asyncio.run(scan_diffusion_loras(family = None, current_subject = "subject"))["loras"]
+ flags = {row["id"]: row["fine_tuned"] for row in rows if row["source"] == "local"}
+ assert flags == {"trained": True, "downloaded": False}
+
+
[email protected]("scanner", ["routes", "inventory"])
+def test_a_marked_gguf_in_a_subfolder_is_not_a_model(tmp_path, scanner):
+ if scanner == "routes":
+ from routes.models import _scan_models_dir
+ else:
+ from hub.services.models.local_inventory import _scan_models_dir
+
+ folder = tmp_path / "image-loras"
+ folder.mkdir()
+ (folder / "style.gguf").write_bytes(b"GGUF" + b"\0" * 60)
+ (folder / "style.json").write_text(json.dumps(_MARK))
+ assert _scan_models_dir(tmp_path) == []
+
+
+def test_a_managed_account_only_sees_custom_folder_loras_it_may_access(
+ catalog, tmp_path, monkeypatch
+):
+ from hub.services.models import account_access
+
+ folder = tmp_path / "shared"
+ _safetensors(folder / "style.safetensors", sidecar = _MARK)
+ register(str(folder))
+ monkeypatch.setattr(account_access, "managed_account", lambda: True)
+ monkeypatch.setattr(account_access, "model_visible", lambda reference, **_: False)
+ assert _local() == {}
+ with pytest.raises(FileNotFoundError):
+ dl.export_local_lora("style", tmp_path / "out")
+ with pytest.raises(FileNotFoundError):
+ dl.resolve_one("style", 1.0)
+
+
[email protected]("scanner", ["routes", "inventory"])
+def test_the_lmstudio_fallback_skips_marked_loras(tmp_path, scanner):
+ if scanner == "routes":
+ from routes.models import _scan_lmstudio_dir
+ else:
+ from hub.services.models.local_inventory import _scan_lmstudio_dir
+
+ for gguf in (tmp_path / "image-loras" / "style.gguf", tmp_path / "loose.gguf"):
+ gguf.parent.mkdir(parents = True, exist_ok = True)
+ gguf.write_bytes(b"GGUF" + b"\0" * 60)
+ gguf.with_suffix(".json").write_text(json.dumps(_MARK))
+ (tmp_path / "real.gguf").write_bytes(b"GGUF" + b"\0" * 60)
+ assert [row.display_name for row in _scan_lmstudio_dir(tmp_path)] == ["real"]
+
+
+def test_stacked_loras_share_one_custom_folder_scan(catalog, tmp_path, monkeypatch):
+ for name in ("a", "b", "c"):
+ (catalog / f"{name}.safetensors").write_bytes(b"w")
+ calls = []
+ real = dl._scan_folder_roots
+ monkeypatch.setattr(dl, "_scan_folder_roots", lambda: calls.append(1) or real())
+ resolved = dl.resolve_specs([("a", 1.0), ("b", 0.5), ("c", 0.8)])
+ assert [r.path for r in resolved] == [str(catalog / f"{n}.safetensors") for n in "abc"]
+ assert len(calls) == 1
+
+
[email protected](os.name == "nt", reason = "symlinks need a privilege on Windows")
+def test_a_managed_account_cannot_reach_out_through_a_catalog_symlink(
+ catalog, tmp_path, monkeypatch
+):
+ from hub.services.models import account_access
+
+ secret = tmp_path / "elsewhere" / "secret.safetensors"
+ _safetensors(secret, sidecar = _MARK)
+ (catalog / "link.safetensors").symlink_to(secret)
+ (catalog / "own.safetensors").write_bytes(b"w")
+ monkeypatch.setattr(account_access, "managed_account", lambda: True)
+ monkeypatch.setattr(
+ account_access,
+ "model_visible",
+ lambda reference, **_: str(catalog) in os.path.realpath(reference),
+ )
+ assert list(_local()) == ["own"]
+ with pytest.raises(FileNotFoundError):
+ dl.export_local_lora("link", tmp_path / "out")
+
+
[email protected](os.name == "nt", reason = "POSIX byte filenames")
+def test_a_non_utf8_filename_does_not_break_the_scan(catalog, tmp_path):
+ folder = tmp_path / "my-models"
+ folder.mkdir()
+ name = os.fsdecode(b"st\xffyle.safetensors")
+ try:
+ _safetensors(folder / name, sidecar = _MARK)
+ except OSError:
+ pytest.skip("this filesystem refuses non-UTF-8 names (APFS)")
+ register(folder)
+ assert [e.local_path for e in _local().values()] == [str(folder / name)]
+
+
+def test_generation_rechecks_access_on_resolve(catalog, monkeypatch):
+ from hub.services.models import account_access
+
+ (catalog / "own.safetensors").write_bytes(b"w")
+ catalog_snapshot = dl._catalog_by_id()
+ monkeypatch.setattr(account_access, "managed_account", lambda: True)
+ monkeypatch.setattr(account_access, "model_visible", lambda reference, **_: False)
+ with pytest.raises(FileNotFoundError):
+ dl.resolve_one("own", 1.0, catalog = catalog_snapshot)
+
+
+def test_a_marked_gguf_beside_a_model_is_not_a_variant(tmp_path):
+ from hub.services.models.common import _main_gguf_files
+
+ (tmp_path / "config.json").write_text("{}")
+ (tmp_path / "model-Q4_K_M.gguf").write_bytes(b"GGUF" + b"\0" * 60)
+ (tmp_path / "style.gguf").write_bytes(b"GGUF" + b"\0" * 60)
+ (tmp_path / "style.json").write_text(json.dumps(_MARK))
+ assert [p.name for p in _main_gguf_files(tmp_path)] == ["model-Q4_K_M.gguf"]
+
+
+def test_a_config_with_only_a_marked_safetensors_is_not_a_model(tmp_path):
+ from hub.services.models.local_inventory import _scan_models_dir
+
+ folder = tmp_path / "loras-with-config"
+ folder.mkdir()
+ (folder / "config.json").write_text("{}")
+ _safetensors(folder / "style.safetensors", sidecar = _MARK)
+ rows = _scan_models_dir(tmp_path)
+ assert all(getattr(r, "model_format", None) != "safetensors" for r in rows)
+
+
+def test_an_unreadable_entry_does_not_fail_the_catalog(catalog, tmp_path, monkeypatch):
+ from pathlib import Path
+
+ folder = tmp_path / "my-models"
+ _safetensors(folder / "good.safetensors", sidecar = _MARK)
+ _safetensors(folder / "locked.safetensors", sidecar = _MARK)
+ register(folder)
+ real_is_file = Path.is_file
+
+ def is_file(self):
+ if self.name == "locked.safetensors":
+ raise PermissionError(13, "Permission denied")
+ return real_is_file(self)
+
+ monkeypatch.setattr(Path, "is_file", is_file)
+ assert [e.display_name for e in _local().values()] == ["good"]
+
+
+def test_an_unreadable_sibling_keeps_the_root_listed(catalog, tmp_path, monkeypatch):
+ from pathlib import Path
+
+ folder = tmp_path / "my-models"
+ _safetensors(folder / "good.safetensors", sidecar = _MARK)
+ (folder / "locked").mkdir()
+ register(folder)
+ real_is_dir = Path.is_dir
+
+ def is_dir(self):
+ if self.name == "locked":
+ raise PermissionError(13, "Permission denied")
+ return real_is_dir(self)
+
+ monkeypatch.setattr(Path, "is_dir", is_dir)
+ assert [e.display_name for e in _local().values()] == ["good"]
diff --git a/studio/backend/tests/test_diffusion_lora_trainer.py b/studio/backend/tests/test_diffusion_lora_trainer.py
index b6089058414..651e7824f77 100644
--- a/studio/backend/tests/test_diffusion_lora_trainer.py
+++ b/studio/backend/tests/test_diffusion_lora_trainer.py
@@ -590,6 +590,7 @@ def test_publish_writes_metadata_sidecar(tmp_path, monkeypatch):
assert meta["lora_rank"] == 8
assert meta["trigger_prompt"] == "a photo in sks style"
assert meta["source"] == "studio-trained"
+ assert meta["kind"] == "diffusion-lora"
def test_publish_does_not_clobber_same_name_adapter(tmp_path, monkeypatch):
diff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.py
index 7b46336a275..48f1d276051 100644
--- a/studio/backend/tests/test_export_absolute_paths.py
+++ b/studio/backend/tests/test_export_absolute_paths.py
@@ -214,6 +214,7 @@ def _install_lightweight_backend_stubs(monkeypatch):
"ExportBaseModelRequest",
"ExportGGUFRequest",
"ConvertQ4NXRequest",
+ "ExportDiffusionLoRARequest",
"ExportLoRAAdapterRequest",
"LlmCompressorExportProbeResponse",
"ExportDecisionInfoResponse",
diff --git a/studio/backend/tests/test_export_diffusion_lora.py b/studio/backend/tests/test_export_diffusion_lora.py
new file mode 100644
index 00000000000..e93b2a7464e
--- /dev/null
+++ b/studio/backend/tests/test_export_diffusion_lora.py
@@ -0,0 +1,230 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Image-generation LoRAs can be exported from the Images catalog to a folder."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+from core.inference import diffusion_lora as dl
+from models import ExportDiffusionLoRARequest
+from routes import export as export_routes
+
+
+def loras(tmp_path, monkeypatch):
+ d = tmp_path / "loras"
+ d.mkdir()
+ (d / "mystyle.safetensors").write_bytes(b"weights")
+ (d / "mystyle.json").write_text(json.dumps({"family": "sdxl", "source": "studio-trained"}))
+ (d / "bare.safetensors").write_bytes(b"bare")
+ monkeypatch.setattr(dl, "loras_dir", lambda: d)
+ return d
+
+
+def test_export_copies_weights_and_a_marked_sidecar(loras, tmp_path):
+ out = dl.export_local_lora("mystyle", tmp_path / "out")
+ assert out == tmp_path / "out" / "mystyle.safetensors"
+ assert out.read_bytes() == b"weights"
+ meta = json.loads(out.with_suffix(".json").read_text())
+ assert meta == {"family": "sdxl", "source": "studio-trained", "kind": "diffusion-lora"}
+ assert dl.is_image_lora_file(out)
+ assert (loras / "mystyle.safetensors").is_file()
+
+
+def test_export_without_sidecar_still_writes_the_marker(loras, tmp_path):
+ out = dl.export_local_lora("bare", tmp_path / "out")
+ assert out.read_bytes() == b"bare"
+ assert json.loads(out.with_suffix(".json").read_text()) == {"kind": "diffusion-lora"}
+
+
+def test_export_into_the_catalog_itself_keeps_the_file(loras):
+ out = dl.export_local_lora("mystyle", loras)
+ assert out.read_bytes() == b"weights"
+ assert json.loads(out.with_suffix(".json").read_text())["family"] == "sdxl"
+
+
+def test_export_never_overwrites_other_files(loras, tmp_path):
+ out_dir = tmp_path / "shared"
+ out_dir.mkdir()
+ (out_dir / "mystyle.safetensors").write_bytes(b"another install")
+ (out_dir / "mystyle.json").write_text(json.dumps({"kind": "diffusion-lora"}))
+ (out_dir / "bare.json").write_text('{"model_type": "llama"}')
+ assert dl.export_local_lora("mystyle", out_dir) == out_dir / "mystyle-2.safetensors"
+ assert (out_dir / "mystyle.safetensors").read_bytes() == b"another install"
+ assert dl.export_local_lora("bare", out_dir) == out_dir / "bare-2.safetensors"
+ assert json.loads((out_dir / "bare.json").read_text()) == {"model_type": "llama"}
+ # Re-exporting the same bytes reuses its slot instead of piling up copies.
+ assert dl.export_local_lora("mystyle", out_dir) == out_dir / "mystyle-2.safetensors"
+
+
+def test_export_never_shares_a_sidecar_with_another_format(loras, tmp_path):
+ out_dir = tmp_path / "shared"
+ out_dir.mkdir()
+ (out_dir / "mystyle.gguf").write_bytes(b"gguf")
+ (out_dir / "mystyle.json").write_text(json.dumps({"family": "flux", "kind": "diffusion-lora"}))
+ assert dl.export_local_lora("mystyle", out_dir) == out_dir / "mystyle-2.safetensors"
+ assert json.loads((out_dir / "mystyle.json").read_text())["family"] == "flux"
+
+
+def test_a_failed_copy_leaves_nothing_behind(loras, tmp_path, monkeypatch):
+ import shutil
+
+ def boom(fsrc, fdst, *_):
+ fdst.write(b"half")
+ raise OSError("disk full")
+
+ monkeypatch.setattr(shutil, "copyfileobj", boom)
+ with pytest.raises(OSError):
+ dl.export_local_lora("mystyle", tmp_path / "out")
+ assert list((tmp_path / "out").iterdir()) == []
+
+
+def test_a_failed_sidecar_write_leaves_nothing_behind(loras, tmp_path, monkeypatch):
+ real_replace = os.replace
+
+ def boom(src, dst):
+ if str(dst).endswith(".json"):
+ raise OSError("disk full")
+ real_replace(src, dst)
+
+ monkeypatch.setattr(os, "replace", boom)
+ with pytest.raises(OSError):
+ dl.export_local_lora("mystyle", tmp_path / "out")
+ assert list((tmp_path / "out").iterdir()) == []
+
+
+def test_the_marker_is_published_before_the_weight(loras, tmp_path, monkeypatch):
+ real_replace = os.replace
+
+ def checked(src, dst):
+ if str(dst).endswith(".safetensors"):
+ assert Path(dst).with_suffix(".json").is_file()
+ real_replace(src, dst)
+
+ monkeypatch.setattr(os, "replace", checked)
+ out = dl.export_local_lora("mystyle", tmp_path / "out")
+ assert dl.is_image_lora_file(out)
+
+
+def test_export_never_writes_a_model_sentinel_json(loras, tmp_path):
+ (loras / "config.safetensors").write_bytes(b"w")
+ out = dl.export_local_lora("config", tmp_path / "out")
+ assert out.name == "config-2.safetensors"
+ assert not (tmp_path / "out" / "config.json").exists()
+
+
[email protected](os.name != "posix", reason = "POSIX modes")
+def test_the_marker_gets_the_umask_mode(loras, tmp_path):
+ old = os.umask(0o022)
+ try:
+ out = dl.export_local_lora("mystyle", tmp_path / "out")
+ finally:
+ os.umask(old)
+ assert out.with_suffix(".json").stat().st_mode & 0o777 == 0o644
+
+
+def test_a_sentinel_stem_is_suffixed_even_in_its_own_folder(loras):
+ (loras / "config.safetensors").write_bytes(b"w")
+ assert dl.export_local_lora("config", loras).name == "config-2.safetensors"
+ assert not (loras / "config.json").exists()
+
+
+def test_a_case_variant_sibling_keeps_its_stem(loras, tmp_path):
+ out_dir = tmp_path / "shared"
+ out_dir.mkdir()
+ (out_dir / "mystyle.GGUF").write_bytes(b"model")
+ assert dl.export_local_lora("mystyle", out_dir).name == "mystyle-2.safetensors"
+ assert not (out_dir / "mystyle.json").exists()
+
+
+def test_a_source_swapped_after_the_scan_is_refused(loras, tmp_path, monkeypatch):
+ other = tmp_path / "other.safetensors"
+ other.write_bytes(b"someone else")
+ real_realpath = os.path.realpath
+ # The handle is opened on the catalog file, then the path resolves elsewhere: identities differ.
+ monkeypatch.setattr(
+ os.path,
+ "realpath",
+ lambda p, *a, **k: str(other)
+ if str(p).endswith("mystyle.safetensors") and "out" not in str(p)
+ else real_realpath(p, *a, **k),
+ )
+ with pytest.raises(FileNotFoundError):
+ dl.export_local_lora("mystyle", tmp_path / "out")
+ assert not (tmp_path / "out" / "mystyle.safetensors").exists()
+
+
+def test_the_copy_keeps_the_source_mode_and_mtime(loras, tmp_path):
+ src = loras / "mystyle.safetensors"
+ os.utime(src, (1_000_000, 1_000_000))
+ out = dl.export_local_lora("mystyle", tmp_path / "out")
+ assert out.stat().st_mtime == 1_000_000
+ assert out.stat().st_mode & 0o777 == src.stat().st_mode & 0o777
+
+
+def test_an_exported_gguf_lora_is_not_an_exported_chat_model(loras, tmp_path):
+ from utils.models.model_config import scan_exported_models
+ from utils.paths.storage_roots import exports_root
+
+ run = exports_root() / "image-loras"
+ run.mkdir(parents = True, exist_ok = True)
+ (run / "style.gguf").write_bytes(b"GGUF" + b"\0" * 60)
+ (run / "style.json").write_text(json.dumps({"kind": "diffusion-lora"}))
+ assert "image-loras" not in [r[0] for r in scan_exported_models()]
+ (run / "style.json").unlink()
+ assert "image-loras" in [r[0] for r in scan_exported_models()]
+
+ nested = exports_root() / "run" / "image-loras"
+ nested.mkdir(parents = True, exist_ok = True)
+ (nested / "style.gguf").write_bytes(b"GGUF" + b"\0" * 60)
+ (nested / "style.json").write_text(json.dumps({"kind": "diffusion-lora"}))
+ assert str(nested / "style.gguf") not in [r[1] for r in scan_exported_models()]
+
+
+def test_a_sibling_differing_only_in_case_keeps_its_stem(loras, tmp_path):
+ out_dir = tmp_path / "shared"
+ out_dir.mkdir()
+ (out_dir / "MYSTYLE.gguf").write_bytes(b"model")
+ assert dl.export_local_lora("mystyle", out_dir).name == "mystyle-2.safetensors"
+
+
+def test_a_long_stem_still_exports(loras, tmp_path):
+ stem = "a" * 233
+ (loras / f"{stem}.safetensors").write_bytes(b"w")
+ assert dl.export_local_lora(stem, tmp_path / "out").name == f"{stem}.safetensors"
+
+
+def test_export_refuses_ids_outside_the_local_catalog(loras, tmp_path):
+ secret = tmp_path / "secret.safetensors"
+ secret.write_bytes(b"secret")
+ for lora_id in ("missing", str(secret), "../secret", "krea/Krea-2-LoRA-retroanime"):
+ with pytest.raises(FileNotFoundError):
+ dl.export_local_lora(lora_id, tmp_path / "out")
+ assert not (tmp_path / "out" / "secret.safetensors").exists()
+
+
+def _export(lora_id, save_directory):
+ request = ExportDiffusionLoRARequest(lora_id = lora_id, save_directory = str(save_directory))
+ return asyncio.run(export_routes.export_diffusion_lora(request, "subject"))
+
+
+def test_route_returns_the_saved_path(loras, tmp_path):
+ response = _export("mystyle", tmp_path / "exported")
+ assert response.success
+ saved = tmp_path / "exported" / "mystyle.safetensors"
+ assert saved.read_bytes() == b"weights"
+ assert response.details == {"output_path": str(saved.resolve())}
+
+
+def test_route_maps_an_unknown_lora_to_404(loras, tmp_path):
+ with pytest.raises(HTTPException) as exc:
+ _export("missing", tmp_path / "exported")
+ assert exc.value.status_code == 404
diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.py
index c326be46243..e32805f3cfe 100644
--- a/studio/backend/utils/models/model_config.py
+++ b/studio/backend/utils/models/model_config.py
@@ -3949,6 +3949,8 @@ def scan_exported_models(
if exports_dir is None:
exports_dir = str(exports_root())
+ from core.inference.diffusion_lora import is_image_lora_file
+
results = []
exports_path = resolve_export_dir(exports_dir)
@@ -3965,7 +3967,9 @@ def scan_exported_models(
gguf_files = [
f
for f in _iter_gguf_files(run_dir)
- if not _is_mmproj(f.name) and not _is_imatrix_path(f.name)
+ if not _is_mmproj(f.name)
+ and not _is_imatrix_path(f.name)
+ and not is_image_lora_file(f)
]
if gguf_files:
base_model = None
@@ -3998,7 +4002,9 @@ def scan_exported_models(
gguf_list = [
f
for f in _iter_gguf_files(checkpoint_dir)
- if not _is_mmproj(f.name) and not _is_imatrix_path(f.name)
+ if not _is_mmproj(f.name)
+ and not _is_imatrix_path(f.name)
+ and not is_image_lora_file(f)
]
has_gguf = bool(gguf_list)
diff --git a/studio/frontend/src/features/export/api/export-api.ts b/studio/frontend/src/features/export/api/export-api.ts
index d7af9ac7d9e..a201fdf9513 100644
--- a/studio/frontend/src/features/export/api/export-api.ts
+++ b/studio/frontend/src/features/export/api/export-api.ts
@@ -237,6 +237,19 @@ export async function convertGgufToQ4nx(params: {
return parseJson<ExportOperationResponse>(response);
}
+/** Copy an image-generation LoRA from the Images catalog (weights plus its .json sidecar) to a folder. */
+export async function exportDiffusionLora(params: {
+ lora_id: string;
+ save_directory: string;
+}): Promise<ExportOperationResponse> {
+ const response = await authFetch("/api/export/export/diffusion-lora", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(params),
+ });
+ return parseJson<ExportOperationResponse>(response);
+}
+
export async function exportLoRA(params: {
save_directory: string;
push_to_hub?: boolean;
diff --git a/studio/frontend/src/features/export/components/image-lora-export-card.tsx b/studio/frontend/src/features/export/components/image-lora-export-card.tsx
new file mode 100644
index 00000000000..00b3741a6ad
--- /dev/null
+++ b/studio/frontend/src/features/export/components/image-lora-export-card.tsx
@@ -0,0 +1,148 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { SectionCard } from "@/components/section-card";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Spinner } from "@/components/ui/spinner";
+import {
+ type DiffusionLoraInfo,
+ listDiffusionLoras,
+} from "@/features/images/api";
+import { ImageAdd02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useEffect, useState } from "react";
+import { exportDiffusionLora } from "../api/export-api";
+
+function imageLoraLabel(lora: DiffusionLoraInfo, clashes: boolean): string {
+ const tags = [...lora.families, ...(lora.fine_tuned ? ["fine-tuned"] : [])];
+ const name = clashes ? `${lora.display_name} [${lora.id}]` : lora.display_name;
+ return tags.length > 0 ? `${name} (${tags.join(", ")})` : name;
+}
+
+export function ImageLoraExportCard() {
+ const [loras, setLoras] = useState<DiffusionLoraInfo[] | null>(null);
+ const [loraId, setLoraId] = useState("");
+ const [saveDirectory, setSaveDirectory] = useState("image-loras");
+ const [running, setRunning] = useState(false);
+ const [result, setResult] = useState<{ ok: boolean; text: string } | null>(
+ null,
+ );
+
+ useEffect(() => {
+ let cancelled = false;
+ listDiffusionLoras()
+ // Only adapters on disk: curated hub entries are already downloadable from their repo.
+ .then((list) => {
+ if (!cancelled) {
+ setLoras(list.filter((l) => l.source === "local"));
+ }
+ })
+ .catch(() => {
+ if (!cancelled) {
+ setLoras([]);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ const canExport = !running && loraId !== "" && saveDirectory.trim() !== "";
+
+ async function handleExport() {
+ setRunning(true);
+ setResult(null);
+ try {
+ const response = await exportDiffusionLora({
+ lora_id: loraId,
+ save_directory: saveDirectory.trim(),
+ });
+ setResult({
+ ok: true,
+ text: `Saved to ${response.details?.output_path ?? saveDirectory}`,
+ });
+ } catch (error) {
+ setResult({
+ ok: false,
+ text: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setRunning(false);
+ }
+ }
+
+ return (
+ <SectionCard
+ icon={<HugeiconsIcon icon={ImageAdd02Icon} className="size-5" />}
+ title="Export an image LoRA"
+ description="Save a copy of an image generation LoRA you trained (or added) on the Images page: the .safetensors adapter plus its .json metadata. Any Unsloth install lists it again from a custom models folder."
+ className="mt-6"
+ >
+ <div className="grid gap-4 sm:grid-cols-2">
+ <div className="space-y-1.5">
+ <label htmlFor="image-lora-id" className="text-sm font-medium">
+ Image LoRA
+ </label>
+ <Select value={loraId} onValueChange={setLoraId}>
+ <SelectTrigger id="image-lora-id" className="w-full">
+ <SelectValue
+ placeholder={
+ loras === null
+ ? "Loading…"
+ : loras.length === 0
+ ? "No image LoRAs found"
+ : "Select an image LoRA…"
+ }
+ />
+ </SelectTrigger>
+ <SelectContent>
+ {(loras ?? []).map((l) => (
+ <SelectItem key={l.id} value={l.id}>
+ {imageLoraLabel(
+ l,
+ (loras ?? []).some(
+ (o) => o.id !== l.id && o.display_name === l.display_name,
+ ),
+ )}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="space-y-1.5">
+ <label htmlFor="image-lora-save" className="text-sm font-medium">
+ Save directory
+ </label>
+ <Input
+ id="image-lora-save"
+ value={saveDirectory}
+ onChange={(e) => setSaveDirectory(e.target.value)}
+ />
+ </div>
+ </div>
+ <div className="flex items-center justify-between gap-3">
+ <p
+ className={
+ result?.ok === false
+ ? "text-xs text-destructive"
+ : "text-xs text-muted-foreground"
+ }
+ >
+ {result?.text ?? "A plain file copy: no model load or GPU needed."}
+ </p>
+ <Button disabled={!canExport} onClick={handleExport}>
+ {running && <Spinner />}
+ Export
+ </Button>
+ </div>
+ </SectionCard>
+ );
+}
diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsx
index f43d23051a1..a55bfe064d9 100644
--- a/studio/frontend/src/features/export/export-page.tsx
+++ b/studio/frontend/src/features/export/export-page.tsx
@@ -71,6 +71,7 @@ import {
} from "./api/export-api";
import { adapterCompatibilityTip, type AdapterFormat } from "./constants";
import { ExportRunPanel } from "./components/export-run-panel";
+import { ImageLoraExportCard } from "./components/image-lora-export-card";
import { MethodPicker } from "./components/method-picker";
import { Q4nxConvertCard } from "./components/q4nx-convert-card";
import { QuantPicker } from "./components/quant-picker";
@@ -2050,6 +2051,7 @@ export function ExportPage() {
</>
)}
</SectionCard>
+ <ImageLoraExportCard />
<Q4nxConvertCard />
</main>
</div>
diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.ts
index 59e5de6e90d..c5a0c40da55 100644
--- a/studio/frontend/src/features/images/api.ts
+++ b/studio/frontend/src/features/images/api.ts
@@ -241,6 +241,7 @@ export interface DiffusionLoraInfo {
families: string[];
size_bytes: number;
weight_default: number;
+ fine_tuned?: boolean;
}
// A persisted image's full generation recipe (also embedded in the PNG).
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 7cd6a9537a8..92209c6c7e2 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -20,6 +20,7 @@ import {
Refresh01Icon,
Delete02Icon,
Download01Icon,
+ FolderAddIcon,
Image03Icon,
ImageAdd02Icon,
InformationCircleIcon,
@@ -151,6 +152,7 @@ import {
} from "@/features/generation-presets";
import { getHfToken, hfApiToken } from "@/features/hub/stores/hf-token-store";
import { formatBytes, formatEta } from "@/features/hub/lib/format";
+import { OnDeviceFoldersDialog } from "@/features/hub/catalog/on-device-folders-dialog";
import { generatePhaseLabel, sameGenerateProgress } from "@/lib/media-generate-phase";
import { ChevronDown } from "lucide-react";
import { NegativePromptField } from "@/components/negative-prompt-field";
@@ -1566,6 +1568,7 @@ export function ImagesPage({
const [trainBaseChoice, setTrainBaseChoice] = useState("");
// Bumped when a training run completes, so the LoRA discovery effect rescans without a model reload.
const [loraRefreshKey, setLoraRefreshKey] = useState(0);
+ const [loraFoldersOpen, setLoraFoldersOpen] = useState(false);
// ControlNet for the next generation: model id, control image, how to derive the map, and the strength.
const [controlnetId, setControlnetId] = useState<string>("");
const [controlImage, setControlImage] = useState<string | null>(null);
@@ -5462,11 +5465,14 @@ export function ImagesPage({
<div className="space-y-2">
{availableLoras.length > 0 && (
<datalist id="diffusion-lora-suggestions">
- {availableLoras.map((a) => (
- <option key={a.id} value={a.id}>
- {a.display_name}
- </option>
- ))}
+ {/* A datalist has no groups, so the label carries the fine-tuned mark. */}
+ {[...availableLoras]
+ .sort((a, b) => Number(Boolean(b.fine_tuned)) - Number(Boolean(a.fine_tuned)))
+ .map((a) => (
+ <option key={a.id} value={a.id}>
+ {a.fine_tuned ? `${a.display_name} (fine-tuned)` : a.display_name}
+ </option>
+ ))}
</datalist>
)}
{loras.map((sel, i) => (
@@ -5515,27 +5521,44 @@ export function ImagesPage({
/>
</div>
))}
- {loras.length < 8 && (
+ <div className="flex gap-2">
+ {loras.length < 8 && (
+ <Button
+ type="button"
+ variant="secondary"
+ size="sm"
+ className="flex-1"
+ onClick={() => {
+ // Prefill with the first unused suggestion when a curated catalog exists, else an empty row.
+ const taken = new Set(loras.map((l) => l.id));
+ const next = availableLoras.find((a) => !taken.has(a.id));
+ setLoras((prev) => [
+ ...prev,
+ next ? { id: next.id, weight: next.weight_default || 1 } : { id: "", weight: 1 },
+ ]);
+ }}
+ >
+ <HugeiconsIcon icon={ImageAdd02Icon} className="size-3.5" />
+ Add LoRA
+ </Button>
+ )}
<Button
type="button"
- variant="secondary"
+ variant="ghost"
size="sm"
- className="w-full"
- onClick={() => {
- // Prefill with the first unused suggestion when a curated catalog exists, else an empty row.
- const taken = new Set(loras.map((l) => l.id));
- const next = availableLoras.find((a) => !taken.has(a.id));
- setLoras((prev) => [
- ...prev,
- next ? { id: next.id, weight: next.weight_default || 1 } : { id: "", weight: 1 },
- ]);
- }}
+ title="Add a custom models folder. Image LoRAs exported from Unsloth in it show up here."
+ onClick={() => setLoraFoldersOpen(true)}
>
- <HugeiconsIcon icon={ImageAdd02Icon} className="size-3.5" />
- Add LoRA
+ <HugeiconsIcon icon={FolderAddIcon} className="size-3.5" />
+ Folders
</Button>
- )}
+ </div>
</div>
+ <OnDeviceFoldersDialog
+ open={loraFoldersOpen}
+ onOpenChange={setLoraFoldersOpen}
+ onInventoryChange={() => setLoraRefreshKey((k) => k + 1)}
+ />
</Field>
)}
{/* ControlNet: shown when the model supports it, one is discoverable, and txt2img is active. */}