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: save Image LoRA training settings as presets (#17019)

Daniel Han763347f4d4ac
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index a67db551463..30d5aa65161 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -306,6 +306,48 @@ class VideoGenerationPresetParams(BaseModel):
audioFlowShift: Optional[float] = Field(default = None, gt = 0, le = 100)
+class TrainingPresetParams(BaseModel):
+ """Image LoRA training form. Numbers carry no bounds: the form autosaves mid-edit, and
+ DiffusionTrainingStartRequest validates them on Start."""
+
+ model_config = ConfigDict(extra = "forbid")
+
+ familyName: str = Field(default = "", max_length = 80)
+ baseChoice: str = Field(default = "", max_length = 1024)
+ customBase: str = Field(default = "", max_length = 4096)
+ durationUnit: Literal["steps", "epochs"] = "steps"
+ steps: float = Field(default = 500, allow_inf_nan = False)
+ epochs: float = Field(default = 10, allow_inf_nan = False)
+ learningRate: float = Field(default = 0.0001, allow_inf_nan = False)
+ rank: float = Field(default = 16, allow_inf_nan = False)
+ resolution: float = Field(default = 768, allow_inf_nan = False)
+ batchSize: float = Field(default = 1, allow_inf_nan = False)
+ gradAccum: float = Field(default = 1, allow_inf_nan = False)
+ seed: float = Field(default = 42, allow_inf_nan = False)
+ saveSteps: float = Field(default = 0, allow_inf_nan = False)
+ sampleEvery: float = Field(default = 0, allow_inf_nan = False)
+ saveTotalLimit: float = Field(default = 2, allow_inf_nan = False)
+ lrScheduler: Literal[
+ "linear",
+ "cosine",
+ "cosine_with_restarts",
+ "polynomial",
+ "constant",
+ "constant_with_warmup",
+ ] = "constant"
+ lrWarmupSteps: float = Field(default = 0, allow_inf_nan = False)
+ gradCheckpoint: bool = True
+ bucketing: bool = True
+ randomFlip: bool = False
+ cfgDropout: float = Field(default = 0, allow_inf_nan = False)
+ loraDropout: float = Field(default = 0, allow_inf_nan = False)
+ flowShiftMode: Literal["default", "custom"] = "default"
+ flowShift: float = Field(default = 3, allow_inf_nan = False)
+ precision: Literal["bf16", "fp16", "no"] = "bf16"
+ basePrecision: Literal["nf4", "bf16", "int8", "fp8", "mxfp8", "auto"] = "auto"
+ compileTransformer: Literal["off", "on", "auto"] = "auto"
+
+
class MediaGenerationPreset(BaseModel):
model_config = ConfigDict(extra = "forbid")
@@ -328,6 +370,10 @@ class VideoGenerationPreset(MediaGenerationPreset):
params: VideoGenerationPresetParams
+class TrainingPreset(MediaGenerationPreset):
+ params: TrainingPresetParams
+
+
class MediaGenerationPresetState(BaseModel):
"""A saved generation recipe and the selection that owns it.
@@ -349,6 +395,10 @@ class VideoGenerationPresetState(MediaGenerationPresetState):
currentParams: VideoGenerationPresetParams = Field(default_factory = VideoGenerationPresetParams)
+class TrainingPresetState(MediaGenerationPresetState):
+ currentParams: TrainingPresetParams = Field(default_factory = TrainingPresetParams)
+
+
class ImageGenerationPresetSettings(ImageGenerationPresetState):
# No cap on read: upsert_media_generation_preset owns the limit; a cap here would 500 the GET.
customPresets: list[ImageGenerationPreset] = Field(default_factory = list)
@@ -360,6 +410,11 @@ class VideoGenerationPresetSettings(VideoGenerationPresetState):
saved: bool = False
+class TrainingPresetSettings(TrainingPresetState):
+ customPresets: list[TrainingPreset] = Field(default_factory = list)
+ saved: bool = False
+
+
def _nested_model(annotation: Any) -> Optional[type[BaseModel]]:
for candidate in (annotation, *get_args(annotation)):
if isinstance(candidate, type) and issubclass(candidate, BaseModel):
@@ -547,8 +602,33 @@ def update_video_generation_preset_settings(
return {"saved": True}
+@_account_settings_router.get(
+ "/generation-presets/training",
+ response_model = TrainingPresetSettings,
+)
+def get_training_preset_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> TrainingPresetSettings:
+ return _get_generation_preset_settings("training", TrainingPresetSettings)
+
+
+@_account_settings_router.put("/generation-presets/training")
+def update_training_preset_settings(
+ payload: TrainingPresetState, current_subject: str = Depends(get_current_subject)
+) -> dict[str, bool]:
+ set_media_generation_preset_settings(
+ "training",
+ payload.model_dump(),
+ lambda stored, submitted: _preserve_recovered_defaults(
+ TrainingPresetState, stored, submitted
+ ),
+ )
+ return {"saved": True}
+
+
def _upsert_custom_generation_preset(
- kind: Literal["image", "video"], payload: ImageGenerationPreset | VideoGenerationPreset
+ kind: Literal["image", "video", "training"],
+ payload: ImageGenerationPreset | VideoGenerationPreset | TrainingPreset,
) -> dict[str, bool]:
try:
schema = type(payload)
@@ -576,9 +656,16 @@ def upsert_custom_video_generation_preset(
return _upsert_custom_generation_preset("video", payload)
+@_account_settings_router.put("/generation-presets/training/custom")
+def upsert_custom_training_preset(
+ payload: TrainingPreset, current_subject: str = Depends(get_current_subject)
+) -> dict[str, bool]:
+ return _upsert_custom_generation_preset("training", payload)
+
+
@_account_settings_router.delete("/generation-presets/{kind}/custom")
def delete_custom_generation_preset(
- kind: Literal["image", "video"],
+ kind: Literal["image", "video", "training"],
name: str,
current_subject: str = Depends(get_current_subject),
) -> dict[str, bool]:
diff --git a/studio/backend/tests/test_media_generation_preset_settings.py b/studio/backend/tests/test_media_generation_preset_settings.py
index 71fc009436a..7e2c47299b3 100644
--- a/studio/backend/tests/test_media_generation_preset_settings.py
+++ b/studio/backend/tests/test_media_generation_preset_settings.py
@@ -507,3 +507,61 @@ def test_a_store_holding_load_options_is_read_without_them_and_keeps_them(monkey
kept = stored["image_generation_presets"]
assert kept["currentLoadConfig"] == {"speedMode": "max"}
assert kept["customPresets"][0]["loadConfig"] == {"memoryMode": "low_vram"}
+
+
+_TRAINING_RECIPE = {
+ "familyName": "z-image",
+ "baseChoice": "__custom__",
+ "customBase": "D:/models/Z-Image-De-Turbo",
+ "steps": 1500,
+ "learningRate": 0.0002,
+ "rank": 32,
+ "flowShiftMode": "custom",
+ "flowShift": 4.5,
+ "basePrecision": "bf16",
+}
+
+
+def test_training_presets_round_trip_a_local_base_and_hyperparameters(monkeypatch):
+ stored = {}
+ client = _client(monkeypatch, stored)
+ preset = {"name": "My Z-Image LoRA", "params": _TRAINING_RECIPE}
+ assert (
+ client.put("/api/settings/generation-presets/training/custom", json = preset).status_code
+ == 200
+ )
+ state = {"currentParams": _TRAINING_RECIPE, "activePreset": "My Z-Image LoRA"}
+ assert client.put("/api/settings/generation-presets/training", json = state).status_code == 200
+ # Idempotent: the same writes again leave one preset and the same selection.
+ client.put("/api/settings/generation-presets/training/custom", json = preset)
+ client.put("/api/settings/generation-presets/training", json = state)
+
+ training = client.get("/api/settings/generation-presets/training").json()
+ assert training["activePreset"] == "My Z-Image LoRA"
+ assert [p["name"] for p in training["customPresets"]] == ["My Z-Image LoRA"]
+ params = training["customPresets"][0]["params"]
+ assert params["customBase"] == "D:/models/Z-Image-De-Turbo"
+ assert params["steps"] == 1500 and params["rank"] == 32 and params["flowShift"] == 4.5
+ assert params["seed"] == 42, "fields the preset omits read back as the form defaults"
+ assert set(stored) == {"training_generation_presets"}
+ assert client.get("/api/settings/generation-presets/image").json()["customPresets"] == []
+
+ response = client.delete(
+ "/api/settings/generation-presets/training/custom", params = {"name": "My Z-Image LoRA"}
+ )
+ assert response.status_code == 200
+ assert client.get("/api/settings/generation-presets/training").json()["customPresets"] == []
+
+
+def test_training_state_accepts_mid_edit_numbers_but_rejects_unknown_fields(monkeypatch):
+ client = _client(monkeypatch)
+ # The form autosaves while a field is being typed; Start validates the numbers, not this store.
+ mid_edit = {
+ "currentParams": {"rank": 0, "learningRate": 0, "steps": 2.5},
+ "activePreset": "Default",
+ }
+ assert client.put("/api/settings/generation-presets/training", json = mid_edit).status_code == 200
+ for bad in ({"hf_token": "hf_x"}, {"dataDir": "/data"}, {"lrScheduler": "nope"}):
+ payload = {"currentParams": bad, "activePreset": "Default"}
+ response = client.put("/api/settings/generation-presets/training", json = payload)
+ assert response.status_code == 422, bad
diff --git a/studio/backend/utils/media_generation_preset_settings.py b/studio/backend/utils/media_generation_preset_settings.py
index 3272770f608..9065992fac9 100644
--- a/studio/backend/utils/media_generation_preset_settings.py
+++ b/studio/backend/utils/media_generation_preset_settings.py
@@ -5,7 +5,7 @@ from threading import RLock
from typing import Callable, Literal, Optional
-MediaGenerationKind = Literal["image", "video"]
+MediaGenerationKind = Literal["image", "video", "training"]
_settings_lock = RLock()
_MAX_PRESETS = 100
diff --git a/studio/frontend/src/features/generation-presets/index.ts b/studio/frontend/src/features/generation-presets/index.ts
index e94866222f8..fd84dcce126 100644
--- a/studio/frontend/src/features/generation-presets/index.ts
+++ b/studio/frontend/src/features/generation-presets/index.ts
@@ -10,5 +10,6 @@ export {
} from "./preset-policy";
export type {
ImageGenerationPresetParams,
+ TrainingPresetParams,
VideoGenerationPresetParams,
} from "./types";
diff --git a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
index cb757e44785..1a0e3bb1cab 100644
--- a/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
+++ b/studio/frontend/src/features/generation-presets/media-generation-preset-control.tsx
@@ -18,10 +18,11 @@ import {
import { HugeiconsIcon } from "@hugeicons/react";
import { Fragment, useState } from "react";
import { DEFAULT_PRESET_NAME } from "./preset-policy";
+import type { MediaGenerationKind } from "./types";
import { Tick02Icon } from "@/lib/tick-icon";
interface MediaGenerationPresetControlProps {
- kind: "image" | "video";
+ kind: MediaGenerationKind;
presets: readonly { name: string }[];
activePreset: string;
ready: boolean;
@@ -46,6 +47,7 @@ export function MediaGenerationPresetControl({
onPasteParameters,
}: MediaGenerationPresetControlProps) {
const [open, setOpen] = useState(false);
+ const purpose = kind === "training" ? "image training" : `${kind} generation`;
const [draftName, setDraftName] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const name = draftName ?? activePreset;
@@ -108,7 +110,7 @@ export function MediaGenerationPresetControl({
variant="outline"
size="sm"
disabled={!ready || saving}
- aria-label={`Manage ${kind} generation presets`}
+ aria-label={`Manage ${purpose} presets`}
className={cn(
"relative size-8 shrink-0 gap-1.5 rounded-full border-border/60 bg-background/70 p-0 text-xs font-medium shadow-none backdrop-blur-sm hover:bg-muted/70 sm:h-8 sm:w-auto sm:max-w-40 sm:px-2.5",
open && "border-border bg-muted/70",
@@ -144,7 +146,7 @@ export function MediaGenerationPresetControl({
<div className="shrink-0 border-b border-border/60 px-4 py-3.5">
<div className="flex items-center justify-between gap-3">
<p className="font-heading text-sm font-medium">
- Generation presets
+ {kind === "training" ? "Training presets" : "Generation presets"}
</p>
{hasUnsavedChanges ? (
<span className="rounded-full bg-amber-500/10 px-2 py-0.5 text-ui-10 font-medium text-amber-700 dark:text-amber-300">
diff --git a/studio/frontend/src/features/generation-presets/preset-policy.ts b/studio/frontend/src/features/generation-presets/preset-policy.ts
index a051bad1d7a..7b901a39428 100644
--- a/studio/frontend/src/features/generation-presets/preset-policy.ts
+++ b/studio/frontend/src/features/generation-presets/preset-policy.ts
@@ -69,3 +69,16 @@ export function shouldApplyModelDefaults(
): boolean {
return !supersededByUser && (alreadySeeded || !storedRecipe);
}
+
+/** What hydration loads into the form. Without working-recipe restore only a named preset loads,
+ * so a store holding just Default leaves the form as a fresh page would. */
+export function hydratedParams<Params>(
+ currentParams: Params,
+ active: { name: string; params: Params },
+ restoreWorkingParams: boolean,
+): Params | null {
+ if (restoreWorkingParams) {
+ return currentParams;
+ }
+ return active.name === DEFAULT_PRESET_NAME ? null : active.params;
+}
diff --git a/studio/frontend/src/features/generation-presets/types.ts b/studio/frontend/src/features/generation-presets/types.ts
index d0f8f66d00a..ca9b50fb74d 100644
--- a/studio/frontend/src/features/generation-presets/types.ts
+++ b/studio/frontend/src/features/generation-presets/types.ts
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-export type MediaGenerationKind = "image" | "video";
+export type MediaGenerationKind = "image" | "video" | "training";
// Model-load options are deliberately absent; the resident build owns them.
export interface MediaGenerationPreset<Params> {
@@ -40,3 +40,33 @@ export interface VideoGenerationPresetParams {
flowShift: number | null;
audioFlowShift: number | null;
}
+
+export interface TrainingPresetParams {
+ familyName: string;
+ baseChoice: string;
+ customBase: string;
+ durationUnit: "steps" | "epochs";
+ steps: number;
+ epochs: number;
+ learningRate: number;
+ rank: number;
+ resolution: number;
+ batchSize: number;
+ gradAccum: number;
+ seed: number;
+ saveSteps: number;
+ sampleEvery: number;
+ saveTotalLimit: number;
+ lrScheduler: "constant" | "constant_with_warmup" | "cosine" | "linear";
+ lrWarmupSteps: number;
+ gradCheckpoint: boolean;
+ bucketing: boolean;
+ randomFlip: boolean;
+ cfgDropout: number;
+ loraDropout: number;
+ flowShiftMode: "default" | "custom";
+ flowShift: number;
+ precision: "bf16" | "fp16" | "no";
+ basePrecision: "nf4" | "bf16" | "int8" | "fp8" | "mxfp8" | "auto";
+ compileTransformer: "off" | "on" | "auto";
+}
diff --git a/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts b/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts
index 3cc86bdf5ef..f145e3db5a3 100644
--- a/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts
+++ b/studio/frontend/src/features/generation-presets/use-media-generation-presets.ts
@@ -21,6 +21,7 @@ import {
DEFAULT_PRESET_NAME,
configKey,
getBuiltinVariantName,
+ hydratedParams,
} from "./preset-policy";
import type {
MediaGenerationKind,
@@ -44,6 +45,8 @@ export interface MediaGenerationPresetsOptions<Params extends object> {
currentParams: Params;
applyParams: (params: Params) => Params;
normalizeParams?: (params: Params) => unknown;
+ // false: reopening loads the active named preset, not unsaved edits.
+ restoreWorkingParams?: boolean;
}
export function useMediaGenerationPresets<Params extends object>({
@@ -52,6 +55,7 @@ export function useMediaGenerationPresets<Params extends object>({
currentParams,
applyParams,
normalizeParams,
+ restoreWorkingParams = true,
}: MediaGenerationPresetsOptions<Params>) {
const paramsKey = useCallback(
(params: Params) =>
@@ -89,12 +93,14 @@ export function useMediaGenerationPresets<Params extends object>({
const defaultParamsRef = useRef(defaultParams);
const applyParamsRef = useRef(applyParams);
const paramsKeyRef = useRef(paramsKey);
+ const restoreWorkingParamsRef = useRef(restoreWorkingParams);
useLayoutEffect(() => {
currentParamsRef.current = currentParams;
activePresetRef.current = activePreset;
applyParamsRef.current = applyParams;
defaultParamsRef.current = defaultParams;
paramsKeyRef.current = paramsKey;
+ restoreWorkingParamsRef.current = restoreWorkingParams;
}, [
activePreset,
applyParams,
@@ -102,6 +108,7 @@ export function useMediaGenerationPresets<Params extends object>({
defaultParams,
hydrated,
paramsKey,
+ restoreWorkingParams,
]);
const presets = useMemo(
@@ -161,7 +168,12 @@ export function useMediaGenerationPresets<Params extends object>({
baselineParamsRef.current = definition.params;
setActivePreset(definition.name);
// Unconditional: the store answers first, then model defaults fill the rest.
- applyParamsRef.current(settings.currentParams);
+ const restored = hydratedParams(
+ settings.currentParams,
+ definition,
+ restoreWorkingParamsRef.current,
+ );
+ if (restored) applyParamsRef.current(restored);
setHydrationSource("saved");
},
[],
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index 7572df8799e..65e8e64a42b 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -6317,6 +6317,7 @@ export function ImagesPage({
baseChoice={trainBaseChoice}
onBaseChoiceChange={setTrainBaseChoice}
onFamiliesChange={setTrainFamilies}
+ savedPresets={true}
/>
</div>
)}
diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
index 97c2fb741cc..140d47490c4 100644
--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx
@@ -118,6 +118,11 @@ import {
import { resolveDiffusionTrainingFacts } from "./diffusion-train-family-facts";
import { diffusionTrainingProgress } from "./diffusion-train-progress";
import { type LrScheduler, lrSchedulePreset } from "./diffusion-train-lr-schedule";
+import {
+ MediaGenerationPresetControl,
+ type TrainingPresetParams,
+ useMediaGenerationPresets,
+} from "@/features/generation-presets";
// Fallback list for an older backend whose /info reports none, in popularity order.
type FamilyPreset = {
@@ -353,6 +358,41 @@ function mergeFamilies(reported?: DiffusionTrainableFamily[]): FamilyPreset[] {
return merged;
}
+function TrainingPresetControl({
+ defaultParams,
+ currentParams,
+ applyParams,
+ readyRef,
+}: {
+ defaultParams: TrainingPresetParams;
+ currentParams: TrainingPresetParams;
+ applyParams: (params: TrainingPresetParams) => TrainingPresetParams;
+ readyRef: { current: boolean };
+}) {
+ const presets = useMediaGenerationPresets({
+ kind: "training",
+ defaultParams,
+ currentParams,
+ applyParams,
+ restoreWorkingParams: false,
+ });
+ useEffect(() => {
+ readyRef.current = presets.presetsReady;
+ }, [presets.presetsReady, readyRef]);
+ return (
+ <MediaGenerationPresetControl
+ kind="training"
+ presets={presets.presets}
+ activePreset={presets.activePreset}
+ ready={presets.presetsReady}
+ hasUnsavedChanges={presets.hasUnsavedChanges}
+ onSelect={presets.selectPreset}
+ onSave={presets.savePreset}
+ onDelete={presets.deletePreset}
+ />
+ );
+}
+
// Kept mounted with the page so a long run survives tab switches; polling is gated on `active`.
export function DiffusionTrainPanel({
active,
@@ -365,6 +405,7 @@ export function DiffusionTrainPanel({
baseChoice,
onBaseChoiceChange,
onFamiliesChange,
+ savedPresets = false,
}: {
active: boolean;
loadedFamily?: string | null;
@@ -374,6 +415,8 @@ export function DiffusionTrainPanel({
baseChoice: string;
onBaseChoiceChange: (repo: string) => void;
onFamiliesChange?: (families: FamilyPreset[]) => void;
+ // One owner per store: Video keeps its own Train panel mounted, and two would race the saved selection.
+ savedPresets?: boolean;
onTrainingComplete?: () => void;
onDeploy?: (args: {
baseRepo: string;
@@ -607,8 +650,11 @@ export function DiffusionTrainPanel({
}
}, [loadedFamily, families]);
+ // A restored preset can name a family only /info reports; seeding the fallback would drop its base.
+ const familyPending =
+ family?.name !== familyName && (infoLoadState === "idle" || infoLoadState === "loading");
useEffect(() => {
- if (!family) return;
+ if (!family || familyPending) return;
// Compare by name: an info refresh yields a new object but is not a family change.
if (seededBaseFamily.current !== family.name) {
seededBaseFamily.current = family.name;
@@ -642,7 +688,7 @@ export function DiffusionTrainPanel({
: "auto",
);
}
- }, [family, loadedBaseRepo, reportedFamily]);
+ }, [family, familyPending, loadedBaseRepo, reportedFamily]);
// Reset to bf16 on a DiT family, or an fp16 left from SDXL is rejected.
useEffect(() => {
@@ -666,6 +712,188 @@ export function DiffusionTrainPanel({
}
}, [basePrequantized, basePrecision]);
+ const recommendedBasePrecision = reportedFamily?.recommended_precision;
+ const defaultPresetParams = useMemo<TrainingPresetParams>(
+ () => ({
+ familyName,
+ baseChoice: effectiveBase,
+ customBase,
+ durationUnit: "steps",
+ steps: 500,
+ epochs: 10,
+ learningRate: family?.defaults.lr ?? 0.0001,
+ rank: family?.defaults.rank ?? 16,
+ resolution: family?.defaults.resolution ?? 768,
+ batchSize: 1,
+ gradAccum: 1,
+ seed: 42,
+ saveSteps: 0,
+ sampleEvery: 0,
+ saveTotalLimit: 2,
+ lrScheduler: family?.defaults.lrScheduler ?? "constant",
+ lrWarmupSteps: family?.defaults.lrWarmupSteps ?? 0,
+ gradCheckpoint: true,
+ bucketing: true,
+ randomFlip: false,
+ cfgDropout: 0,
+ loraDropout: 0,
+ flowShiftMode: "default",
+ flowShift: 3,
+ precision: "bf16",
+ basePrecision:
+ recommendedBasePrecision === "nf4" ||
+ recommendedBasePrecision === "bf16" ||
+ recommendedBasePrecision === "int8" ||
+ recommendedBasePrecision === "fp8"
+ ? recommendedBasePrecision
+ : "auto",
+ compileTransformer: "auto",
+ }),
+ [familyName, effectiveBase, customBase, family, recommendedBasePrecision],
+ );
+ const currentPresetParams = useMemo<TrainingPresetParams>(
+ () => ({
+ familyName,
+ baseChoice: effectiveBase,
+ customBase,
+ durationUnit,
+ steps,
+ epochs,
+ learningRate,
+ rank,
+ resolution,
+ batchSize,
+ gradAccum,
+ seed,
+ saveSteps,
+ sampleEvery,
+ saveTotalLimit,
+ lrScheduler,
+ lrWarmupSteps,
+ gradCheckpoint,
+ bucketing,
+ randomFlip,
+ cfgDropout,
+ loraDropout,
+ flowShiftMode,
+ flowShift,
+ precision,
+ basePrecision,
+ compileTransformer,
+ }),
+ [
+ familyName,
+ effectiveBase,
+ customBase,
+ durationUnit,
+ steps,
+ epochs,
+ learningRate,
+ rank,
+ resolution,
+ batchSize,
+ gradAccum,
+ seed,
+ saveSteps,
+ sampleEvery,
+ saveTotalLimit,
+ lrScheduler,
+ lrWarmupSteps,
+ gradCheckpoint,
+ bucketing,
+ randomFlip,
+ cfgDropout,
+ loraDropout,
+ flowShiftMode,
+ flowShift,
+ precision,
+ basePrecision,
+ compileTransformer,
+ ],
+ );
+ const presetsReadyRef = useRef(false);
+ // Not every control sets a dirty ref (family, toggles), so any edit before presets settle counts.
+ const editedBeforePresets = useRef(false);
+ const trainRailRef = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ // Listens on the scroller natively: its opening tag must carry only className (rail clamp).
+ const root = trainRailRef.current?.parentElement;
+ if (!root) {
+ return;
+ }
+ const noteFormEdit = (event: Event) => {
+ if (presetsReadyRef.current || !(event.target instanceof Element)) {
+ return;
+ }
+ const control = event.target.closest(
+ "input, textarea, button, [role=combobox], [role=switch], [role=radio]",
+ );
+ if (control && !control.closest("[data-testid=training-generation-presets]")) {
+ editedBeforePresets.current = true;
+ }
+ };
+ root.addEventListener("pointerdown", noteFormEdit, true);
+ root.addEventListener("keydown", noteFormEdit, true);
+ return () => {
+ root.removeEventListener("pointerdown", noteFormEdit, true);
+ root.removeEventListener("keydown", noteFormEdit, true);
+ };
+ }, []);
+ const applyPresetParams = useCallback(
+ (params: TrainingPresetParams) => {
+ const userEdited =
+ editedBeforePresets.current ||
+ settingsDirty.current ||
+ lrScheduleDirty.current ||
+ precisionDirty.current ||
+ baseDirty.current;
+ // The stored preset can land seconds after mount; fields edited by then are newer.
+ if (!presetsReadyRef.current && userEdited) {
+ return params;
+ }
+ // Default re-seeds from the family as a fresh page does; a named preset owns every field.
+ const owned = params !== defaultPresetParams;
+ settingsDirty.current = owned;
+ lrScheduleDirty.current = owned;
+ precisionDirty.current = owned;
+ if (owned) {
+ // Neither a loaded model nor the family re-seed may replace the preset's base.
+ seededFromLoaded.current = true;
+ seededBaseFamily.current = params.familyName;
+ baseDirty.current = true;
+ }
+ setFamilyName(params.familyName);
+ setBaseChoice(params.baseChoice);
+ setCustomBase(params.customBase);
+ setDurationUnit(params.durationUnit);
+ setSteps(params.steps);
+ setEpochs(params.epochs);
+ setLearningRate(params.learningRate);
+ setRank(params.rank);
+ setResolution(params.resolution);
+ setBatchSize(params.batchSize);
+ setGradAccum(params.gradAccum);
+ setSeed(params.seed);
+ setSaveSteps(params.saveSteps);
+ setSampleEvery(params.sampleEvery);
+ setSaveTotalLimit(params.saveTotalLimit);
+ setLrScheduler(params.lrScheduler);
+ setLrWarmupSteps(params.lrWarmupSteps);
+ setGradCheckpoint(params.gradCheckpoint);
+ setBucketing(params.bucketing);
+ setRandomFlip(params.randomFlip);
+ setCfgDropout(params.cfgDropout);
+ setLoraDropout(params.loraDropout);
+ setFlowShiftMode(params.flowShiftMode);
+ setFlowShift(params.flowShift);
+ setPrecision(params.precision);
+ setBasePrecision(params.basePrecision);
+ setCompileTransformer(params.compileTransformer);
+ return params;
+ },
+ [defaultPresetParams, setFamilyName, setBaseChoice],
+ );
+
const poll = useCallback(async () => {
try {
setStatus(await getDiffusionTrainingStatus());
@@ -1635,7 +1863,7 @@ export function DiffusionTrainPanel({
// row pan the page sideways on a phone.
return (
<div className="flex min-h-0 w-full min-w-0 flex-1 flex-col overflow-y-auto overflow-x-hidden pr-5 sm:pr-8 @[50rem]:flex-row @[50rem]:overflow-hidden">
- <div className="flex w-full min-w-0 shrink-0 flex-col border-b border-border/60 pl-10 max-sm:pl-5 @[50rem]:w-[min(var(--media-rail-width,calc(408px*var(--ui-space-scale,1))),calc(100%-var(--media-header-min-width,13rem)+--spacing(8)))] @[50rem]:overflow-hidden @[50rem]:border-r @[50rem]:border-b-0">
+ <div ref={trainRailRef} className="flex w-full min-w-0 shrink-0 flex-col border-b border-border/60 pl-10 max-sm:pl-5 @[50rem]:w-[min(var(--media-rail-width,calc(408px*var(--ui-space-scale,1))),calc(100%-var(--media-header-min-width,13rem)+--spacing(8)))] @[50rem]:overflow-hidden @[50rem]:border-r @[50rem]:border-b-0">
<div
ref={attachSettingsScroll}
onScroll={onSettingsScroll}
@@ -1644,17 +1872,27 @@ export function DiffusionTrainPanel({
settingsFadeClass,
)}
>
- <div className="mb-1 grid gap-1.5">
- <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none">
- <HugeiconsIcon
- icon={TestTubeOutlineIcon}
- className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0"
+ <div className="mb-1 flex items-start justify-between gap-3">
+ <div className="grid min-w-0 gap-1.5">
+ <h2 className="flex items-center gap-2 font-heading text-xl font-medium leading-none">
+ <HugeiconsIcon
+ icon={TestTubeOutlineIcon}
+ className="size-[calc(18px*var(--ui-space-scale,1))] shrink-0"
+ />
+ Train a LoRA
+ </h2>
+ <p className="text-xs leading-snug text-muted-foreground">
+ Teach a model a new style or subject.
+ </p>
+ </div>
+ {savedPresets ? (
+ <TrainingPresetControl
+ defaultParams={defaultPresetParams}
+ currentParams={currentPresetParams}
+ applyParams={applyPresetParams}
+ readyRef={presetsReadyRef}
/>
- Train a LoRA
- </h2>
- <p className="text-xs leading-snug text-muted-foreground">
- Teach a model a new style or subject.
- </p>
+ ) : null}
</div>
<div className={fieldClass}>
diff --git a/studio/frontend/tests/diffusion-train-presets.test.ts b/studio/frontend/tests/diffusion-train-presets.test.ts
new file mode 100644
index 00000000000..3efd228dd6f
--- /dev/null
+++ b/studio/frontend/tests/diffusion-train-presets.test.ts
@@ -0,0 +1,103 @@
+// 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 { hydratedParams } from "../src/features/generation-presets/preset-policy.ts";
+import { readSrcAsync } from "./helpers/kit.ts";
+
+const panel = await readSrcAsync("features/images/train/diffusion-train-panel.tsx");
+const images = await readSrcAsync("features/images/images-page.tsx");
+const video = await readSrcAsync("features/video/video-page.tsx");
+const hook = await readSrcAsync(
+ "features/generation-presets/use-media-generation-presets.ts",
+);
+
+test("image and video generation still restore the working recipe", () => {
+ const working = { steps: 30 };
+ assert.equal(hydratedParams(working, { name: "Default", params: { steps: 9 } }, true), working);
+ assert.equal(hydratedParams(working, { name: "Mine", params: { steps: 20 } }, true), working);
+ assert.match(hook, /restoreWorkingParams = true,/);
+});
+
+test("training loads the active named preset, and Default leaves a fresh form", () => {
+ const preset = { steps: 1200 };
+ assert.equal(hydratedParams({ steps: 77 }, { name: "Mine", params: preset }, false), preset);
+ assert.equal(hydratedParams({ steps: 77 }, { name: "Default", params: { steps: 500 } }, false), null);
+});
+
+test("the training panel uses its own preset kind without working-recipe restore", () => {
+ const call = panel.slice(panel.indexOf("useMediaGenerationPresets({"));
+ assert.match(call, /kind: "training",/);
+ assert.match(call, /restoreWorkingParams: false,/);
+ assert.match(panel, /<MediaGenerationPresetControl\s+kind="training"/);
+});
+
+test("only the Images Train panel owns the saved presets", () => {
+ // Video keeps its own Train panel mounted; a second hook would race the saved selection.
+ assert.match(panel, /savedPresets = false,/);
+ assert.match(panel, /\{savedPresets \? \(\s+<TrainingPresetControl/);
+ assert.match(images, /savedPresets=\{true\}/);
+ assert.doesNotMatch(video, /savedPresets/);
+});
+
+test("a named preset survives the family re-seed and the loaded-model seed", () => {
+ const apply = panel.slice(
+ panel.indexOf("const applyPresetParams = useCallback("),
+ panel.indexOf("const poll = useCallback("),
+ );
+ assert.match(apply, /const owned = params !== defaultPresetParams;/);
+ for (const ref of ["settingsDirty", "lrScheduleDirty", "precisionDirty"]) {
+ assert.match(apply, new RegExp(`${ref}\\.current = owned;`));
+ }
+ const ownedBlock = apply.slice(apply.indexOf("if (owned) {"));
+ assert.match(ownedBlock, /seededFromLoaded\.current = true;/);
+ assert.match(ownedBlock, /seededBaseFamily\.current = params\.familyName;/);
+ assert.match(ownedBlock, /baseDirty\.current = true;/);
+ assert.ok(
+ apply.indexOf("if (owned) {") < apply.indexOf("setFamilyName(params.familyName);"),
+ "the refs are set before the family changes, so the re-seed effect sees them",
+ );
+});
+
+test("edits made before the stored preset lands are kept", () => {
+ const apply = panel.slice(
+ panel.indexOf("const applyPresetParams = useCallback("),
+ panel.indexOf("const poll = useCallback("),
+ );
+ const guard = apply.indexOf("if (!presetsReadyRef.current && userEdited) {");
+ assert.ok(guard > 0, "hydration must not overwrite a form the user already edited");
+ assert.ok(guard < apply.indexOf("setFamilyName(params.familyName);"));
+ assert.match(apply, /editedBeforePresets\.current \|\|/, "family and toggle edits count too");
+ assert.match(panel, /root\.addEventListener\("pointerdown", noteFormEdit, true\);/);
+ assert.match(panel, /root\.addEventListener\("keydown", noteFormEdit, true\);/);
+ assert.match(panel, /<div ref=\{trainRailRef\} className=/);
+ assert.match(panel, /readyRef\.current = presets\.presetsReady;/);
+ assert.match(panel, /readyRef=\{presetsReadyRef\}/);
+});
+
+test("a preset family only /info reports is not seeded from the fallback family", () => {
+ assert.match(
+ panel,
+ /const familyPending =\s+family\?\.name !== familyName && \(infoLoadState === "idle" \|\| infoLoadState === "loading"\);/,
+ );
+ const seed = panel.slice(panel.indexOf("const familyPending ="));
+ assert.match(seed, /if \(!family \|\| familyPending\) return;/);
+ assert.match(seed, /\}, \[family, familyPending, loadedBaseRepo, reportedFamily\]\);/);
+});
+
+test("every saved field is applied back to the form", () => {
+ const current = panel.slice(
+ panel.indexOf("const currentPresetParams = useMemo<TrainingPresetParams>("),
+ panel.indexOf("const applyPresetParams = useCallback("),
+ );
+ const fields = [...current.slice(0, current.indexOf("}),")).matchAll(/^\s+(\w+)(?::|,)/gm)].map(
+ (m) => m[1],
+ );
+ assert.ok(fields.length >= 25, `expected the full recipe, got ${fields.join(",")}`);
+ const apply = panel.slice(panel.indexOf("const applyPresetParams = useCallback("));
+ for (const field of fields) {
+ assert.match(apply, new RegExp(`\\(params\\.${field}\\)`), `${field} is saved but never applied`);
+ }
+});