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
Unsloth Studio: export a trained image LoRA from the Train tab, list exported copies once (#13289)
Daniel Hane5bae1a47c47
diff --git a/studio/backend/core/inference/diffusion_lora.py b/studio/backend/core/inference/diffusion_lora.pyindex ca487226666..ee5af6bbfe6 100644--- a/studio/backend/core/inference/diffusion_lora.py+++ b/studio/backend/core/inference/diffusion_lora.py@@ -59,6 +59,8 @@ class LoraCatalogEntry:size_bytes: int = 0weight_default: float = 1.0fine_tuned: bool = False+ # Id of the loras/diffusion adapter this custom-folder file is an export of: listed once, still resolvable.+ copy_of: Optional[str] = None@dataclass(frozen = True)@@ -240,11 +242,25 @@ def _scan_local() -> list[LoraCatalogEntry]:found.append((p, entry_id))entries: list[LoraCatalogEntry] = []+ # An export carries its source's sidecar plus ``kind``. Only trainer sidecars (``created_at``) qualify, and the+ # bytes at both ends must match too: equal size and metadata alone fit two different same-rank LoRAs.+ originals: dict[tuple, tuple[str, Path]] = {}for p, entry_id in found:try:size = p.stat().st_sizeexcept OSError:size = 0+ sidecar = _sidecar_data(p) or {}+ meta = {k: v for k, v in sidecar.items() if k != "kind"}+ signature = (+ (size, json.dumps(meta, sort_keys = True, default = str)) if "created_at" in meta else None+ )+ copy_of = None+ if p.parent == root_dir:+ if signature:+ originals.setdefault(signature, (entry_id, p))+ elif signature in originals and _same_ends(originals[signature][1], p):+ copy_of = originals[signature][0]# 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)@@ -258,12 +274,29 @@ def _scan_local() -> list[LoraCatalogEntry]:size_bytes = size,families = families,weight_default = weight_default,- fine_tuned = (_sidecar_data(p) or {}).get("source") == "studio-trained",+ fine_tuned = sidecar.get("source") == "studio-trained",+ copy_of = copy_of,))return entries+def _same_ends(+ a: Path,+ b: Path,+ n: int = 1 << 16,+) -> bool:+ try:+ with _open_pinned(a) as fa, _open_pinned(b) as fb:+ if fa.read(n) != fb.read(n):+ return False+ for f in (fa, fb):+ f.seek(max(0, os.fstat(f.fileno()).st_size - n))+ return fa.read(n) == fb.read(n)+ except OSError:+ return False++def _sidecar_data(weight_path: Path) -> Optional[dict]:try:data = json.loads(weight_path.with_suffix(".json").read_text(encoding = "utf-8"))@@ -303,13 +336,15 @@ def _read_lora_sidecar(weight_path: Path) -> tuple[tuple[str, ...], float]:return tuple(names), weight_default-def list_loras(*, family: Optional[str] = None) -> list[LoraCatalogEntry]:+def list_loras(+ *, family: Optional[str] = None, include_copies: bool = False+) -> list[LoraCatalogEntry]:"""The merged catalog (curated + local), optionally family-filtered.Cheap: one directory scan plus the in-memory curated list. Network is only touched onresolve(), when a hub adapter is selected."""- merged = list(_CURATED) + _scan_local()+ merged = [e for e in list(_CURATED) + _scan_local() if include_copies or not e.copy_of]if family:fam = family.strip().lower()merged = [e for e in merged if not e.families or fam in {f.lower() for f in e.families}]diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex 4c569393efd..b391d0a0525 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -1006,7 +1006,9 @@ def media_adapter_references(request) -> list[str]:groups = []if loras:from core.inference import diffusion_lora- groups.append((loras, diffusion_lora.list_loras()))++ # Copies are hidden from the listing but resolve by id, so they must authorize by their path.+ groups.append((loras, diffusion_lora.list_loras(include_copies = True)))if controlnet:from core.inference import diffusion_controlnetgroups.append(([controlnet], diffusion_controlnet.list_controlnets()))diff --git a/studio/backend/tests/test_diffusion_lora_scan_folders.py b/studio/backend/tests/test_diffusion_lora_scan_folders.pyindex 2c4cde6dbb8..13d931ede8c 100644--- a/studio/backend/tests/test_diffusion_lora_scan_folders.py+++ b/studio/backend/tests/test_diffusion_lora_scan_folders.py@@ -292,3 +292,66 @@ def test_an_unreadable_sibling_keeps_the_root_listed(catalog, tmp_path, monkeypamonkeypatch.setattr(Path, "is_dir", is_dir)assert [e.display_name for e in _local().values()] == ["good"]+++def test_an_export_of_a_listed_adapter_is_listed_once(catalog, tmp_path):+ meta = {"family": "sdxl", "source": "studio-trained", "created_at": 1.5, **_MARK}+ _safetensors(catalog / "mystyle.safetensors", sidecar = meta)+ folder = tmp_path / "my-models"+ out = dl.export_local_lora("mystyle", folder / "image-loras")+ register(folder)+ assert list(_local()) == ["mystyle"]+ copy = next(e for e in dl._scan_local() if e.copy_of)+ assert copy.copy_of == "mystyle" and copy.local_path == str(out)+ # Still resolvable, so a recipe saved with the copy's id keeps working.+ assert dl.resolve_one(copy.id, 1.0).path == str(out)+ # Account checks see the copy's own path, not its bare id.+ from types import SimpleNamespace+ from hub.services.models.account_access import media_adapter_references++ request = SimpleNamespace(loras = [SimpleNamespace(id = copy.id)], controlnet = None)+ assert media_adapter_references(request) == [str(out)]+++def test_same_sized_adapters_without_metadata_are_not_collapsed(catalog, tmp_path):+ _safetensors(catalog / "a.safetensors")+ folder = tmp_path / "my-models"+ _safetensors(folder / "b.safetensors", sidecar = _MARK)+ register(folder)+ assert len(_local()) == 2+++def test_a_different_training_run_with_the_same_name_is_not_a_copy(catalog, tmp_path):+ _safetensors(+ catalog / "style.safetensors", sidecar = {"source": "studio-trained", "created_at": 1.0}+ )+ folder = tmp_path / "my-models"+ _safetensors(+ folder / "style.safetensors",+ sidecar = {"source": "studio-trained", "created_at": 2.0, **_MARK},+ )+ register(folder)+ assert len(_local()) == 2+++def test_a_same_layout_adapter_with_other_weights_is_not_a_copy(catalog, tmp_path):+ meta = {"family": "sdxl", "source": "studio-trained", "created_at": 1.5}+ (catalog / "style.safetensors").write_bytes(b"A" * 200_000)+ (catalog / "style.json").write_text(json.dumps(meta))+ folder = tmp_path / "my-models"+ folder.mkdir()+ (folder / "style.safetensors").write_bytes(b"A" * 100_000 + b"B" * 100_000)+ (folder / "style.json").write_text(json.dumps({**meta, **_MARK}))+ register(folder)+ assert len(_local()) == 2+++def test_hand_written_metadata_never_collapses(catalog, tmp_path):+ (catalog / "style.safetensors").write_bytes(b"w" * 10)+ (catalog / "style.json").write_text(json.dumps({"family": "sdxl"}))+ folder = tmp_path / "my-models"+ folder.mkdir()+ (folder / "style.safetensors").write_bytes(b"w" * 10)+ (folder / "style.json").write_text(json.dumps({"family": "sdxl", **_MARK}))+ register(folder)+ assert len(_local()) == 2diff --git a/studio/frontend/src/app/routes/export.tsx b/studio/frontend/src/app/routes/export.tsxindex 5a7b586f19a..f0676cf20c1 100644--- a/studio/frontend/src/app/routes/export.tsx+++ b/studio/frontend/src/app/routes/export.tsx@@ -14,6 +14,8 @@ export type ExportSearch = {// Preselect a training run on the Export page (its output-dir basename, which// equals the checkpoint scan's model name). Set when arriving from a run view.run?: string;+ // Preselect an image LoRA (its loras/diffusion file name) in the image LoRA card, from Images > Train.+ imageLora?: string;};export const Route = createRoute({@@ -23,6 +25,8 @@ export const Route = createRoute({beforeLoad: () => requireAuth(),validateSearch: (search: Record<string, unknown>): ExportSearch => ({run: typeof search.run === "string" ? search.run : undefined,+ imageLora:+ typeof search.imageLora === "string" ? search.imageLora : undefined,}),component: ExportPage,});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.tsxindex 00b3741a6ad..8ae2a8cf156 100644--- a/studio/frontend/src/features/export/components/image-lora-export-card.tsx+++ b/studio/frontend/src/features/export/components/image-lora-export-card.tsx@@ -16,18 +16,22 @@ import {type DiffusionLoraInfo,listDiffusionLoras,} from "@/features/images/api";+import { matchCatalogId } from "@/features/images/train/diffusion-train-deploy";import { ImageAdd02Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { useEffect, useState } from "react";import { exportDiffusionLora } from "../api/export-api";+import { savedLabel } from "../constants";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;+ const name = clashes+ ? `${lora.display_name} [${lora.id}]`+ : lora.display_name;return tags.length > 0 ? `${name} (${tags.join(", ")})` : name;}-export function ImageLoraExportCard() {+export function ImageLoraExportCard({ preselect }: { preselect?: string }) {const [loras, setLoras] = useState<DiffusionLoraInfo[] | null>(null);const [loraId, setLoraId] = useState("");const [saveDirectory, setSaveDirectory] = useState("image-loras");@@ -55,6 +59,18 @@ export function ImageLoraExportCard() {};}, []);+ // From a finished image run: pick it and scroll here, since the text-model card above shows no runs.+ useEffect(() => {+ const id = preselect ? matchCatalogId(loras ?? [], preselect) : undefined;+ if (!id) {+ return;+ }+ setLoraId(id);+ document+ .getElementById("image-lora-id")+ ?.scrollIntoView({ behavior: "smooth", block: "center" });+ }, [preselect, loras]);+const canExport = !running && loraId !== "" && saveDirectory.trim() !== "";async function handleExport() {@@ -67,7 +83,7 @@ export function ImageLoraExportCard() {});setResult({ok: true,- text: `Saved to ${response.details?.output_path ?? saveDirectory}`,+ text: `Saved to ${savedLabel(String(response.details?.output_path ?? saveDirectory))}. To use it on another install, copy that folder over and add it from Images > LoRAs > Folders.`,});} catch (error) {setResult({diff --git a/studio/frontend/src/features/export/constants.ts b/studio/frontend/src/features/export/constants.tsindex 92f8af52151..8d0b0458948 100644--- a/studio/frontend/src/features/export/constants.ts+++ b/studio/frontend/src/features/export/constants.ts@@ -409,3 +409,8 @@ export function adapterCompatibilityTip("is required for GGUF adapter export.");}++// The image LoRA route reports a path relative to the exports folder unless the user typed an absolute one.+export function savedLabel(path: string): string {+ return /^([a-zA-Z]:[\\/]|[\\/])/.test(path) ? path : `exports/${path}`;+}diff --git a/studio/frontend/src/features/export/export-page.tsx b/studio/frontend/src/features/export/export-page.tsxindex 909d22a4193..081ed7ab05b 100644--- a/studio/frontend/src/features/export/export-page.tsx+++ b/studio/frontend/src/features/export/export-page.tsx@@ -349,7 +349,7 @@ export function ExportPage() {// Apply the ?run= deep link once its run appears in the checkpoint list: select the run and// default to GGUF. The main checkpoint is auto-selected below, after the model-change effect.- const { run: preselectRun } = useSearch({ from: "/export" });+ const { run: preselectRun, imageLora: preselectImageLora } = useSearch({ from: "/export" });const appliedRunRef = useRef<string | null>(null);useEffect(() => {if (!preselectRun) {@@ -2056,7 +2056,7 @@ export function ExportPage() {</>)}</SectionCard>- <ImageLoraExportCard />+ <ImageLoraExportCard preselect={preselectImageLora} /><Q4nxConvertCard /></main></div>diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 92209c6c7e2..e54b8dbf272 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -1550,6 +1550,11 @@ export function ImagesPage({// LoRA adapters selected for the next generation (id + weight), plus the list the picker offers.const [loras, setLoras] = useState<LoraSpecInput[]>([]);const [availableLoras, setAvailableLoras] = useState<DiffusionLoraInfo[]>([]);+ // Fine-tuned (trained in Unsloth) first, for both the suggestions and the Add LoRA prefill.+ const sortedLoras = useMemo(+ () => [...availableLoras].sort((a, b) => Number(Boolean(b.fine_tuned)) - Number(Boolean(a.fine_tuned))),+ [availableLoras],+ );// Page mode: "create" is the generation workspace, "train" the LoRA training workspace.const pageMode = useImageWorkflowStore((s) => s.pageMode);const setPageMode = useImageWorkflowStore((s) => s.setPageMode);@@ -5466,13 +5471,11 @@ export function ImagesPage({{availableLoras.length > 0 && (<datalist id="diffusion-lora-suggestions">{/* 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>- ))}+ {sortedLoras.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) => (@@ -5531,7 +5534,7 @@ export function ImagesPage({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));+ const next = sortedLoras.find((a) => !taken.has(a.id));setLoras((prev) => [...prev,next ? { id: next.id, weight: next.weight_default || 1 } : { id: "", weight: 1 },diff --git a/studio/frontend/src/features/images/train/diffusion-train-deploy.ts b/studio/frontend/src/features/images/train/diffusion-train-deploy.tsindex c1b492fa8a7..00774c1e496 100644--- a/studio/frontend/src/features/images/train/diffusion-train-deploy.ts+++ b/studio/frontend/src/features/images/train/diffusion-train-deploy.ts@@ -56,6 +56,26 @@ export function resolveDiffusionTrainingBase(const name = normalizedRepo(trainingRepo.split("/").pop() ?? "");if (!name) return null;return (- family.base_repos.find((repo) => normalizedRepo(repo.split("/").pop() ?? "") === name) ?? null+ family.base_repos.find(+ (repo) => normalizedRepo(repo.split("/").pop() ?? "") === name,+ ) ?? null);}++// The catalog id is the file stem, or the full name when a same-stem file of the other format exists.+export function catalogFileName(catalogPath: string): string {+ return catalogPath.split(/[\\/]/).pop() ?? catalogPath;+}++// Same format only (a stale run must not pick a same-stem GGUF), stem before full name (`x.safetensors.safetensors`).+export function matchCatalogId(+ loras: { id: string; format: string }[],+ fileName: string,+): string | undefined {+ const match = /^(.*)\.(safetensors|gguf)$/i.exec(fileName);+ const ids = loras+ .filter((l) => !match || l.format === match[2].toLowerCase())+ .map((l) => l.id);+ const stem = match ? match[1] : fileName;+ return ids.find((id) => id === stem) ?? ids.find((id) => id === fileName);+}diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsxindex 75c3dde2316..d9d65d544b3 100644--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx@@ -17,6 +17,7 @@ import {Upload01Icon,} from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";+import { useNavigate } from "@tanstack/react-router";import { TestTubeOutlineIcon } from "@/lib/hugeicons-derived";import {@@ -106,6 +107,7 @@ import {resumeActionLabel,} from "./resume-diffusion-run";import {+ catalogFileName,resolveDiffusionDeployBase,resolveDiffusionTrainingBase,} from "./diffusion-train-deploy";@@ -1287,6 +1289,11 @@ export function DiffusionTrainPanel({[info?.families],);+ const navigate = useNavigate();+ const exportAdapter = useCallback(+ (catalogPath: string) => void navigate({ to: "/export", search: { imageLora: catalogFileName(catalogPath) } }),+ [navigate],+ );const onDeployClick = useCallback(() => {if (!status?.catalog_path) {toast.error("The trained adapter is not available yet.");@@ -2055,6 +2062,16 @@ export function DiffusionTrainPanel({Deploy to Create</Button>)}+ {viewRun.saved && viewRun.catalog_path && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => exportAdapter(viewRun.catalog_path as string)}+ >+ Export+ </Button>+ )}<Buttontype="button"size="sm"@@ -2268,6 +2285,16 @@ export function DiffusionTrainPanel({Deploy to Create</Button>)}+ {status?.catalog_path && (+ <Button+ type="button"+ size="sm"+ variant="outline"+ onClick={() => exportAdapter(status.catalog_path as string)}+ >+ Export+ </Button>+ )}{/* Only a run stopped short can be continued. Disabled until the run record lands, with thebackend's reason as the tooltip. */}{!completed && status?.job_id && (diff --git a/studio/frontend/tests/image-lora-export-handoff.test.ts b/studio/frontend/tests/image-lora-export-handoff.test.tsnew file mode 100644index 00000000000..9f51fb67ee5--- /dev/null+++ b/studio/frontend/tests/image-lora-export-handoff.test.ts@@ -0,0 +1,78 @@+// 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 assert from "node:assert/strict";+import test from "node:test";++import { savedLabel } from "../src/features/export/constants.ts";+import {+ catalogFileName,+ matchCatalogId,+} from "../src/features/images/train/diffusion-train-deploy.ts";++import { readSrcAsync } from "./helpers/kit.ts";++test("a published adapter is matched by its stem, or its full name when the stem collides", () => {+ assert.equal(+ catalogFileName(+ "/home/u/.unsloth/studio/loras/diffusion/sksdog.safetensors",+ ),+ "sksdog.safetensors",+ );+ assert.equal(+ catalogFileName("C:\\Users\\u\\loras\\diffusion\\my.style.gguf"),+ "my.style.gguf",+ );+ const st = (id: string) => ({ id, format: "safetensors" });+ const gg = (id: string) => ({ id, format: "gguf" });+ assert.equal(+ matchCatalogId([st("sksdog"), st("other")], "sksdog.safetensors"),+ "sksdog",+ );+ assert.equal(+ matchCatalogId([gg("s.gguf"), st("s.safetensors")], "s.safetensors"),+ "s.safetensors",+ );+ // A stale run whose safetensors is gone never picks the same-stem GGUF.+ assert.equal(matchCatalogId([gg("style")], "style.safetensors"), undefined);+ assert.equal(+ matchCatalogId([st("dog.safetensors"), st("dog")], "dog.safetensors"),+ "dog",+ );+ assert.equal(matchCatalogId([st("other")], "sksdog.safetensors"), undefined);+});++test("the export result names the exports folder unless the path is absolute", () => {+ assert.equal(+ savedLabel("image-loras/sksdog.safetensors"),+ "exports/image-loras/sksdog.safetensors",+ );+ assert.equal(+ savedLabel("/data/loras/sksdog.safetensors"),+ "/data/loras/sksdog.safetensors",+ );+ assert.equal(+ savedLabel("D:\\loras\\sksdog.safetensors"),+ "D:\\loras\\sksdog.safetensors",+ );+});++test("the finished training run hands its LoRA to the Export page", async () => {+ const panel = await readSrcAsync(+ "features/images/train/diffusion-train-panel.tsx",+ );+ assert.match(+ panel,+ /to: "\/export",\s*search: \{ imageLora: catalogFileName\(catalogPath\)\s*\}/,+ );+ assert.equal(panel.match(/exportAdapter\(/g)?.length, 2);+ // A run stopped early with a saved adapter can be exported too, not only a completed one.+ assert.doesNotMatch(panel, /completed && status\?\.catalog_path && \(/);+ const route = await readSrcAsync("app/routes/export.tsx");+ assert.match(route, /imageLora:\s*typeof search\.imageLora === "string"/);+ const page = await readSrcAsync("features/export/export-page.tsx");+ assert.match(+ page,+ /<ImageLoraExportCard preselect=\{preselectImageLora\} \/>/,+ );+});