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
Studio: pick the sampler on the Images page and load v-prediction SDXL checkpoints correctly (#13569)
Daniel Hand1d749577a0a
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex ede7912097b..ecab9d63233 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -278,6 +278,12 @@ from .diffusion_flow_shift import (pipe_sample_sigmas,sample_sigmas_for_steps,)+from .diffusion_sampler import (+ DEFAULT_SAMPLER,+ apply_checkpoint_prediction_type,+ build_scheduler,+ sampler_options,+)from .diffusion_single_file_converters import (CONVERTERS as _ORIGINAL_LAYOUT_CONVERTERS,load_original_layout_transformer,@@ -7361,6 +7367,8 @@ class DiffusionBackend:pipe = pipeline_cls.from_single_file(single_file_path, **sf_pipe_kwargs)+ # The base repo's scheduler is epsilon; a v-pred checkpoint says so only in its header.+ apply_checkpoint_prediction_type(pipe, single_file_path, logger)else:# Transformer-only single file; VAE/text-encoder/scheduler come from the base repo.sf_kwargs: dict[str, Any] = {@@ -10441,6 +10449,8 @@ class DiffusionBackend:allow_oversized: bool = False,# None = on unless UNSLOTH_DIFFUSION_PREVIEW=0.live_preview: Optional[bool] = None,+ sampler: Optional[str] = None,+ schedule_type: Optional[str] = None,) -> dict[str, Any]:import torchfrom PIL import Image@@ -10473,6 +10483,7 @@ class DiffusionBackend:self._gen = _GenState(total_steps = steps)# Reset in the finally, so a failed or cancelled generation frees its reused outputs.static_skip_pipe = None+ restore_scheduler: Optional[tuple[Any, Any]] = Nonerestore_vae: Optional[Callable[[], None]] = Nonerestore_resident: Optional[Callable[[], None]] = Nonebg = None@@ -10731,6 +10742,10 @@ class DiffusionBackend:# reconciles.self._make_vae_encode_dtype_safe(pipe)+ swapped, resolved_schedule = build_scheduler(pipe.scheduler, sampler, schedule_type)+ if swapped is not None:+ restore_scheduler = (pipe, pipe.scheduler)+ pipe.scheduler = swapped# Pipelines vary in accepted kwargs, so gate every optional one on the signature.call_params = inspect.signature(pipe.__call__).parameters@@ -11315,6 +11330,10 @@ class DiffusionBackend:"workflow": workflow,"reference_resolution": ref_resolution,"localized_edit": localized_edit.mode if localized_edit is not None else None,+ "sampler": sampler+ if swapped is not None and sampler != DEFAULT_SAMPLER+ else None,+ "schedule_type": resolved_schedule,}logger.info("diffusion.generated: %s",@@ -11328,6 +11347,8 @@ class DiffusionBackend:)return resultfinally:+ if restore_scheduler is not None:+ restore_scheduler[0].scheduler = restore_scheduler[1]if bg_token is not None:bg_compile._FORCE_EAGER.reset(bg_token)if static_skip_pipe is not None:@@ -11627,6 +11648,7 @@ class DiffusionBackend:# Workflows the loaded family supports, so the UI can gate its tabs."workflows": _family_workflows(state.family),"supports_negative_prompt": state.family.uses_negative_prompt,+ "samplers": sampler_options(getattr(state.pipe, "scheduler", None)),"conditioning": conditioning_capabilities(state.family, _family_workflows(state.family)),diff --git a/studio/backend/core/inference/diffusion_sampler.py b/studio/backend/core/inference/diffusion_sampler.pynew file mode 100644index 00000000000..fc4aeb1c253--- /dev/null+++ b/studio/backend/core/inference/diffusion_sampler.py@@ -0,0 +1,232 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Sampler (scheduler) choice for the diffusers image engine, plus the v-prediction markers a+single-file SDXL checkpoint carries. Names follow AUTOMATIC1111; the mapping is the diffusers+scheduler overview table. No torch/diffusers imports at module level."""++from __future__ import annotations++from functools import lru_cache, wraps+from typing import Any, Optional++DEFAULT_SAMPLER = "default"+AUTOMATIC_SCHEDULE = "automatic"++# id -> (label, diffusers class, constructor overrides)+SAMPLERS: dict[str, tuple[str, Optional[str], dict[str, Any]]] = {+ DEFAULT_SAMPLER: ("Model default", None, {}),+ "euler": ("Euler", "EulerDiscreteScheduler", {}),+ "euler_a": ("Euler a", "EulerAncestralDiscreteScheduler", {}),+ "dpmpp_2m": (+ "DPM++ 2M",+ "DPMSolverMultistepScheduler",+ {"algorithm_type": "dpmsolver++", "solver_order": 2},+ ),+ "dpmpp_2m_sde": (+ "DPM++ 2M SDE",+ "DPMSolverMultistepScheduler",+ {"algorithm_type": "sde-dpmsolver++", "solver_order": 2},+ ),+}++SCHEDULE_TYPES: dict[str, tuple[str, Optional[str]]] = {+ AUTOMATIC_SCHEDULE: ("Automatic", None),+ "uniform": ("Uniform", None),+ "karras": ("Karras", "use_karras_sigmas"),+ "exponential": ("Exponential", "use_exponential_sigmas"),+}+_SIGMA_FLAGS = ("use_karras_sigmas", "use_exponential_sigmas", "use_beta_sigmas", "use_lu_lambdas")++# AUTOMATIC1111's per-sampler default schedule (modules/sd_samplers_kdiffusion.py); absent = keep the config's.+_AUTOMATIC_FOR = {"dpmpp_2m": "karras", "dpmpp_2m_sde": "exponential"}+++def _init_params(cls: type) -> frozenset[str]:+ import inspect+ try:+ return frozenset(inspect.signature(cls.__init__).parameters)+ except (TypeError, ValueError):+ return frozenset()+++def _class_for(sampler: str, resident: Any) -> Optional[type]:+ cls_name = SAMPLERS[sampler][1]+ if cls_name is None:+ return type(resident)+ import diffusers++ return getattr(diffusers, cls_name, None)+++def _schedule_types_for(cls: type) -> list[str]:+ params = _init_params(cls)+ return [sid for sid, (_label, flag) in SCHEDULE_TYPES.items() if flag is None or flag in params]+++@lru_cache(maxsize = 32)+def _options_for(scheduler_cls: type) -> tuple[tuple[str, str, tuple[str, ...]], ...]:+ compatible = {+ c if isinstance(c, str) else getattr(c, "__name__", "")+ for c in (getattr(scheduler_cls, "_compatibles", None) or ())+ }+ if not compatible:+ return ()+ import diffusers++ options = []+ for sid, (label, cls_name, _overrides) in SAMPLERS.items():+ if cls_name is not None and cls_name not in compatible:+ continue+ cls = scheduler_cls if cls_name is None else getattr(diffusers, cls_name, None)+ if cls is None:+ continue+ options.append((sid, label, tuple(_schedule_types_for(cls))))+ return tuple(options) if len(options) > 1 else ()+++def sampler_options(scheduler: Any) -> list[dict[str, Any]]:+ """Samplers the resident scheduler can be swapped for, each with the schedule types it takes.++ Empty when the scheduler lists no compatible classes (every flow-matching model), so the+ control is absent there rather than offering choices that cannot run. Read on every status poll,+ hence cached per class."""+ config = getattr(scheduler, "config", None) or {}+ # A DPM / UniPC scheduler driving a flow model lists the epsilon samplers as compatible too.+ if (+ scheduler is None+ or config.get("use_flow_sigmas")+ or config.get("prediction_type") == "flow_prediction"+ ):+ return []+ return [+ {"id": sid, "label": label, "schedule_types": list(types)}+ for sid, label, types in _options_for(type(scheduler))+ ]+++def resolve_schedule(+ sampler: Optional[str],+ schedule_type: Optional[str],+ config: Any = None,+) -> Optional[str]:+ """The schedule a request runs: ``automatic`` resolves to the sampler's A1111 default, None = config's."""+ schedule_type = schedule_type or AUTOMATIC_SCHEDULE+ if schedule_type != AUTOMATIC_SCHEDULE:+ return schedule_type+ resolved = _AUTOMATIC_FOR.get(sampler or DEFAULT_SAMPLER)+ # Exponential spacing down from a zero-SNR sigma_max (~4096) washes out detail (NoobAI-XL V-Pred 1.0).+ if resolved == "exponential" and (config or {}).get("rescale_betas_zero_snr"):+ return "karras"+ return resolved+++def build_scheduler(+ resident: Any, sampler: Optional[str], schedule_type: Optional[str]+) -> tuple[Optional[Any], Optional[str]]:+ """``(scheduler, resolved schedule)`` for a request; scheduler None keeps ``resident`` as is.++ Built from the resident config, so prediction type and zero-SNR settings carry over. Raises+ ValueError for a choice this model does not offer."""+ sampler = sampler or DEFAULT_SAMPLER+ schedule_type = schedule_type or AUTOMATIC_SCHEDULE+ if sampler not in SAMPLERS:+ raise ValueError(f"Unknown sampler '{sampler}'.")+ if schedule_type not in SCHEDULE_TYPES:+ raise ValueError(f"Unknown schedule type '{schedule_type}'.")+ if sampler == DEFAULT_SAMPLER and schedule_type == AUTOMATIC_SCHEDULE:+ return None, None+ options = {o["id"]: o for o in sampler_options(resident)}+ if sampler not in options:+ raise ValueError(+ f"The {SAMPLERS[sampler][0]} sampler is not available for the loaded model."+ )+ if schedule_type not in options[sampler]["schedule_types"]:+ raise ValueError(+ f"The {SCHEDULE_TYPES[schedule_type][0]} schedule type does not apply to the "+ f"{SAMPLERS[sampler][0]} sampler."+ )+ cls = _class_for(sampler, resident)+ params = _init_params(cls)+ overrides = {k: v for k, v in SAMPLERS[sampler][2].items() if k in params}+ resolved = resolve_schedule(sampler, schedule_type, resident.config)+ if resolved is not None:+ flag = SCHEDULE_TYPES[resolved][1]+ for name in _SIGMA_FLAGS:+ if name in params:+ overrides[name] = name == flag+ built = cls.from_config(resident.config, **overrides)+ set_begin_index = getattr(built, "set_begin_index", None)+ if callable(set_begin_index):+ # Zero-SNR Karras grids repeat 999; without a begin index (SDXL ControlNet sets none) DPM++ overruns.+ set_timesteps = built.set_timesteps++ @wraps(set_timesteps)+ def _set_timesteps(*args: Any, **kwargs: Any) -> Any:+ out = set_timesteps(*args, **kwargs)+ set_begin_index(0)+ return out++ built.set_timesteps = _set_timesteps+ return built, resolved+++def sampler_label(sampler: Optional[str]) -> Optional[str]:+ entry = SAMPLERS.get(sampler or "")+ return entry[0] if entry and sampler != DEFAULT_SAMPLER else None+++def schedule_label(schedule_type: Optional[str]) -> Optional[str]:+ entry = SCHEDULE_TYPES.get(schedule_type or "")+ return entry[0] if entry and schedule_type != AUTOMATIC_SCHEDULE else None+++def _safetensors_top_level_keys(path: str) -> frozenset[str]:+ import json+ import struct++ with open(path, "rb") as fh:+ (size,) = struct.unpack("<Q", fh.read(8))+ if size <= 0 or size > 100_000_000:+ return frozenset()+ header = json.loads(fh.read(size))+ return frozenset(k for k in header if "." not in k)+++def checkpoint_prediction_overrides(path: Optional[str]) -> dict[str, Any]:+ """Scheduler overrides a single-file checkpoint asks for through its ``v_pred`` / ``ztsnr`` marker+ tensors (ComfyUI's detection, comfy/supported_models.py SDXL.model_type). Empty when unmarked."""+ if not path or not str(path).endswith(".safetensors"):+ return {}+ try:+ keys = _safetensors_top_level_keys(str(path))+ except Exception: # noqa: BLE001 - an unreadable header keeps the shipped scheduler+ return {}+ if "v_pred" not in keys:+ return {}+ overrides: dict[str, Any] = {"prediction_type": "v_prediction"}+ if "ztsnr" in keys:+ # Zero terminal SNR samples from the last timestep (arXiv 2305.08891, section 3.3).+ overrides.update(rescale_betas_zero_snr = True, timestep_spacing = "trailing")+ return overrides+++def apply_checkpoint_prediction_type(+ pipe: Any,+ path: Optional[str],+ logger: Any = None,+) -> bool:+ """Rebuild ``pipe.scheduler`` for a v-prediction checkpoint. True when it changed; idempotent."""+ overrides = checkpoint_prediction_overrides(path)+ scheduler = getattr(pipe, "scheduler", None)+ config = getattr(scheduler, "config", None)+ if not overrides or config is None:+ return False+ params = _init_params(type(scheduler))+ overrides = {k: v for k, v in overrides.items() if k in params}+ if all(config.get(k) == v for k, v in overrides.items()):+ return False+ pipe.scheduler = type(scheduler).from_config(config, **overrides)+ if logger is not None:+ logger.info("scheduler set from checkpoint markers: %s", overrides)+ return Truediff --git a/studio/backend/core/inference/image_gallery.py b/studio/backend/core/inference/image_gallery.pyindex 9b53a99e243..c2928ca5da7 100644--- a/studio/backend/core/inference/image_gallery.py+++ b/studio/backend/core/inference/image_gallery.py@@ -49,8 +49,15 @@ def _params_text(meta: dict[str, Any]) -> str:negative = meta.get("negative_prompt")if negative:lines.append(f"Negative prompt: {negative}")+ from core.inference.diffusion_sampler import sampler_label, schedule_label++ sampler = sampler_label(meta.get("sampler"))+ schedule = schedule_label(meta.get("schedule_type"))lines.append(- f"Steps: {meta.get('steps')}, CFG scale: {meta.get('guidance')}, "+ f"Steps: {meta.get('steps')}, "+ + (f"Sampler: {sampler}, " if sampler else "")+ + (f"Schedule type: {schedule}, " if schedule else "")+ + f"CFG scale: {meta.get('guidance')}, "f"Seed: {meta.get('seed')}, Size: {meta.get('width')}x{meta.get('height')}, "f"Model: {meta.get('model', '')}")diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 75067a8a05a..d170b68bc86 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -4832,6 +4832,16 @@ class DiffusionGenerateRequest(BaseModel):"Omitted applies none and behaves exactly as before. Rejected with a clear message when ""the loaded model or its quantisation can't apply ControlNet.",)+ sampler: Optional[Literal["default", "euler", "euler_a", "dpmpp_2m", "dpmpp_2m_sde"]] = Field(+ None,+ description = "Sampler for this generation, one of the loaded model's status `samplers` ids. "+ "Omitted or 'default' keeps the model's shipped scheduler.",+ )+ schedule_type: Optional[Literal["automatic", "uniform", "karras", "exponential"]] = Field(+ None,+ description = "Noise schedule for the sampler. Omitted or 'automatic' uses the sampler's "+ "usual schedule (Karras for DPM++ 2M, Exponential for DPM++ 2M SDE, else the model's).",+ )@field_validator("loras")@classmethod@@ -5000,6 +5010,12 @@ class GalleryImage(BaseModel):localized_edit: Optional[str] = Field(None, description = "Localized edit convention used: annotate, paint or mask")+ sampler: Optional[str] = Field(+ None, description = "Sampler id the image ran with; null = the model's shipped scheduler"+ )+ schedule_type: Optional[str] = Field(+ None, description = "Schedule type the sampler ran with (resolved); null = the config's"+ )created_at: float = Field(..., description = "Creation time (epoch seconds)")# Library state, not recipe: stored beside the PNG, so older files simply read as unset.pinned: bool = Field(False, description = "Pinned to the front of the gallery")@@ -5302,6 +5318,12 @@ class DiffusionStatusResponse(BaseModel):"(drives the Negative prompt field). False for FLUX and Ideogram 4 on diffusers, and ""for FLUX.1 / Kontext / FLUX.2-dev on the native engine.",)+ samplers: list[Dict[str, Any]] = Field(+ default_factory = list,+ description = "Samplers the loaded model can run, each {id, label, schedule_types}; the "+ "first is 'default' (the shipped scheduler). Empty when there is no choice: flow-matching "+ "models, the native and MLX engines, or nothing loaded.",+ )# declare provenance explicitly because Pydantic extra="ignore" would otherwise discard it.resolved: Optional[Dict[str, DiffusionResolvedControl]] = Field(None,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex fb3cd0f735a..1049fc206d8 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -46981,6 +46981,22 @@ def _live_preview_kwarg(generate: Any, requested: Optional[bool]) -> dict:return {}+def _sampler_kwargs(generate: Any, sampler: Optional[str], schedule_type: Optional[str]) -> dict:+ """``sampler`` / ``schedule_type`` for an engine whose generate() takes them (diffusers only).++ A real choice sent to another engine is refused (ValueError -> 400) rather than ignored, so a+ recipe never records a sampler that did not run."""+ try:+ import inspect+ if "sampler" in inspect.signature(generate).parameters:+ return {"sampler": sampler, "schedule_type": schedule_type}+ except (TypeError, ValueError):+ pass+ if sampler not in (None, "default") or schedule_type not in (None, "automatic"):+ raise ValueError("Choosing a sampler is supported on the diffusers engine only.")+ return {}++# Count of finished generations still writing their PNG/gallery records; generate-progress reports active while above 0. Mutated only on the event loop, so no lock._diffusion_persist_active = 0@@ -47118,6 +47134,7 @@ async def generate_diffusion_image(else None),**_live_preview_kwarg(backend.generate, request.live_preview),+ **_sampler_kwargs(backend.generate, request.sampler, request.schedule_type),)breakexcept ImageActivationShortfallError as exc:@@ -47226,6 +47243,8 @@ async def generate_diffusion_image(# From the engine, not the request: an omitted resolution resolves to the family default."reference_resolution": result.get("reference_resolution"),"localized_edit": result.get("localized_edit"),+ "sampler": result.get("sampler"),+ "schedule_type": result.get("schedule_type"),"created_at": created_at,},)diff --git a/studio/backend/tests/test_diffusion_sampler.py b/studio/backend/tests/test_diffusion_sampler.pynew file mode 100644index 00000000000..0b497021c0d--- /dev/null+++ b/studio/backend/tests/test_diffusion_sampler.py@@ -0,0 +1,222 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Images page sampler choice and the v-prediction markers of single-file SDXL checkpoints."""++from __future__ import annotations++import types++import pytest++diffusers = pytest.importorskip("diffusers")++from core.inference.diffusion_sampler import (+ apply_checkpoint_prediction_type,+ build_scheduler,+ checkpoint_prediction_overrides,+ sampler_options,+)+from core.inference.image_gallery import _params_text++# stabilityai/stable-diffusion-xl-base-1.0 scheduler/scheduler_config.json+_SDXL = dict(+ beta_end = 0.012,+ beta_schedule = "scaled_linear",+ beta_start = 0.00085,+ clip_sample = False,+ interpolation_type = "linear",+ num_train_timesteps = 1000,+ prediction_type = "epsilon",+ sample_max_value = 1.0,+ set_alpha_to_one = False,+ skip_prk_steps = True,+ steps_offset = 1,+ timestep_spacing = "leading",+ trained_betas = None,+ use_karras_sigmas = False,+)+++def _sdxl(**overrides):+ return diffusers.EulerDiscreteScheduler.from_config({**_SDXL, **overrides})+++def test_sdxl_offers_the_popular_samplers():+ options = {o["id"]: o["schedule_types"] for o in sampler_options(_sdxl())}+ assert list(options) == ["default", "euler", "euler_a", "dpmpp_2m", "dpmpp_2m_sde"]+ assert options["dpmpp_2m"] == ["automatic", "uniform", "karras", "exponential"]+ assert options["euler_a"] == ["automatic", "uniform"]+++def test_flow_matching_offers_nothing():+ assert sampler_options(diffusers.FlowMatchEulerDiscreteScheduler()) == []+ assert sampler_options(None) == []+++def test_flow_configured_dpm_offers_nothing():+ flow_dpm = diffusers.DPMSolverMultistepScheduler(+ use_flow_sigmas = True, prediction_type = "flow_prediction"+ )+ assert sampler_options(flow_dpm) == []+++def test_uniform_clears_an_inherited_lu_schedule():+ dpm = diffusers.DPMSolverMultistepScheduler.from_config({**_SDXL, "use_lu_lambdas": True})+ built, _ = build_scheduler(dpm, "dpmpp_2m", "uniform")+ assert built.config.use_lu_lambdas is False+ assert built.config.use_karras_sigmas is False+++def test_default_keeps_the_shipped_scheduler():+ assert build_scheduler(_sdxl(), None, None) == (None, None)+ assert build_scheduler(_sdxl(), "default", "automatic") == (None, None)+++ "sampler, schedule, cls, algorithm, flags",+ [+ ("dpmpp_2m", "automatic", "DPMSolverMultistepScheduler", "dpmsolver++", "karras"),+ ("dpmpp_2m_sde", None, "DPMSolverMultistepScheduler", "sde-dpmsolver++", "exponential"),+ ("dpmpp_2m", "uniform", "DPMSolverMultistepScheduler", "dpmsolver++", "uniform"),+ ("euler", "karras", "EulerDiscreteScheduler", None, "karras"),+ ("default", "exponential", "EulerDiscreteScheduler", None, "exponential"),+ ],+)+def test_build_scheduler(sampler, schedule, cls, algorithm, flags):+ built, resolved = build_scheduler(_sdxl(use_karras_sigmas = True), sampler, schedule)+ assert type(built).__name__ == cls+ assert resolved == flags+ assert built.config.use_karras_sigmas is (flags == "karras")+ assert built.config.use_exponential_sigmas is (flags == "exponential")+ if algorithm:+ assert built.config.algorithm_type == algorithm+++def test_euler_a_automatic_keeps_the_config_spacing():+ built, resolved = build_scheduler(_sdxl(), "euler_a", None)+ assert type(built).__name__ == "EulerAncestralDiscreteScheduler"+ assert resolved is None+ assert built.config.timestep_spacing == "leading"+++def test_prediction_settings_carry_over():+ vpred = _sdxl(+ prediction_type = "v_prediction",+ rescale_betas_zero_snr = True,+ timestep_spacing = "trailing",+ )+ for sampler in ("euler_a", "dpmpp_2m", "dpmpp_2m_sde"):+ built, _ = build_scheduler(vpred, sampler, None)+ assert built.config.prediction_type == "v_prediction"+ assert built.config.rescale_betas_zero_snr is True+ assert built.config.timestep_spacing == "trailing"+++def test_zero_snr_automatic_avoids_exponential():+ vpred = _sdxl(prediction_type = "v_prediction", rescale_betas_zero_snr = True)+ built, resolved = build_scheduler(vpred, "dpmpp_2m_sde", "automatic")+ assert resolved == "karras"+ assert built.config.use_karras_sigmas is True+ assert build_scheduler(vpred, "dpmpp_2m_sde", "exponential")[1] == "exponential"++[email protected]("sampler", ["dpmpp_2m", "dpmpp_2m_sde"])+def test_zero_snr_karras_runs_every_step_without_a_pipeline_begin_index(sampler):+ # The SDXL ControlNet pipeline never calls set_begin_index; the duplicate first timestep overran.+ torch = pytest.importorskip("torch")+ vpred = _sdxl(+ prediction_type = "v_prediction", rescale_betas_zero_snr = True, timestep_spacing = "trailing"+ )+ built, _ = build_scheduler(vpred, sampler, "karras")+ built.set_timesteps(28)+ assert built.timesteps[0] == built.timesteps[1]+ sample = torch.randn(1, 4, 8, 8)+ generator = torch.Generator().manual_seed(0)+ for t in built.timesteps:+ sample = built.step(torch.zeros_like(sample), t, sample, generator = generator).prev_sample+ assert torch.isfinite(sample).all()+++def test_unavailable_choices_are_refused():+ with pytest.raises(ValueError, match = "does not apply"):+ build_scheduler(_sdxl(), "euler_a", "karras")+ with pytest.raises(ValueError, match = "not available"):+ build_scheduler(diffusers.FlowMatchEulerDiscreteScheduler(), "euler", None)+ with pytest.raises(ValueError, match = "Unknown sampler"):+ build_scheduler(_sdxl(), "lms", None)+++def _checkpoint(path, *markers):+ torch = pytest.importorskip("torch")+ from safetensors.torch import save_file++ tensors = {"model.diffusion_model.input_blocks.0.0.weight": torch.zeros(2)}+ tensors.update({m: torch.zeros(0) for m in markers})+ save_file(tensors, str(path))+ return str(path)+++def test_vpred_ztsnr_markers(tmp_path):+ pipe = types.SimpleNamespace(scheduler = _sdxl())+ path = _checkpoint(tmp_path / "noob.safetensors", "v_pred", "ztsnr")+ assert apply_checkpoint_prediction_type(pipe, path) is True+ config = pipe.scheduler.config+ assert type(pipe.scheduler).__name__ == "EulerDiscreteScheduler"+ assert config.prediction_type == "v_prediction"+ assert config.rescale_betas_zero_snr is True+ assert config.timestep_spacing == "trailing"+ assert apply_checkpoint_prediction_type(pipe, path) is False+++def test_vpred_marker_without_ztsnr(tmp_path):+ path = _checkpoint(tmp_path / "vpred.safetensors", "v_pred")+ assert checkpoint_prediction_overrides(path) == {"prediction_type": "v_prediction"}+++def test_unmarked_and_unreadable_checkpoints_keep_epsilon(tmp_path):+ pipe = types.SimpleNamespace(scheduler = _sdxl())+ plain = _checkpoint(tmp_path / "sdxl.safetensors")+ assert apply_checkpoint_prediction_type(pipe, plain) is False+ junk = tmp_path / "junk.safetensors"+ junk.write_bytes(b"not a safetensors file")+ assert apply_checkpoint_prediction_type(pipe, str(junk)) is False+ assert apply_checkpoint_prediction_type(pipe, None) is False+ assert pipe.scheduler.config.prediction_type == "epsilon"+++def _meta(**extra):+ return dict(+ prompt = "a cat", steps = 25, guidance = 7, seed = 1, width = 1024, height = 1024, model = "m", **extra+ )+++def test_parameters_text_names_the_sampler():+ text = _params_text(_meta(sampler = "dpmpp_2m", schedule_type = "karras"))+ assert "Steps: 25, Sampler: DPM++ 2M, Schedule type: Karras, CFG scale: 7," in text+ assert "Sampler" not in _params_text(_meta())+ assert "Schedule type" not in _params_text(_meta(sampler = "euler_a"))+++def test_route_refuses_a_sampler_the_engine_cannot_run():+ from routes.inference import _sampler_kwargs++ def native_generate(*, prompt):+ return None++ def diffusers_generate(+ *,+ prompt,+ sampler = None,+ schedule_type = None,+ ):+ return None++ assert _sampler_kwargs(native_generate, None, None) == {}+ assert _sampler_kwargs(native_generate, "default", "automatic") == {}+ with pytest.raises(ValueError, match = "diffusers engine only"):+ _sampler_kwargs(native_generate, "dpmpp_2m", None)+ assert _sampler_kwargs(diffusers_generate, "euler", "karras") == {+ "sampler": "euler",+ "schedule_type": "karras",+ }diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 34ca4489623..bc08b8c2ad2 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -74,6 +74,8 @@ export interface DiffusionStatus {// Whether the loaded model can apply a ControlNet. Diffusers only, for families with a ControlNet pipeline.supports_controlnet?: boolean;supports_negative_prompt?: boolean;+ // "default" first; empty or absent = no choice (flow models, native / MLX engines, older backend).+ samplers?: DiffusionSamplerOption[];// Per-Advanced-control provenance, keyed by control name. Present only when a model is loaded on a// backend that records it; absent on older backends.resolved?: Record<string, DiffusionResolvedControl> | null;@@ -81,6 +83,12 @@ export interface DiffusionStatus {generation_defaults?: { steps?: number; guidance?: number } | null;}+export interface DiffusionSamplerOption {+ id: string;+ label: string;+ schedule_types: string[];+}+export interface DiffusionConditioning {// Total input images per call, INCLUDING the source.max_condition_images: number;@@ -201,6 +209,8 @@ export interface DiffusionGenerateRequest {loras?: LoraSpecInput[];// ControlNet conditioning for this generation. Rejected (400) when the loaded model cannot apply ControlNet.controlnet?: ControlNetSpecInput;+ sampler?: string;+ schedule_type?: string;}// One LoRA selection sent with a generation.@@ -286,6 +296,9 @@ export interface GalleryImage {reference_image_count?: number | null;reference_resolution?: number | null;localized_edit?: LocalizedEditMode | null;+ // null = the model's shipped scheduler; schedule_type is the resolved schedule.+ sampler?: string | null;+ schedule_type?: string | null;created_at: number;// Library state, not recipe: stored beside the PNG, absent on records written before this existed.pinned?: boolean;diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex b8dcc466f98..9f8510539c3 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -234,6 +234,7 @@ import {type DiffusionLoadProgress,type DiffusionLoadRequest,type DiffusionLoraInfo,+ type DiffusionSamplerOption,type DiffusionStatus,type LocalizedEditMode,type GalleryImage,@@ -273,6 +274,17 @@ import {shouldOfferGenerateAnyway,shouldRunQueuedOversizedRetry,} from "./lib/memory-refusal";+import {+ AUTOMATIC_SCHEDULE,+ DEFAULT_SAMPLER,+ normalizeSamplerChoice,+ readSamplerChoices,+ type SamplerChoice,+ samplerRecipeLabel,+ samplerRequestFields,+ SCHEDULE_LABELS,+ withSamplerChoice,+} from "./lib/sampler-choice";import { useNavigate, useSearch } from "@tanstack/react-router";import { useStagedDownload, type StagedDownloadEntry } from "@/features/hub/download-manager";import { DiffusionTrainPanel } from "./train/diffusion-train-panel";@@ -707,6 +719,8 @@ function loadToastArgs(};}+const NO_SAMPLERS: DiffusionSamplerOption[] = [];+const IDLE_PROGRESS: DiffusionLoadProgress = {phase: null,bytes_downloaded: 0,@@ -1278,6 +1292,12 @@ function RecipePopover({<RecipeRow label="Size" value={`${image.width} × ${image.height}`} /><RecipeRow label="Steps" value={String(image.steps)} /><RecipeRow label="Guidance" value={String(image.guidance)} />+ {samplerRecipeLabel(image.sampler, image.schedule_type) ? (+ <RecipeRow+ label="Sampler"+ value={samplerRecipeLabel(image.sampler, image.schedule_type) ?? ""}+ />+ ) : null}<RecipeRow label="Seed" value={String(image.seed)} mono /></div><div className="shrink-0 border-t border-border/60 px-3 py-2.5">@@ -1483,6 +1503,9 @@ export function ImagesPage({// Z-Image-Turbo official defaults: 9 steps (= 8 DiT forwards), guidance 0 (distilled, CFG-free).const [steps, setSteps] = useState(DEFAULT_GEN.steps);const [guidance, setGuidance] = useState(DEFAULT_GEN.guidance);+ const [samplerChoices, setSamplerChoices] = useState(readSamplerChoices);+ // A recipe restored while unloaded: Generate recalls the model, uses this, and stores it for that model.+ const [restoredSampler, setRestoredSampler] = useState<Partial<SamplerChoice> | null>(null);// Whether the user has taken the recipe since the pick still waiting for its status: a preset// selected while the model downloaded is newer than that pick.const pickRecipeSuperseded = useRef<(() => boolean) | null>(null);@@ -1939,6 +1962,26 @@ export function ImagesPage({// Refresh the ControlNet options when the loaded family changes, and clear a stale selection.const controlnetCapable = Boolean(status?.loaded && status?.supports_controlnet);const negativeCapable = status?.supports_negative_prompt !== false;+ const samplerOptions = (status?.loaded ? status.samplers : null) ?? NO_SAMPLERS;+ // The checkpoint, not residentDefaults: community SDXL files all share the SDXL base repo.+ const samplerModelKey = status?.loaded ? `${status.repo_id ?? ""}|${status.gguf_filename ?? ""}` : "";+ const samplerChoice = normalizeSamplerChoice(+ samplerOptions,+ restoredSampler ?? samplerChoices[samplerModelKey],+ );+ const changeSamplerChoice = useCallback(+ (next: Partial<SamplerChoice>) => {+ setRestoredSampler(null);+ setSamplerChoices((all) =>+ withSamplerChoice(+ all,+ samplerModelKey,+ normalizeSamplerChoice(samplerOptions, { ...samplerChoice, ...next }),+ ),+ );+ },+ [samplerChoice, samplerModelKey, samplerOptions],+ );useEffect(() => {if (!controlnetCapable) {setAvailableControlNets([]);@@ -2456,6 +2499,12 @@ export function ImagesPage({if (restoredNegative) setNegativeOpen(true);setSteps(image.steps);setGuidance(image.guidance);+ const restoredChoice = {+ sampler: image.sampler ?? DEFAULT_SAMPLER,+ scheduleType: image.schedule_type ?? AUTOMATIC_SCHEDULE,+ };+ if (samplerOptions.length > 0) changeSamplerChoice(restoredChoice);+ else setRestoredSampler(restoredChoice);// Restore from the BASE batch seed, not this image's derived seed, or a replay with batch_size// advances it again.setSeed(String(image.batch_seed ?? image.seed));@@ -2520,7 +2569,7 @@ export function ImagesPage({} else {toast.success("Settings restored to inputs", rescaled);}- }, [setPromptFor, setWorkflow, sizeLimits]);+ }, [changeSamplerChoice, samplerOptions.length, setPromptFor, setWorkflow, sizeLimits]);// A locked ratio keeps the paired dimension in step; "custom" frees both, Flip swaps W/H. ratioHW is h/w for [a,b].const ratioHW = (a: number, b: number) => (portrait ? a / b : b / a);@@ -4220,6 +4269,10 @@ export function ImagesPage({toast.error("Prompt is empty");return;}+ if (restoredSampler && samplerOptions.length > 0) {+ setRestoredSampler(null);+ setSamplerChoices((all) => withSamplerChoice(all, samplerModelKey, samplerChoice));+ }const isTransform = workflow === "transform";const isInpaint = workflow === "inpaint";const isExtend = workflow === "extend";@@ -4441,6 +4494,7 @@ export function ImagesPage({upscale: condUpscale,allow_oversized: allowOversizedSent ? true : undefined,live_preview: livePreview,+ ...samplerRequestFields(samplerOptions, samplerChoice),...condFields,// Drop empty and zero-weight rows and trim hand-typed repo ids, so the recipe records only// adapters that applied. Gated on loraCapable, since a restore can leave adapters in state.@@ -4527,7 +4581,7 @@ export function ImagesPage({setGenStep(null);setStopping(false);}- }, [allowOversized, livePreview, prompt, negativePrompt, negativeCapable, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);+ }, [allowOversized, livePreview, prompt, negativePrompt, negativeCapable, restoredSampler, samplerModelKey, samplerOptions, samplerChoice, width, height, steps, guidance, seed, batchSize, count, workflow, initImage, maskImage, strength, extendPct, extendSides, upscaleFactor, upscaleStrength, referenceImages, loras, loraCapable, controlnetCapable, controlnetId, controlImage, controlType, controlStrength, ensureSrc, loadGallery, refreshStatus, unifiedEdit, localizedMode, localizedLayer, maxExtras, referenceResolution, conditioning, editSize, editSizing, sizeLimits]);// Stop the in-flight generation. Latch FIRST, so a multi-run request stops even if the POST// races the run that is already finishing.@@ -5676,6 +5730,49 @@ export function ImagesPage({onChange={setCount}/>{/* A slider row ends flush with its track, so the label below needs room. */}+ {samplerOptions.length > 1 && (+ <Field+ label="Sampler"+ hint="How each denoising step is taken. Model default keeps the scheduler the model ships with. Community checkpoints often name one, such as DPM++ 2M with Karras."+ className="pt-2"+ >+ <div className="flex items-center gap-2">+ <Select+ value={samplerChoice.sampler}+ onValueChange={(v) => changeSamplerChoice({ sampler: v })}+ >+ <SelectTrigger className="h-8 flex-1 text-xs" aria-label="Sampler">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {samplerOptions.map((o) => (+ <SelectItem key={o.id} value={o.id}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <Select+ value={samplerChoice.scheduleType}+ onValueChange={(v) => changeSamplerChoice({ scheduleType: v })}+ >+ <SelectTrigger className="h-8 w-32 text-xs" aria-label="Schedule type">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(+ samplerOptions.find((o) => o.id === samplerChoice.sampler)+ ?.schedule_types ?? [AUTOMATIC_SCHEDULE]+ ).map((t) => (+ <SelectItem key={t} value={t}>+ {SCHEDULE_LABELS[t] ?? t}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </Field>+ )}<Fieldlabel="Seed"hint="Leave empty for a fresh random seed each run."diff --git a/studio/frontend/src/features/images/lib/sampler-choice.ts b/studio/frontend/src/features/images/lib/sampler-choice.tsnew file mode 100644index 00000000000..b0ef28b3bfa--- /dev/null+++ b/studio/frontend/src/features/images/lib/sampler-choice.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++/** Backend ids: core/inference/diffusion_sampler.py. Labels follow AUTOMATIC1111. */+export const DEFAULT_SAMPLER = "default";+export const AUTOMATIC_SCHEDULE = "automatic";++const SAMPLER_LABELS: Record<string, string> = {+ default: "Model default",+ euler: "Euler",+ euler_a: "Euler a",+ dpmpp_2m: "DPM++ 2M",+ dpmpp_2m_sde: "DPM++ 2M SDE",+};++export const SCHEDULE_LABELS: Record<string, string> = {+ automatic: "Automatic",+ uniform: "Uniform",+ karras: "Karras",+ exponential: "Exponential",+};++export interface SamplerOption {+ id: string;+ label: string;+ schedule_types: string[];+}++export interface SamplerChoice {+ sampler: string;+ scheduleType: string;+}++export const DEFAULT_SAMPLER_CHOICE: SamplerChoice = {+ sampler: DEFAULT_SAMPLER,+ scheduleType: AUTOMATIC_SCHEDULE,+};++export function normalizeSamplerChoice(+ options: SamplerOption[],+ choice: Partial<SamplerChoice> | null | undefined,+): SamplerChoice {+ const option = options.find((o) => o.id === choice?.sampler);+ if (!option) return DEFAULT_SAMPLER_CHOICE;+ const scheduleType =+ choice?.scheduleType && option.schedule_types.includes(choice.scheduleType)+ ? choice.scheduleType+ : AUTOMATIC_SCHEDULE;+ return { sampler: option.id, scheduleType };+}++/** Request fields: omitted for the shipped scheduler, so the request is what it was before the control. */+export function samplerRequestFields(+ options: SamplerOption[],+ choice: SamplerChoice,+): { sampler?: string; schedule_type?: string } {+ const valid = normalizeSamplerChoice(options, choice);+ return {+ ...(valid.sampler !== DEFAULT_SAMPLER ? { sampler: valid.sampler } : {}),+ ...(valid.scheduleType !== AUTOMATIC_SCHEDULE ? { schedule_type: valid.scheduleType } : {}),+ };+}++export function samplerRecipeLabel(+ sampler: string | null | undefined,+ scheduleType: string | null | undefined,+): string | null {+ if (!sampler && !scheduleType) return null;+ const name = SAMPLER_LABELS[sampler ?? DEFAULT_SAMPLER] ?? sampler ?? "";+ const schedule = scheduleType ? (SCHEDULE_LABELS[scheduleType] ?? scheduleType) : "";+ return [name, schedule].filter(Boolean).join(" ");+}++const KEY = "unsloth:images:sampler-by-model";++export function readSamplerChoices(): Record<string, SamplerChoice> {+ try {+ const value = JSON.parse(localStorage.getItem(KEY) ?? "{}");+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};+ } catch {+ return {};+ }+}++export function withSamplerChoice(+ choices: Record<string, SamplerChoice>,+ modelKey: string,+ choice: SamplerChoice,+): Record<string, SamplerChoice> {+ if (!modelKey) return choices;+ const next = { ...choices };+ if (choice.sampler === DEFAULT_SAMPLER && choice.scheduleType === AUTOMATIC_SCHEDULE) {+ delete next[modelKey];+ } else {+ next[modelKey] = choice;+ }+ try {+ localStorage.setItem(KEY, JSON.stringify(next));+ } catch {+ // storage can be unavailable in private browsing+ }+ return next;+}diff --git a/studio/frontend/tests/images-sampler-choice.test.ts b/studio/frontend/tests/images-sampler-choice.test.tsnew file mode 100644index 00000000000..e1cd48c3d26--- /dev/null+++ b/studio/frontend/tests/images-sampler-choice.test.ts@@ -0,0 +1,72 @@+// 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 { installLocalStorageFake, readSrc } from "./helpers/kit.ts";+import {+ normalizeSamplerChoice,+ readSamplerChoices,+ samplerRecipeLabel,+ samplerRequestFields,+ withSamplerChoice,+} from "../src/features/images/lib/sampler-choice.ts";++const SDXL = [+ { id: "default", label: "Model default", schedule_types: ["automatic", "uniform", "karras", "exponential"] },+ { id: "euler_a", label: "Euler a", schedule_types: ["automatic", "uniform"] },+ { id: "dpmpp_2m", label: "DPM++ 2M", schedule_types: ["automatic", "uniform", "karras", "exponential"] },+];++test("the shipped scheduler sends the request it always sent", () => {+ assert.deepEqual(samplerRequestFields(SDXL, { sampler: "default", scheduleType: "automatic" }), {});+ assert.deepEqual(samplerRequestFields([], { sampler: "dpmpp_2m", scheduleType: "karras" }), {});+ assert.deepEqual(samplerRequestFields(SDXL, { sampler: "dpmpp_2m", scheduleType: "karras" }), {+ sampler: "dpmpp_2m",+ schedule_type: "karras",+ });+});++test("a choice the loaded model lacks falls back instead of failing the generation", () => {+ assert.deepEqual(normalizeSamplerChoice(SDXL, { sampler: "euler_a", scheduleType: "karras" }), {+ sampler: "euler_a",+ scheduleType: "automatic",+ });+ assert.deepEqual(normalizeSamplerChoice(SDXL, { sampler: "dpmpp_2m_sde" }), {+ sampler: "default",+ scheduleType: "automatic",+ });+ assert.deepEqual(normalizeSamplerChoice([], { sampler: "euler_a" }), {+ sampler: "default",+ scheduleType: "automatic",+ });+});++test("choices are remembered per model and the default is not stored", () => {+ const { store } = installLocalStorageFake();+ let all = withSamplerChoice({}, "sdxl-a", { sampler: "dpmpp_2m", scheduleType: "karras" });+ all = withSamplerChoice(all, "sdxl-b", { sampler: "euler_a", scheduleType: "automatic" });+ assert.deepEqual(readSamplerChoices(), all);+ all = withSamplerChoice(all, "sdxl-b", { sampler: "default", scheduleType: "automatic" });+ assert.deepEqual(Object.keys(readSamplerChoices()), ["sdxl-a"]);+ store.set("unsloth:images:sampler-by-model", "not json");+ assert.deepEqual(readSamplerChoices(), {});+});++test("recipe label", () => {+ assert.equal(samplerRecipeLabel("dpmpp_2m", "karras"), "DPM++ 2M Karras");+ assert.equal(samplerRecipeLabel("euler_a", null), "Euler a");+ assert.equal(samplerRecipeLabel(null, null), null);+});++test("the Images page sends, restores and shows the sampler only where the model offers one", () => {+ const page = readSrc("features/images/images-page.tsx");+ assert.match(page, /\.\.\.samplerRequestFields\(samplerOptions, samplerChoice\)/);+ assert.match(page, /samplerOptions\.length > 1 && \(/);+ assert.match(page, /scheduleType: image\.schedule_type \?\? AUTOMATIC_SCHEDULE/);+ assert.match(page, /if \(samplerOptions\.length > 0\) changeSamplerChoice\(restoredChoice\);\s*else setRestoredSampler\(restoredChoice\);/);+ // Consumed by the first Generate that has the model's options, then stored for that model only.+ assert.match(page, /setRestoredSampler\(null\);\s*setSamplerChoices\(\(all\) => withSamplerChoice\(all, samplerModelKey, samplerChoice\)\)/);+ assert.match(page, /restoredSampler \?\? samplerChoices\[samplerModelKey\]/);+});