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: diffusion flow_shift is the effective shift, and min-SNR is recorded as unused for flow-matching runs (#13215)
Daniel Han92fcec8e7467
diff --git a/studio/backend/core/training/diffusion_checkpoint.py b/studio/backend/core/training/diffusion_checkpoint.pyindex 83c4f880734..1ad643f2e92 100644--- a/studio/backend/core/training/diffusion_checkpoint.py+++ b/studio/backend/core/training/diffusion_checkpoint.py@@ -371,6 +371,22 @@ def _optional_float(value: Any) -> Optional[float]:return None+# Families whose scheduler bakes a static shift into ``sigmas`` (no dynamic shifting, shift != 1): Z-Image's 3 / 6.+_STATIC_SHIFT_FAMILIES = frozenset({"z-image"})+++def _flow_shift_key(value: Any, family: str = "") -> str:+ """None keeps the "1.0" earlier builds wrote. Numbers changed meaning only on static-shift+ families, so only those get a new token (older checkpoints are refused there)."""+ if value is None:+ return "1.0"+ if isinstance(value, str):+ return value+ if family in _STATIC_SHIFT_FAMILIES:+ return f"effective:{float(value)}"+ return str(float(value))++def _snr_gamma_key(value: Any) -> str:"""min-SNR as a comparable token. None DISABLES the weighting, so it gets its own value ratherthan the unknown the optional-field rule skips."""@@ -549,11 +565,16 @@ def identity_for_config(lora_alpha = int(cfg.lora_alpha if cfg.lora_alpha is not None else cfg.lora_rank),lora_dropout = round(float(getattr(cfg, "lora_dropout", 0.0) or 0.0), 6),cfg_dropout = round(float(getattr(cfg, "cfg_dropout", 0.0) or 0.0), 6),- # flow_shift is float | "auto" | None, so it is recorded as text: "auto" and the number it resolves to are- # different runs, and comparing them as floats would lose that.- flow_shift = str(getattr(cfg, "flow_shift", None)),+ flow_shift = _flow_shift_key(+ getattr(cfg, "flow_shift", None), str(getattr(cfg, "resolved_family", "") or "")+ ),weighting_scheme = str(getattr(cfg, "weighting_scheme", "") or "none"),- snr_gamma = _snr_gamma_key(getattr(cfg, "snr_gamma", None)),+ # Only the SDXL loop applies min-SNR, so a flow-matching run records "cannot tell" rather than the unused default.+ snr_gamma = (+ _snr_gamma_key(getattr(cfg, "snr_gamma", None))+ if str(getattr(cfg, "resolved_family", "") or "sdxl") == "sdxl"+ else None+ ),lr_scheduler = str(getattr(cfg, "lr_scheduler", "") or "constant"),lr_warmup_steps = int(getattr(cfg, "lr_warmup_steps", 0) or 0),seed = int(getattr(cfg, "seed", 0) or 0),diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex 765f8033ea0..11e92d3e7f3 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -177,19 +177,26 @@ def _gather_sigmas(sigma_table, indices, device, dtype, n_dim):return sigma+def _unshifted_sigmas(scheduler):+ """Uniform u before any init-time static shift, as ``FlowMatchEulerDiscreteScheduler.__init__`` builds it."""+ import numpy as np+ import torch++ sc = scheduler.config+ if getattr(sc, "use_dynamic_shifting", False) or float(getattr(sc, "shift", 1.0) or 1.0) == 1.0:+ return scheduler.sigmas+ n = int(sc.num_train_timesteps)+ u = torch.from_numpy(np.linspace(1, n, n, dtype = np.float32)[::-1].copy()) / n+ return u.to(scheduler.sigmas.dtype)++def _training_sigma_table(scheduler, flow_shift):- """The sigma table training draws index into, per ``cfg.flow_shift``. ``1.0`` (every non-Qwen- family's default) returns ``scheduler.sigmas`` unchanged: the historical behavior, correct- for the families whose schedule already matches training convention. ``"auto"`` (the- qwen-image default) reproduces the family's INFERENCE sigma distribution, which the scheduler- never bakes into ``sigmas`` when ``use_dynamic_shifting`` is true (the static ``shift`` at- init is skipped, so Qwen-Image otherwise trains on unshifted uniform sigmas): apply the- scheduler's own ``time_shift`` at mu = ``max_shift`` (Qwen pins base_shift = max_shift = log- 3, so the inference mu is constant at every resolution) followed by its- ``stretch_shift_to_terminal`` -- using the scheduler's methods keeps the transform faithful- across diffusers versions. A numeric value applies the standard linear shift s*u/(1+(s-1)*u)- (musubi/kohya style discrete_flow_shift)."""+ """None: the scheduler's own sigmas. "auto": the inference distribution, which dynamic-shifting+ schedulers never bake into ``sigmas`` (Qwen pins mu = max_shift = log 3). A number: the effective+ shift s*u/(1+(s-1)*u) on unshifted u (musubi/kohya); applying it on top of a baked-in shift is WRONG."""sigmas = scheduler.sigmas+ if flow_shift is None:+ return sigmasif flow_shift == "auto":sc = scheduler.configif not getattr(sc, "use_dynamic_shifting", False):@@ -197,14 +204,14 @@ def _training_sigma_table(scheduler, flow_shift):mu = float(getattr(sc, "max_shift", None) or math.log(3.0))shifted = scheduler.time_shift(mu, 1.0, sigmas)if getattr(sc, "shift_terminal", None):- # The stretch scales off the table's own final sigma, so it must see the full descending schedule, never a- # batch.+ # Stretch must see the full descending table, never a batch.shifted = scheduler.stretch_shift_to_terminal(shifted)return shifteds = float(flow_shift)+ u = _unshifted_sigmas(scheduler)if s == 1.0:- return sigmas- return s * sigmas / (1.0 + (s - 1.0) * sigmas)+ return u+ return s * u / (1.0 + (s - 1.0) * u)def _bell_loss_weights(num_train_timesteps):@@ -2126,8 +2133,8 @@ def _train_dit()# getattr defaults keep an un-normalized config on the historical behaviour.flow_shift = getattr(cfg, "flow_shift", None)- if flow_shift is None:- flow_shift = "auto" if spec.family in AUTO_FLOW_SHIFT_FAMILIES else 1.0+ if flow_shift is None and spec.family in AUTO_FLOW_SHIFT_FAMILIES:+ flow_shift = "auto"sigma_table = _training_sigma_table(scheduler, flow_shift)shift_active = sigma_table is not scheduler.sigmasnum_train_ts = scheduler.config.num_train_timestepsdiff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex 06145663869..3072b282d64 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -1037,8 +1037,7 @@ class DiffusionLoraConfig:# eager), "int8" (torchao weight-only), "fp8" (Ada/Hopper/Blackwell + compile) or "auto". Non-nf4 needs a dense# base.base_precision: str = "nf4"- # None resolves per family in normalized(); a number applies s*u/(1+(s-1)*u), and "auto" without dynamic shifting- # falls back to identity.+ # None: model's own schedule ("auto" for AUTO_FLOW_SHIFT_FAMILIES); a number is the effective shift on unshifted u.flow_shift: Optional[Any] = None# Per-sample probability of replacing the caption with the empty prompt (classifier-free-guidance dropout). 0.0# disables.@@ -1208,11 +1207,9 @@ class DiffusionLoraConfig:f"base_precision={base_precision!r} is not validated for training "f"{resolved_family}. Use 'nf4', 'int8', 'bf16', or 'auto'.")- # flow_shift: None resolves to the family default ("auto" only for qwen-image, whose scheduler skips its- # static shift under use_dynamic_shifting); an explicit value is validated and kept.flow_shift = self.flow_shift- if flow_shift is None:- flow_shift = "auto" if resolved_family in AUTO_FLOW_SHIFT_FAMILIES else 1.0+ if flow_shift is None and resolved_family in AUTO_FLOW_SHIFT_FAMILIES:+ flow_shift = "auto"if isinstance(flow_shift, str):flow_shift = flow_shift.strip().lower()if flow_shift != "auto":@@ -1222,7 +1219,7 @@ class DiffusionLoraConfig:raise ValueError(f"flow_shift must be a positive number or 'auto', got {self.flow_shift!r}") from exc- if not isinstance(flow_shift, str):+ if flow_shift is not None and not isinstance(flow_shift, str):flow_shift = float(flow_shift)# isfinite as well as positive: JSON accepts 1e309, which floats to inf and would poison every sampled# sigma while progress looks normal.@@ -1598,11 +1595,15 @@ def train_recipe_overrides(cfg: Any) -> dict[str, Any]:for the same reason ``h3_train_unsupported_reason`` is: the trainer applies these in theCHILD, while the run record is written by the PARENT from the config handed to``service.start``. Normalising in the trainer alone therefore fixed what ran and left- Previous Runs describing cropping, flipping and min-SNR weighting that never happened. Empty- for every other family: their loops honour all three."""- if (getattr(cfg, "resolved_family", "") or "").strip().lower() != "minimax-h3":- return {}- return dict(_H3_FIXED_RECIPE)+ Previous Runs describing cropping, flipping and min-SNR weighting that never happened. The+ other flow-matching families drop only min-SNR; SDXL honours all of them."""+ family = (getattr(cfg, "resolved_family", "") or "").strip().lower()+ if family == "minimax-h3":+ return dict(_H3_FIXED_RECIPE)+ # Min-SNR is an SDXL (epsilon-prediction) weighting; the flow-matching loops never read it.+ if family and family != "sdxl":+ return {"snr_gamma": None}+ return {}# LTX-2 is deliberately not here: it trains a style LoRA FROM still images, so it keeps the image discovery.diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex a9ded5d195c..0d04315f019 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -958,7 +958,10 @@ class DiffusionTrainingStartRequest(BaseModel):# Finite for the same reason as max_grad_norm: an inf gamma collapses every min-SNR weight to 1.0,# silently training on plain unweighted MSE.snr_gamma: Optional[float] = Field(- 5.0, gt = 0, allow_inf_nan = False, description = "Min-SNR loss weighting; null disables"+ 5.0,+ gt = 0,+ allow_inf_nan = False,+ description = "Min-SNR loss weighting (SDXL only; flow-matching families ignore it); null disables",)gradient_checkpointing: bool = Field(True)lr_scheduler: Literal[@@ -1023,8 +1026,10 @@ class DiffusionTrainingStartRequest(BaseModel):flow_shift: Optional[Union[float, Literal["auto"]]] = Field(None,description = (- "Flow-matching timestep shift. null uses the family default "- "(auto for qwen-image, 1.0 otherwise)."+ "Flow-matching timestep shift, as the effective shift on the unshifted schedule "+ "(musubi / kohya discrete_flow_shift; 1.0 trains unshifted). null uses the family "+ "default: auto for qwen-image, ltx-2 and minimax-h3, otherwise the model's own "+ "scheduler shift (3.0 for Z-Image-Turbo, 6.0 for Z-Image)."),)save_steps: int = Field(diff --git a/studio/backend/tests/test_diffusion_dit_trainer_flow_shift.py b/studio/backend/tests/test_diffusion_dit_trainer_flow_shift.pyindex dc1a9356242..e6037b983e0 100644--- a/studio/backend/tests/test_diffusion_dit_trainer_flow_shift.py+++ b/studio/backend/tests/test_diffusion_dit_trainer_flow_shift.py@@ -42,8 +42,8 @@ def _qwen_scheduler():def _flux_static_scheduler():# A static-shift scheduler (shift baked into sigmas at init, no dynamic shifting).- from diffusers import FlowMatchEulerDiscreteScheduler- return FlowMatchEulerDiscreteScheduler(num_train_timesteps = 1000, shift = 3.0)+ diffusers = pytest.importorskip("diffusers")+ return diffusers.FlowMatchEulerDiscreteScheduler(num_train_timesteps = 1000, shift = 3.0)# ── config resolution ─────────────────────────────────────────────────────────@@ -56,11 +56,11 @@ def test_flow_shift_defaults_per_family():flux = DiffusionLoraConfig(base_model = "black-forest-labs/FLUX.1-dev", data_dir = "d", output_dir = "o").normalized()- assert flux.flow_shift == 1.0+ assert flux.flow_shift is Nonezimg = DiffusionLoraConfig(base_model = "Tongyi-MAI/Z-Image-Turbo", data_dir = "d", output_dir = "o").normalized()- assert zimg.flow_shift == 1.0+ assert zimg.flow_shift is Nonedef test_flow_shift_explicit_values_and_validation():@@ -170,13 +170,60 @@ def test_numeric_table_applies_the_linear_shift():def test_identity_and_static_families_are_untouched():- # flow_shift 1.0 must return the scheduler's own table object (no numeric drift for FLUX / Z-Image / Krea 2), and "auto"- # on a static-shift scheduler is a no-op: its init already baked the shift into sigmas.+ # None returns the scheduler's own table; "auto" on a static-shift scheduler is a no-op.sched = _qwen_scheduler()+ assert _training_sigma_table(sched, None) is sched.sigmasassert _training_sigma_table(sched, 1.0) is sched.sigmasstatic = _flux_static_scheduler()+ assert _training_sigma_table(static, None) is static.sigmasassert _training_sigma_table(static, "auto") is static.sigmas- assert _training_sigma_table(static, 1.0) is static.sigmas+++def test_a_numeric_shift_is_the_effective_shift_on_a_static_scheduler():+ import torch++ # Z-Image-Turbo bakes in shift 3: a requested 3 is that schedule (not 9); 1.0 is unshifted.+ static = _flux_static_scheduler()+ assert torch.allclose(_training_sigma_table(static, 3.0), static.sigmas, atol = 1e-6)+ u = _training_sigma_table(static, 1.0)+ assert torch.allclose(u, torch.linspace(1.0, 0.001, 1000), atol = 1e-6)+ assert torch.allclose(_training_sigma_table(static, 2.0), 2.0 * u / (1.0 + u), atol = 1e-6)+++def test_the_resume_identity_keeps_the_default_token_and_drops_min_snr_for_flow_families():+ from core.training import diffusion_checkpoint as dc++ flux = DiffusionLoraConfig(+ base_model = "black-forest-labs/FLUX.1-dev", data_dir = "d", output_dir = "o"+ ).normalized()+ ident = dc.identity_for_config(flux)+ # Earlier builds recorded the model's own schedule as "1.0", so a default run still resumes their checkpoints.+ assert ident.flow_shift == "1.0"+ assert ident.snr_gamma is None+ old = dc.CheckpointIdentity.from_dict({**ident.as_dict(), "snr_gamma": "5.0"})+ assert old.mismatch_reason(ident) is None+ # FLUX.1 shifts dynamically, so older checkpoints still resume.+ flux_shifted = dc.identity_for_config(+ DiffusionLoraConfig(+ base_model = "black-forest-labs/FLUX.1-dev", data_dir = "d", output_dir = "o", flow_shift = 3.0+ ).normalized()+ )+ assert flux_shifted.flow_shift == "3.0"+ legacy = dc.CheckpointIdentity.from_dict({**flux_shifted.as_dict(), "flow_shift": "3.0"})+ assert legacy.mismatch_reason(flux_shifted) is None+ # Z-Image bakes a static shift in: a number is now effective, not on top of it, so an older run is refused.+ zimage_shifted = dc.identity_for_config(+ DiffusionLoraConfig(+ base_model = "Tongyi-MAI/Z-Image-Turbo", data_dir = "d", output_dir = "o", flow_shift = 3.0+ ).normalized()+ )+ assert zimage_shifted.flow_shift == "effective:3.0"+ legacy = dc.CheckpointIdentity.from_dict({**zimage_shifted.as_dict(), "flow_shift": "3.0"})+ assert "timestep shift" in (legacy.mismatch_reason(zimage_shifted) or "")+ sdxl = DiffusionLoraConfig(+ base_model = "stabilityai/stable-diffusion-xl-base-1.0", data_dir = "d", output_dir = "o"+ ).normalized()+ assert dc.identity_for_config(sdxl).snr_gamma == "5.0"def test_sampled_sigma_distribution_shifts_under_auto():diff --git a/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py b/studio/backend/tests/test_diffusion_dit_trainer_ltx2.pyindex c684caa5127..6c80ae84755 100644--- a/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py+++ b/studio/backend/tests/test_diffusion_dit_trainer_ltx2.py@@ -554,7 +554,7 @@ def test_ltx2_flow_shift_defaults_to_auto():flux = DiffusionLoraConfig(base_model = "black-forest-labs/FLUX.1-dev", data_dir = "d", output_dir = "o").normalized()- assert flux.flow_shift == 1.0+ assert flux.flow_shift is Nonedef test_ltx2_rejects_fp16_before_loading():diff --git a/studio/backend/tests/test_diffusion_h3_trainer.py b/studio/backend/tests/test_diffusion_h3_trainer.pyindex db6382990ef..8bd5019e015 100644--- a/studio/backend/tests/test_diffusion_h3_trainer.py+++ b/studio/backend/tests/test_diffusion_h3_trainer.py@@ -1318,14 +1318,21 @@ def test_the_persisted_h3_recipe_is_the_one_the_loop_runs():"cache_latents": True,"cache_variants": 1,}- # Config-only, and no other family's loop disagrees with its request.+ # Config-only: the other flow-matching loops disagree only on min-SNR, and SDXL on nothing.other = DiffusionLoraConfig(base_model = "black-forest-labs/FLUX.1-dev",data_dir = "/tmp/d",output_dir = "/tmp/o",instance_prompt = "p",).normalized()- assert train_recipe_overrides(other) == {}+ assert train_recipe_overrides(other) == {"snr_gamma": None}+ sdxl = DiffusionLoraConfig(+ base_model = "stabilityai/stable-diffusion-xl-base-1.0",+ data_dir = "/tmp/d",+ output_dir = "/tmp/o",+ instance_prompt = "p",+ ).normalized()+ assert train_recipe_overrides(sdxl) == {}# The two appliers: the trainer for what runs, the service for what is recorded.from core.training import diffusion_h3_trainer