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: sample images during image LoRA training (#13220)
Daniel Han33176a75e956
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex 1b100ce1d50..38047ed9764 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -81,6 +81,13 @@ from core.training.diffusion_checkpoint import (with_resolved_revision,preflight_resume,)+from core.training.diffusion_samples import (+ discard_samples,+ euler_flow_sample,+ isolated_sampling,+ plan_samples,+ run_sample_round,+)from core.training.diffusion_train_extras import (BucketBatchSampler,LoRAEMA,@@ -168,6 +175,10 @@ class _FamilySpec:forward: Callable[..., Any]# Save the LoRA in diffusers format via the family pipeline's save_lora_weights.save: Callable[..., None]+ # (vae, h, w) -> (latent shape, packed seq len for the shift), and latents -> pixels. None = no sampling path.+ latent_shape: Optional[Callable[..., tuple]] = None+ decode_latents: Optional[Callable[..., Any]] = None+ sample_forward_kwargs: Optional[dict] = Nonedef _gather_sigmas(sigma_table, indices, device, dtype, n_dim):@@ -698,28 +709,45 @@ def _flux_collate(_FLUX_STATIC: dict[tuple, tuple] = {}-def _flux_static_inputs(bsz, h, w, device):+def _flux_static_inputs(+ bsz,+ h,+ w,+ device,+ guidance_value = 1.0,+):import torchfrom diffusers import FluxPipeline- key = (bsz, h, w, str(device))+ key = (bsz, h, w, str(device), float(guidance_value))hit = _FLUX_STATIC.get(key)if hit is None:# Position ids drive RoPE and are indices, not activations, so keep them float32 regardless of the training# dtype.img_ids = FluxPipeline._prepare_latent_image_ids(bsz, h // 2, w // 2, device, torch.float32)- guidance = torch.full((bsz,), 1.0, device = device, dtype = torch.float32)+ guidance = torch.full((bsz,), float(guidance_value), device = device, dtype = torch.float32)hit = _FLUX_STATIC[key] = (img_ids, guidance)return hit-def _flux_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, device, weight_dtype):+def _flux_forward(+ transformer,+ noisy,+ timesteps,+ sigmas,+ embeds_batch,+ cfg,+ device,+ weight_dtype,+ guidance = 1.0,+):from diffusers import FluxPipelinepe, pooled, text_ids = embeds_batchbsz, c, h, w = noisy.shapepacked = FluxPipeline._pack_latents(noisy, bsz, c, h, w)- img_ids, guidance = _flux_static_inputs(bsz, h, w, device)+ # Training feeds guidance 1.0 (diffusers dreambooth convention); sampling feeds the inference 3.5.+ img_ids, guidance = _flux_static_inputs(bsz, h, w, device, guidance)model_pred = transformer(hidden_states = packed,timestep = timesteps / 1000,@@ -1137,7 +1165,17 @@ def _flux2_static_img_ids(latents, device):return hit-def _flux2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, device, weight_dtype):+def _flux2_forward(+ transformer,+ noisy,+ timesteps,+ sigmas,+ embeds_batch,+ cfg,+ device,+ weight_dtype,+ guidance_value = None,+):import torchfrom diffusers import Flux2Pipeline@@ -1149,7 +1187,10 @@ def _flux2_forward(transformer, noisy, timesteps, sigmas, embeds_batch, cfg, devguidance = Noneif getattr(transformer.config, "guidance_embeds", False):guidance = torch.full(- (noisy.shape[0],), _FLUX2_TRAIN_GUIDANCE, device = device, dtype = torch.float32+ (noisy.shape[0],),+ _FLUX2_TRAIN_GUIDANCE if guidance_value is None else guidance_value,+ device = device,+ dtype = torch.float32,)pred = transformer(hidden_states = packed,@@ -1393,6 +1434,40 @@ def _ltx2_save(pipe_cls, out_dir, transformer_lora_layers):)+def _vae8_latent_shape(vae, height, width):+ return (1, vae.config.latent_channels, height // 8, width // 8), (height // 16) * (width // 16)+++def _flux_decode_latents(vae, latents):+ lat = latents / vae.config.scaling_factor + vae.config.shift_factor+ return vae.decode(lat.to(vae.dtype)).sample+++def _qwen_latent_shape(vae, height, width):+ return (1, vae.config.z_dim, 1, height // 8, width // 8), (height // 16) * (width // 16)+++def _qwen_decode_latents(vae, latents):+ mean, std = _qwen_latent_affine(vae, latents)+ return vae.decode((latents * std + mean).to(vae.dtype)).sample[:, :, 0]+++def _flux2_latent_shape(vae, height, width):+ return (1, vae.config.latent_channels * 4, height // 16, width // 16), (height // 16) * (+ width // 16+ )+++def _flux2_decode_latents(vae, latents):+ import torch+ from diffusers import Flux2Pipeline++ mean = vae.bn.running_mean.view(1, -1, 1, 1).to(latents)+ std = torch.sqrt(vae.bn.running_var.view(1, -1, 1, 1) + vae.config.batch_norm_eps).to(latents)+ lat = Flux2Pipeline._unpatchify_latents(latents * std + mean)+ return vae.decode(lat.to(vae.dtype)).sample++_SPECS: dict[str, _FamilySpec] = {"flux.1": _FamilySpec(family = "flux.1",@@ -1407,6 +1482,9 @@ _SPECS: dict[str, _FamilySpec] = {collate = _flux_collate,forward = _flux_forward,save = _flux_save,+ latent_shape = _vae8_latent_shape,+ decode_latents = _flux_decode_latents,+ sample_forward_kwargs = {"guidance": 3.5},),"qwen-image": _FamilySpec(family = "qwen-image",@@ -1421,6 +1499,8 @@ _SPECS: dict[str, _FamilySpec] = {collate = _qwen_collate,forward = _qwen_forward,save = _qwen_save,+ latent_shape = _qwen_latent_shape,+ decode_latents = _qwen_decode_latents,),"z-image": _FamilySpec(family = "z-image",@@ -1435,6 +1515,8 @@ _SPECS: dict[str, _FamilySpec] = {collate = _zimage_collate,forward = _zimage_forward,save = _zimage_save,+ latent_shape = _vae8_latent_shape,+ decode_latents = _flux_decode_latents,),"krea-2": _FamilySpec(family = "krea-2",@@ -1449,6 +1531,8 @@ _SPECS: dict[str, _FamilySpec] = {collate = _krea2_collate,forward = _krea2_forward,save = _krea2_save,+ latent_shape = _qwen_latent_shape,+ decode_latents = _qwen_decode_latents,),"flux.2-klein": _FamilySpec(family = "flux.2-klein",@@ -1464,6 +1548,8 @@ _SPECS: dict[str, _FamilySpec] = {collate = _flux2_collate,forward = _flux2_forward,save = _flux2_klein_save,+ latent_shape = _flux2_latent_shape,+ decode_latents = _flux2_decode_latents,),"flux.2-dev": _FamilySpec(family = "flux.2-dev",@@ -1480,6 +1566,10 @@ _SPECS: dict[str, _FamilySpec] = {collate = _flux2_collate,forward = _flux2_forward,save = _flux2_save,+ latent_shape = _flux2_latent_shape,+ decode_latents = _flux2_decode_latents,+ # Flux2Pipeline's default guidance_scale, which Studio's FLUX.2-dev inference also uses.+ sample_forward_kwargs = {"guidance_value": 4.0},),"ltx-2": _FamilySpec(family = "ltx-2",@@ -2013,6 +2103,12 @@ def _train_dit(# the captions (the encoders are freed right after).cfg_dropout = float(getattr(cfg, "cfg_dropout", 0.0) or 0.0)to_encode = uniq + ([""] if cfg_dropout > 0 and "" not in uniq else [])+ # Own dict: caption_embeds sizes the qwen compile pad bucket, which a long preview prompt must not grow.+ sample_plan = plan_samples(cfg, spec.family, captions) if spec.decode_latents else None+ sample_texts = sample_plan.encode_texts if sample_plan is not None else []+ sample_embeds: dict = {}+ # Kept past a failed round (which drops sample_plan) so a discard still removes what was written.+ sample_owner = sample_planuse_cache = cfg.cache_latents and os.environ.get("UNSLOTH_DIFFUSION_NO_LATENT_CACHE", "") not in ("1", "true")@@ -2056,11 +2152,22 @@ def _train_dit(done = len(image_paths),total = len(image_paths),)+ if caption_embeds is not None and sample_texts:+ # Warm conditioning skips the VAE and encoders, but previews need the VAE and their own embeddings. RNG-isolated:+ # a run without previews never makes this load, so it must not move the training streams.+ with isolated_sampling(device, False):+ pipe, vae = spec.load_conditioners(fetch_cfg, device, weight_dtype)+ encoded = _encode_prompts_cached(spec, pipe, sample_texts, device, pcache)+ sample_embeds = dict(zip(sample_texts, encoded))+ _free_text_encoders(pipe)if caption_embeds is None:latent_cache = Nonepipe, vae = spec.load_conditioners(fetch_cfg, device, weight_dtype)- encoded = _encode_prompts_cached(spec, pipe, to_encode, device, pcache)+ extra = [t for t in sample_texts if t not in to_encode]+ encoded = _encode_prompts_cached(spec, pipe, to_encode + extra, device, pcache)caption_embeds = {cap: emb for cap, emb in zip(to_encode, encoded)}+ all_embeds = dict(zip(to_encode + extra, encoded))+ sample_embeds = {t: all_embeds[t] for t in sample_texts}_free_text_encoders(pipe)gc.collect()if device == "cuda":@@ -2099,6 +2206,10 @@ def _train_dit(discarded = not _save_on_stop(),)return str(out_dir)+ # VAE parked on the host between rounds when the latent cache would have freed it: training VRAM unchanged.+ sample_vae = vae if sample_plan is not None else None+ if sample_vae is not None and latent_cache is not None:+ sample_vae.to("cpu")if latent_cache is not None and vae is not None:try:pipe.vae = None@@ -2251,6 +2362,7 @@ def _train_dit(peak_gb = 0.0t_start = time.time()t_steady = None+ t_rate = t_start# Starts at the resumed step so a no-op resume still reports the real step.done = resumed@@ -2285,7 +2397,87 @@ def _train_dit(if device in ("cuda", "xpu")else nullcontext())++ def _render_dit(index, prompt):+ shape, seq_len = spec.latent_shape(+ sample_vae, sample_plan.resolution, sample_plan.resolution+ )+ extra = spec.sample_forward_kwargs or {}++ def velocity(x, t, sig, embeds):+ with autocast:+ return spec.forward(+ transformer, x, t, sig, embeds, cfg, device, weight_dtype, **extra+ )++ cond = spec.collate([sample_embeds[prompt]], device, weight_dtype)+ uncond = (+ spec.collate([sample_embeds[""]], device, weight_dtype)+ if sample_plan.uses_cfg+ else None+ )+ latents = euler_flow_sample(+ plan = sample_plan,+ index = index,+ latent_shape = shape,+ image_seq_len = seq_len,+ family = spec.family,+ scheduler_config = scheduler.config,+ velocity = velocity,+ cond = cond,+ uncond = uncond,+ device = device,+ weight_dtype = weight_dtype,+ stop_requested = _stop_during_sample,+ )+ return spec.decode_latents(sample_vae, latents.to(next(sample_vae.parameters()).device))++ # The stop poll drains the request, so one seen mid-round is latched here for the loop to act on.+ stop_latched = False++ def _stop_during_sample() -> bool:+ nonlocal stop_latched+ if not stop_latched and _check_stop():+ stop_latched = True+ return stop_latched++ def _sample(step: int) -> None:+ nonlocal sample_plan, t_rate, t_steady+ if sample_plan is None:+ return+ t_round = time.time()+ parked = next(sample_vae.parameters()).device.type == "cpu"+ try:+ with isolated_sampling(device, compiled):+ transformer.eval()+ if parked:+ sample_vae.to(device)+ run_sample_round(+ sample_plan, step, _render_dit, on_event, _emit, _stop_during_sample+ )+ except Exception as exc: # noqa: BLE001 -- previews are diagnostics, never a reason to lose the run+ _emit(on_event, "warning", message = f"Sample images disabled after an error: {exc}")+ sample_plan = None+ finally:+ transformer.train()+ if parked:+ sample_vae.to("cpu")+ if device == "cuda":+ torch.cuda.empty_cache()+ elif device == "xpu":+ torch.xpu.empty_cache()+ spent = time.time() - t_round+ t_rate += spent+ if t_steady is not None:+ t_steady += spent++ if sample_plan is not None and resumed < cfg.train_steps:+ _sample(resumed)+for opt_step in range(resumed, cfg.train_steps):+ if stop_latched:+ stopped = True+ breakoptimizer.zero_grad(set_to_none = True)step_loss = 0.0for _ in range(cfg.gradient_accumulation_steps):@@ -2376,7 +2568,7 @@ def _train_dit(if t_steady is not None and ran_here > 1:sps = round((ran_here - 1) * per_step / max(now - t_steady, 1e-6), 3)else:- sps = round(ran_here * per_step / max(now - t_start, 1e-6), 3)+ sps = round(ran_here * per_step / max(now - t_rate, 1e-6), 3)_emit(on_event,"progress",@@ -2390,6 +2582,9 @@ def _train_dit(peak_memory_gb = peak_gb or None,)stop_now = _check_stop()+ if not stop_now and sample_plan is not None and sample_plan.due(done, cfg.train_steps):+ _sample(done)+ stop_now = stop_latched# Skipped on the final step and when stopping, since the stop path writes one at the exact step.if (not stop_now@@ -2436,6 +2631,7 @@ def _train_dit(# the optimizer state in a directory the user got no artifact from: invisible to every scanner, unresumable,# with no delete path in the UI.clear_own_checkpoints(out_dir, preexisting_checkpoints)+ discard_samples(sample_owner)try:out_dir.rmdir()except OSError:diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.pyindex edb27e4980b..65a4b098c6b 100644--- a/studio/backend/core/training/diffusion_lora_trainer.py+++ b/studio/backend/core/training/diffusion_lora_trainer.py@@ -70,6 +70,15 @@ from core.training.diffusion_train_common import ( # noqa: F401restore_resume_state,write_resume_checkpoint,)+from core.training.diffusion_samples import (+ discard_samples,+ initial_noise,+ isolated_sampling,+ plan_samples,+ run_sample_round,+ sample_seed,+ SampleRoundStopped,+)from core.training.diffusion_train_extras import BucketBatchSampler, cover_resize_dimsfrom core.training.diffusion_checkpoint import (clear_own_checkpoints,@@ -478,6 +487,14 @@ def run_diffusion_lora_training(# CLIP encoders are freed afterwards.precompute = os.environ.get("UNSLOTH_DIFFUSION_NO_PRECOMPUTE", "") not in ("1", "true")caption_embeds: dict[str, tuple] = {}+ sample_plan = plan_samples(cfg, "sdxl", [c for _, c in pairs])+ # Kept past a failed round (which drops sample_plan) so a discard still removes what was written.+ sample_owner = sample_plan+ sample_embeds: dict[str, tuple] = {}+ if sample_plan is not None:+ for text in sample_plan.encode_texts:+ pe, pooled_c = _encode_sdxl_prompts([text], tokenizers, text_encoders, device)+ sample_embeds[text] = (pe.cpu(), pooled_c.cpu())if precompute:for cap in sorted({c for _, c in pairs}):pe, pooled_c = _encode_sdxl_prompts([cap], tokenizers, text_encoders, device)@@ -532,6 +549,8 @@ def run_diffusion_lora_training()return str(out_dir)else:+ if sample_plan is not None:+ sample_vae = vae.to("cpu")try:pipe.vae = Noneexcept Exception: # noqa: BLE001 -- a pipeline without a settable vae keeps it@@ -541,6 +560,8 @@ def run_diffusion_lora_training(gc.collect()if device == "cuda":torch.cuda.empty_cache()+ if sample_plan is not None and vae is not None:+ sample_vae = vae# Variant picks use their own stream so the loop index/noise draws stay seed-deterministic whether# or not the cache is enabled.variant_rng = random.Random(cfg.seed + 1)@@ -606,6 +627,7 @@ def run_diffusion_lora_training(peak_gb = 0.0t_start = time.time()t_steady = None+ t_rate = t_start# Starts at the resumed step so a no-op resume (nothing left to train) still reports the real step.done = resumed@@ -631,7 +653,92 @@ def run_diffusion_lora_training(preexisting = preexisting_checkpoints,)+ def _interrupt_on_stop(p, _i, _t, _kwargs):+ # The pipeline skips its remaining steps once _interrupt is set (pipeline_stable_diffusion_xl.py).+ if _stop_during_sample():+ p._interrupt = True+ return {}++ def _render_sdxl(index, prompt):+ res = sample_plan.resolution+ pe, pooled_c = (t.to(device, dtype = weight_dtype) for t in sample_embeds[prompt])+ npe = npooled = None+ if sample_plan.uses_cfg:+ npe, npooled = (t.to(device, dtype = weight_dtype) for t in sample_embeds[""])+ # Studio inference sends no negative, so the pipeline zeros it on SDXL base (force_zeros_for_empty_prompt).+ if pipe.config.get("force_zeros_for_empty_prompt", False):+ npe, npooled = torch.zeros_like(npe), torch.zeros_like(npooled)+ noise = initial_noise(sample_plan, index, (1, 4, res // 8, res // 8), device)+ latents = pipe(+ prompt_embeds = pe,+ pooled_prompt_embeds = pooled_c,+ negative_prompt_embeds = npe,+ negative_pooled_prompt_embeds = npooled,+ num_inference_steps = sample_plan.steps,+ guidance_scale = sample_plan.guidance,+ height = res,+ width = res,+ latents = noise.to(weight_dtype),+ generator = torch.Generator(device = "cpu").manual_seed(+ sample_seed(sample_plan, index)+ ),+ output_type = "latent",+ return_dict = False,+ callback_on_step_end = _interrupt_on_stop,+ )[0]+ if stop_latched:+ raise SampleRoundStopped()+ return sample_vae.decode(latents.float() / vae_scale).sample++ # The stop poll drains the request, so one seen mid-round is latched here for the loop to act on.+ stop_latched = False++ def _stop_during_sample() -> bool:+ nonlocal stop_latched+ if not stop_latched and _check_stop():+ stop_latched = True+ return stop_latched++ def _sample(step: int) -> None:+ nonlocal sample_plan, t_rate, t_steady+ if sample_plan is None:+ return+ t_round = time.time()+ parked = next(sample_vae.parameters()).device.type == "cpu"+ try:+ with isolated_sampling(device, compiled):+ unet.eval()+ if parked:+ sample_vae.to(device)+ run_sample_round(+ sample_plan, step, _render_sdxl, on_event, _emit, _stop_during_sample+ )+ except Exception as exc: # noqa: BLE001 -- previews never cost the run+ _emit(on_event, "warning", message = f"Sample images disabled after an error: {exc}")+ sample_plan = None+ finally:+ unet.train()+ if parked:+ sample_vae.to("cpu")+ if device == "cuda":+ torch.cuda.empty_cache()+ spent = time.time() - t_round+ t_rate += spent+ if t_steady is not None:+ t_steady += spent++ if sample_plan is not None:+ try:+ pipe.set_progress_bar_config(disable = True)+ except Exception: # noqa: BLE001+ pass+ if resumed < cfg.train_steps:+ _sample(resumed)+for opt_step in range(resumed, cfg.train_steps):+ if stop_latched:+ stopped = True+ breakoptimizer.zero_grad(set_to_none = True)step_loss = 0.0for _ in range(cfg.gradient_accumulation_steps):@@ -742,7 +849,7 @@ def run_diffusion_lora_training((ran_here - 1) * per_step / max(now - t_steady, 1e-6), 3)else:- samples_per_second = round(ran_here * per_step / max(now - t_start, 1e-6), 3)+ samples_per_second = round(ran_here * per_step / max(now - t_rate, 1e-6), 3)_emit(on_event,"progress",@@ -757,6 +864,9 @@ def run_diffusion_lora_training()stop_now = _check_stop()+ if not stop_now and sample_plan is not None and sample_plan.due(done, cfg.train_steps):+ _sample(done)+ stop_now = stop_latched# Skipped on the final step and when stopping, since the stop path writes one at the exact step.if (not stop_now@@ -802,6 +912,7 @@ def run_diffusion_lora_training(# save_total_limit copies of the optimizer state in a directory the user got no artifact from:# invisible to every scanner, unresumable, with no delete path in the UI.clear_own_checkpoints(out_dir, preexisting_checkpoints)+ discard_samples(sample_owner)try:out_dir.rmdir()except OSError:diff --git a/studio/backend/core/training/diffusion_samples.py b/studio/backend/core/training/diffusion_samples.pynew file mode 100644index 00000000000..61b67c117ab--- /dev/null+++ b/studio/backend/core/training/diffusion_samples.py@@ -0,0 +1,422 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Fixed-seed preview images during diffusion LoRA training. A round never touches training state:+fork_rng, private noise generator, a fresh scheduler copy, and force_eager for a compiled model."""++from __future__ import annotations++import re+import secrets+import shutil+import time+from contextlib import contextmanager, nullcontext+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Callable, Optional++# Video families are left out: a preview there is a clip with audio, not a cheap still.+SAMPLE_FAMILIES: frozenset[str] = frozenset(+ {"sdxl", "z-image", "flux.1", "flux.2-klein", "flux.2-dev", "qwen-image", "krea-2"}+)+MAX_SAMPLE_PROMPTS = 4+MAX_SAMPLE_PROMPT_CHARS = 1000+MAX_SAMPLE_RESOLUTION = 768+SAMPLES_DIRNAME = "samples"+SAMPLE_PATH_RE = re.compile(+ r"^samples/[0-9]{8}-[0-9]{6}-[0-9a-f]{6}/step-[0-9]{1,6}-[0-9]{1,2}\.png$"+)+++def validate_sample_settings(+ sample_every: Any, sample_prompts: Any, family: str+) -> tuple[int, tuple[str, ...]]:+ """Normalise (sample_every, sample_prompts). Raises ValueError on a value that cannot run."""+ try:+ every = int(sample_every or 0)+ except (TypeError, ValueError) as exc:+ raise ValueError(f"sample_every must be a whole number, got {sample_every!r}") from exc+ if every < 0:+ raise ValueError("sample_every must be >= 0 (0 disables sample images)")+ if isinstance(sample_prompts, str):+ sample_prompts = [sample_prompts]+ prompts = tuple(str(p).strip() for p in (sample_prompts or ()) if str(p or "").strip())+ if len(prompts) > MAX_SAMPLE_PROMPTS:+ raise ValueError(f"at most {MAX_SAMPLE_PROMPTS} sample prompts are supported")+ if any(len(p) > MAX_SAMPLE_PROMPT_CHARS for p in prompts):+ raise ValueError(f"sample prompts must be at most {MAX_SAMPLE_PROMPT_CHARS} characters")+ if every and family not in SAMPLE_FAMILIES:+ # Refused, not ignored: a silently ignored setting reads as "sampling is broken".+ raise ValueError(f"sample images are not supported for {family}; set sample_every to 0")+ return every, prompts+++# How each diffusers pipeline combines the conditional (c) and empty-prompt (u) predictions, and above which scale it+# runs the second pass at all: "uncond" u + g(c - u) (SDXL, FLUX.1 true CFG, FLUX.2 Klein; on when g > 1), "cond"+# c + g(c - u) (Z-Image pipeline_z_image.py:547, Krea 2 pipeline_krea2.py:666; on when g > 0), "qwen" the "uncond"+# combination rescaled to the conditional prediction's per-token norm (pipeline_qwenimage.py:668-672; on when g > 1).+_CFG_MODES = {"z-image": "cond", "krea-2": "cond", "qwen-image": "qwen"}+++@dataclass(frozen = True)+class SampleSettings:+ steps: int+ # The pipeline's own guidance_scale (true_cfg_scale for Qwen-Image / FLUX.1); 0 means one conditional pass.+ guidance: float+ cfg_mode: str = "uncond"+ # A fixed schedule shift (Krea 2 Turbo pins mu = 1.15, pipeline_krea2.py:615); None derives it.+ mu: Optional[float] = None++ @property+ def uses_cfg(self) -> bool:+ return self.guidance > (0.0 if self.cfg_mode == "cond" else 1.0)+++def sample_inference_settings(family: str, base_model: str) -> SampleSettings:+ """Distilled setting for a distilled base, else a short schedule at the pipeline's default guidance."""+ name = (base_model or "").lower()+ mode = _CFG_MODES.get(family, "uncond")+ if family == "sdxl":+ return SampleSettings(4, 0.0) if "turbo" in name else SampleSettings(20, 5.0)+ if family == "z-image":+ if "de-turbo" in name or "turbo" not in name:+ return SampleSettings(28, 4.0, mode)+ return SampleSettings(8, 0.0, mode)+ if family == "flux.2-klein":+ return SampleSettings(28, 4.0) if "base" in name else SampleSettings(4, 0.0)+ if family == "flux.2-dev":+ # Guidance-distilled: the forward feeds the guidance embedding (4.0, the pipeline default) instead of true CFG.+ return SampleSettings(28, 0.0)+ if family == "flux.1":+ return SampleSettings(20, 0.0)+ if family == "qwen-image":+ return SampleSettings(20, 4.0, mode)+ if family == "krea-2":+ if "turbo" in name:+ return SampleSettings(8, 0.0, mode, mu = 1.15)+ return SampleSettings(20, 4.5, mode)+ return SampleSettings(20, 0.0)+++def combine_cfg(mode: str, guidance: float, cond, uncond):+ """One guided prediction, exactly as the family's pipeline forms it (see _CFG_MODES)."""+ if mode == "cond":+ return cond + guidance * (cond - uncond)+ comb = uncond + guidance * (cond - uncond)+ if mode == "qwen":+ return comb * (_token_norm(cond) / _token_norm(comb))+ return comb+++def _token_norm(v):+ """Per-token norm of an unpacked Qwen latent [B,C,1,H,W]: the pipeline takes it over the last dim+ of the packed [B, H/2*W/2, C*4] sequence, i.e. over the channels of each 2x2 patch."""+ b, c, f, h, w = v.shape+ p = v.reshape(b, c, f, h // 2, 2, w // 2, 2)+ n = p.pow(2).sum(dim = (1, 4, 6), keepdim = True).sqrt()+ return n.expand_as(p).reshape(v.shape)+++def sample_resolution(train_resolution: int, multiple: int = 64) -> int:+ res = min(int(train_resolution), MAX_SAMPLE_RESOLUTION)+ return max(multiple, res // multiple * multiple)+++@dataclass+class SamplePlan:+ every: int+ prompts: tuple[str, ...]+ seed: int+ steps: int+ guidance: float+ resolution: int+ out_dir: Path+ tag: str+ written: list+ cfg_mode: str = "uncond"+ mu: Optional[float] = None++ @property+ def uses_cfg(self) -> bool:+ return SampleSettings(self.steps, self.guidance, self.cfg_mode).uses_cfg++ @property+ def encode_texts(self) -> list[str]:+ """Every text whose embedding a round needs: the prompts, plus the empty prompt under CFG."""+ texts = list(dict.fromkeys(self.prompts))+ if self.uses_cfg and "" not in texts:+ texts.append("")+ return texts++ def due(self, step: int, total_steps: int) -> bool:+ return step > 0 and (step % self.every == 0 or step == total_steps)++ @property+ def run_dir(self) -> Path:+ return self.out_dir / SAMPLES_DIRNAME / self.tag++ def path_for(self, step: int, index: int) -> Path:+ return self.run_dir / f"step-{int(step)}-{int(index)}.png"++ def relpath(self, path: Path) -> str:+ return path.relative_to(self.out_dir).as_posix()+++def plan_samples(cfg: Any, family: str, captions: list[str]) -> Optional[SamplePlan]:+ every = int(getattr(cfg, "sample_every", 0) or 0)+ if every <= 0 or family not in SAMPLE_FAMILIES:+ return None+ prompts = tuple(getattr(cfg, "sample_prompts", ()) or ())+ if not prompts:+ default = (getattr(cfg, "instance_prompt", None) or "").strip() or next(+ (c for c in captions if c and c.strip()), ""+ )+ prompts = (default,)+ settings = sample_inference_settings(family, getattr(cfg, "base_model", ""))+ multiple = 128 if family.startswith("flux.2") else 64+ return SamplePlan(+ every = every,+ prompts = prompts,+ seed = int(getattr(cfg, "seed", 0) or 0),+ steps = settings.steps,+ guidance = settings.guidance,+ cfg_mode = settings.cfg_mode,+ mu = settings.mu,+ resolution = sample_resolution(getattr(cfg, "resolution", 1024), multiple),+ out_dir = Path(cfg.output_dir).expanduser(),+ tag = f"{time.strftime('%Y%m%d-%H%M%S')}-{secrets.token_hex(3)}",+ written = [],+ )+++def sample_seed(plan: SamplePlan, index: int) -> int:+ # Bounded to int64 so manual_seed accepts any configured seed.+ return (plan.seed + 1000003 * (index + 1)) % (2**63)+++@contextmanager+def isolated_sampling(device: str, compiled: bool):+ """No-grad, RNG-isolated (keeps runs bit-identical with sampling on or off), eager when compiled."""+ import torch++ devices: list = []+ device_type = "cuda"+ if device == "cuda" and torch.cuda.is_available():+ devices = [torch.cuda.current_device()]+ elif device == "xpu" and hasattr(torch, "xpu") and torch.xpu.is_available():+ devices = [torch.xpu.current_device()]+ device_type = "xpu"+ stance = nullcontext()+ set_stance = getattr(getattr(torch, "compiler", None), "set_stance", None)+ if compiled and callable(set_stance):+ stance = set_stance("force_eager")+ with torch.random.fork_rng(devices = devices, device_type = device_type), torch.no_grad(), stance:+ yield+++def initial_noise(plan: SamplePlan, index: int, shape, device):+ """Fixed-seed fp32 noise from a private CPU generator; never draws from the training streams."""+ import torch++ gen = torch.Generator(device = "cpu").manual_seed(sample_seed(plan, index))+ return torch.randn(tuple(shape), generator = gen, dtype = torch.float32).to(device)+++def flow_sigmas(+ scheduler_config: Any,+ family: str,+ steps: int,+ image_seq_len: int,+ mu: Optional[float] = None,+):+ """Inference sigmas from a FRESH scheduler: set_timesteps on the training one rewrites its tables."""+ import numpy as np+ import torch+ from diffusers import FlowMatchEulerDiscreteScheduler++ sched = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)+ sc = sched.config+ kwargs: dict = {}+ if getattr(sc, "use_dynamic_shifting", False):+ if mu is not None:+ kwargs["mu"] = float(mu)+ elif family.startswith("flux.2"):+ from diffusers.pipelines.flux2.pipeline_flux2 import compute_empirical_mu+ kwargs["mu"] = compute_empirical_mu(image_seq_len, steps)+ else:+ base_len = sc.get("base_image_seq_len", 256)+ # pipeline_krea2.py:620 defaults the max length to 6400; every other pipeline to 4096.+ max_len = sc.get("max_image_seq_len", 6400 if family == "krea-2" else 4096)+ base_shift = sc.get("base_shift", 0.5)+ max_shift = sc.get("max_shift", 1.15)+ m = (max_shift - base_shift) / (max_len - base_len)+ kwargs["mu"] = image_seq_len * m + (base_shift - m * base_len)+ sched.set_timesteps(+ sigmas = np.linspace(1.0, 1.0 / steps, steps).tolist(), device = "cpu", **kwargs+ )+ return sched.sigmas.to(dtype = torch.float32), float(sc.num_train_timesteps)+++def to_pil(images):+ """Raises on a non-finite decode, which the trainers turn into a "sampling disabled" warning instead of+ saving a black image that reads as a broken LoRA."""+ import torch+ from PIL import Image++ images = images.float()+ if not bool(torch.isfinite(images).all()):+ raise ValueError("the preview decoded to NaN / inf values")+ arr = ((images.clamp(-1, 1) + 1) * 127.5).round().to(dtype = torch.uint8)+ arr = arr.permute(0, 2, 3, 1).cpu().numpy()+ return [Image.fromarray(a) for a in arr]+++def save_round(plan: SamplePlan, step: int, images: list) -> list[dict]:+ plan.run_dir.mkdir(parents = True, exist_ok = True)+ out = []+ for i, (img, prompt) in enumerate(zip(images, plan.prompts)):+ path = plan.path_for(step, i)+ tmp = path.with_suffix(".png.tmp")+ img.save(tmp, format = "PNG")+ tmp.replace(path)+ plan.written.append(path)+ out.append({"path": plan.relpath(path), "prompt": prompt, "seed": sample_seed(plan, i)})+ return out+++def discard_samples(plan: Optional[SamplePlan]) -> None:+ """Remove this run's previews (a stop-without-saving); never another run's."""+ if plan is None:+ return+ try:+ if plan.run_dir.is_dir():+ shutil.rmtree(plan.run_dir)+ plan.run_dir.parent.rmdir()+ except OSError:+ pass+++def _run_dirs(base: Path, relpaths: list) -> set:+ """The per-run tag folders (``samples/<tag>``) the reported paths name; never anything else."""+ root = base / SAMPLES_DIRNAME+ dirs = set()+ for rel in relpaths:+ if isinstance(rel, str) and SAMPLE_PATH_RE.match(rel):+ dirs.add(root / rel.split("/")[1])+ return dirs+++def discard_sample_paths(output_dir: Optional[str], relpaths: list) -> None:+ """Parent-side ``discard_samples`` for a child that died before cleaning up."""+ if not output_dir:+ return+ base = Path(output_dir)+ for d in _run_dirs(base, relpaths):+ try:+ if d.is_dir() and not d.is_symlink():+ shutil.rmtree(d)+ except OSError:+ pass+ try:+ (base / SAMPLES_DIRNAME).rmdir()+ except OSError:+ pass+++def delete_sample_files(output_dir: Optional[str], relpaths: list) -> None:+ """Delete individual reported images (history thinning), so no file outlives its listing."""+ if not output_dir:+ return+ for rel in relpaths:+ if isinstance(rel, str) and SAMPLE_PATH_RE.match(rel):+ try:+ (Path(output_dir) / rel).unlink()+ except OSError:+ pass+++class SampleRoundStopped(Exception):+ """Raised by a render whose stop check fired mid-denoise."""+++def run_sample_round(+ plan: SamplePlan,+ step: int,+ render: Callable[[int, str], Any],+ on_event,+ emit,+ stop_requested: Optional[Callable[[], bool]] = None,+) -> bool:+ """Render, save and emit each prompt; a stop keeps finished images. True when cut short."""+ t0 = time.time()+ images = []+ stopped = False+ for i, prompt in enumerate(plan.prompts):+ if stop_requested is not None and stop_requested():+ stopped = True+ break+ try:+ images.extend(to_pil(render(i, prompt)))+ except SampleRoundStopped:+ stopped = True+ break+ if images:+ entries = save_round(plan, step, images)+ emit(on_event, "sample", step = int(step), images = entries, seconds = round(time.time() - t0, 2))+ return stopped+++def euler_flow_sample(+ *,+ plan: SamplePlan,+ index: int,+ latent_shape,+ image_seq_len: int,+ family: str,+ scheduler_config: Any,+ velocity: Callable[[Any, Any, Any, Any], Any],+ cond,+ uncond,+ device,+ weight_dtype,+ stop_requested: Optional[Callable[[], bool]] = None,+):+ """Flow-matching Euler: x <- x + (sigma_next - sigma) * v, with v from the training forward+ (target convention noise - latents) and the family pipeline's CFG combination."""+ import torch++ sigmas, num_train = flow_sigmas(scheduler_config, family, plan.steps, image_seq_len, plan.mu)+ x = initial_noise(plan, index, latent_shape, device)+ for i in range(len(sigmas) - 1):+ if stop_requested is not None and stop_requested():+ raise SampleRoundStopped()+ s, s_next = float(sigmas[i]), float(sigmas[i + 1])+ t = torch.full((x.shape[0],), s * num_train, device = device, dtype = torch.float32)+ sig = torch.full((x.shape[0],), s, device = device, dtype = weight_dtype)+ while sig.ndim < x.ndim:+ sig = sig.unsqueeze(-1)+ xin = x.to(weight_dtype)+ v = velocity(xin, t, sig, cond).float()+ if plan.uses_cfg and uncond is not None:+ v_u = velocity(xin, t, sig, uncond).float()+ v = combine_cfg(plan.cfg_mode, plan.guidance, v, v_u)+ x = x + (s_next - s) * v+ return x+++__all__ = [+ "MAX_SAMPLE_PROMPTS",+ "SAMPLE_FAMILIES",+ "SAMPLE_PATH_RE",+ "SamplePlan",+ "SampleRoundStopped",+ "combine_cfg",+ "discard_sample_paths",+ "discard_samples",+ "euler_flow_sample",+ "isolated_sampling",+ "plan_samples",+ "run_sample_round",+ "sample_inference_settings",+ "validate_sample_settings",+]diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex f116cb76825..cb920f858ac 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -38,6 +38,8 @@ from core.inference.diffusion_torchao_patches import install_torchao_int_mm_patcfrom core.inference.video_families import detect_video_family, supported_video_family_namesfrom utils.paths.path_utils import drop_appledouble_metadata+from core.training.diffusion_samples import SAMPLE_FAMILIES, validate_sample_settings+# The trainers run in a spawned child that imports diffusers itself, so the inference-side install does not carry# over. Both import this module first.install_xformers_windows_rocm_stub()@@ -962,6 +964,8 @@ def family_train_infos() -> list[dict[str, Any]]:# save_steps is REFUSED for a checkpointless family, not ignored, so a panel that keeps offering# "Checkpoint every" turns a nonzero value into a rejected Start with no way to see why."supports_checkpoints": name not in CHECKPOINTLESS_FAMILIES,+ # sample_every is refused elsewhere, so the panel offers "Sample every" only where it runs.+ "supports_samples": name in SAMPLE_FAMILIES,"supports_bucketing": name not in UNBUCKETED_FAMILIES,# A batch > 1 is REFUSED for a family whose forward covers one packed sequence, so leaving the control# unrestricted turns a reasonable 2 into a rejected Start with nothing to say why.@@ -1051,6 +1055,10 @@ class DiffusionLoraConfig:save_steps: int = 0# How many checkpoint-<N> bundles to keep in the output dir; 0 keeps every one.save_total_limit: int = 2+ # 0 disables. Not part of the resume identity: previews never touch the training math.+ sample_every: int = 0+ # Empty uses the instance prompt, else the first caption.+ sample_prompts: tuple[str, ...] = ()# The run's output_dir, or one of its checkpoint-<N> directories; the start route resolves and validates it before# the trainer spawns.resume_from_checkpoint: Optional[str] = None@@ -1162,6 +1170,9 @@ class DiffusionLoraConfig:# so valid decays live in [0, 1).if not 0.0 <= ema_decay < 1.0:raise ValueError("ema_decay must be in [0, 1); 0 disables the EMA adapter")+ sample_every, sample_prompts = validate_sample_settings(+ self.sample_every, self.sample_prompts, resolved_family+ )# A blank cond_cache_dir (the Unsloth default when unset) means "off", not cwd.cond_cache_dir = (str(self.cond_cache_dir).strip() if self.cond_cache_dir is not None else ""@@ -1300,6 +1311,8 @@ class DiffusionLoraConfig:bucketing = bucketing,save_steps = save_steps,save_total_limit = save_total_limit,+ sample_every = sample_every,+ sample_prompts = sample_prompts,resume_from_checkpoint = resume_from_checkpoint,cond_cache_dir = cond_cache_dir,ema_decay = ema_decay,@@ -2311,6 +2324,8 @@ def _config_from_dict(config: dict) -> DiffusionLoraConfig:kwargs.pop("train_steps", None)if kwargs.get("lora_target_modules"):kwargs["lora_target_modules"] = tuple(kwargs["lora_target_modules"])+ if isinstance(kwargs.get("sample_prompts"), (list, tuple)):+ kwargs["sample_prompts"] = tuple(kwargs["sample_prompts"])if "gradient_checkpointing" in kwargs:kwargs["gradient_checkpointing"] = _coerce_gradient_checkpointing(kwargs["gradient_checkpointing"]diff --git a/studio/backend/core/training/diffusion_training_service.py b/studio/backend/core/training/diffusion_training_service.pyindex e3631c1169d..9db37a7e557 100644--- a/studio/backend/core/training/diffusion_training_service.py+++ b/studio/backend/core/training/diffusion_training_service.py@@ -292,6 +292,7 @@ def list_diffusion_runs(limit: int = 20) -> list[dict]:continuerec.pop("metric_history", None)rec.pop("config", None)+ rec.pop("samples", None)out.append(rec)return out@@ -389,9 +390,46 @@ def _idle_state() -> dict[str, Any]:# stay index-aligned."metric_video_loss": [],"metric_audio_loss": [],+ "samples": [],}+# Past this the oldest half after the step-0 baseline is thinned, like the metrics.+_SAMPLES_CAP = 400+++def _append_samples(+ state: dict[str, Any],+ step: Any,+ images: Any,+ output_dir: Optional[str] = None,+) -> None:+ """Fold one ``sample`` event; thinned rounds' images are deleted so every file on disk stays listed."""+ from core.training.diffusion_samples import SAMPLE_PATH_RE, delete_sample_files++ try:+ istep = int(step)+ except (TypeError, ValueError):+ return+ entries = state.setdefault("samples", [])+ for img in images if isinstance(images, list) else []:+ if not isinstance(img, dict) or not SAMPLE_PATH_RE.match(str(img.get("path") or "")):+ continue+ entries.append(+ {+ "step": istep,+ "path": str(img["path"]),+ "prompt": str(img.get("prompt") or ""),+ "seed": img.get("seed") if isinstance(img.get("seed"), int) else None,+ }+ )+ if len(entries) > _SAMPLES_CAP:+ steps = sorted({e["step"] for e in entries})+ keep = set(steps[:1] + steps[1:-1][::2] + steps[-1:])+ state["samples"] = [e for e in entries if e["step"] in keep]+ delete_sample_files(output_dir, [e["path"] for e in entries if e["step"] not in keep])++# The value series, in append order, paired index-for-index with metric_steps. One list so a new# series cannot be added to the appends and forgotten in the decimation below, which would# silently misalign the curves.@@ -791,6 +829,19 @@ class DiffusionTrainingService:snap["active"] = self._proc is not None and self._proc.is_alive()return snap+ def sample_source(self, job_id: str) -> Optional[tuple[Optional[str], list]]:+ """(output_dir, samples) for the live job ``job_id``, or None when it is not the live job or+ belongs to another account (the run record answers for a finished one)."""+ from core.training.account_jobs import job_is_foreign++ if job_is_foreign(self):+ return None+ with self._lock:+ if not job_id or self._state.get("job_id") != job_id:+ return None+ out = self._state.get("output_dir") or self._config.get("output_dir")+ return (str(out) if out else None), list(self._state.get("samples") or [])+def _open_worker_stderr_capture(self) -> None:previous = self._stderr_captureself._stderr_capture = None@@ -898,12 +949,22 @@ class DiffusionTrainingService:delete = Falsewith self._lock:own = list(self._own_checkpoints) if delete else []+ samples = [e.get("path") for e in self._state.get("samples") or []] if delete else []+ sample_root = self._state.get("output_dir") or self._config.get("output_dir")self._state["resume_blocked_reason"] = ("This run was stopped without saving, so it was discarded.")self._state["checkpoint_path"] = Noneself._state["checkpoint_step"] = None+ # Their files are deleted, so listing them would serve 404s.+ self._state["samples"] = []self._own_checkpoints = []+ if samples:+ try:+ from core.training.diffusion_samples import discard_sample_paths+ discard_sample_paths(sample_root, samples)+ except Exception: # noqa: BLE001 -- cleanup must never break the terminal transition+ passif not own:returntry:@@ -991,6 +1052,7 @@ class DiffusionTrainingService:"video_loss": s.get("metric_video_loss") or [],"audio_loss": s.get("metric_audio_loss") or [],},+ "samples": s.get("samples") or [],}path = _runs_dir() / f"{s['job_id']}.json"path.write_text(json.dumps(record), encoding = "utf-8")@@ -1116,6 +1178,13 @@ class DiffusionTrainingService:ev.get("video_loss"),ev.get("audio_loss"),)+ elif etype == "sample":+ _append_samples(+ s,+ ev.get("step"),+ ev.get("images"),+ s.get("output_dir") or self._config.get("output_dir"),+ )elif etype == "complete":# Reset in_model_load: a stop during model load emits complete with no preceding# model_load_completed, leaving a stale indicator.@@ -1151,6 +1220,7 @@ class DiffusionTrainingService:s["resume_blocked_reason"] = ("This run was stopped without saving, so it was discarded.")+ s["samples"] = []elif etype == "error":# Reset in_model_load too: an error during model loading has no model_load_completed.s.update(diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex 45efe21b77b..36f83e60fd0 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -1057,6 +1057,22 @@ class DiffusionTrainingStartRequest(BaseModel):save_total_limit: int = Field(2, ge = 0, le = 100, description = "How many checkpoints to keep; 0 keeps every one")+ sample_every: int = Field(+ 0,+ ge = 0,+ le = 100000,+ description = (+ "Render fixed-seed preview images every N optimizer steps (plus a step-0 baseline and "+ "the final step). 0 (the default) renders none. Image families only."+ ),+ )+ sample_prompts: List[str] = Field(+ default_factory = list,+ max_length = 4,+ description = (+ "Preview prompts, one image each. Empty uses the instance prompt, else the first caption."+ ),+ )resume_from_checkpoint: Optional[str] = Field(None,description = (@@ -1107,6 +1123,15 @@ class DiffusionMetricHistory(BaseModel):audio_loss: List[Optional[float]] = Field(default_factory = list)+class DiffusionSampleImage(BaseModel):+ """One preview image; ``path`` is relative to the run's output_dir."""++ step: int+ path: str+ prompt: str = ""+ seed: Optional[int] = None++class DiffusionTrainingStatusResponse(BaseModel):"""A snapshot of the current diffusion training job (or idle)."""@@ -1148,6 +1173,7 @@ class DiffusionTrainingStatusResponse(BaseModel):updated_at: Optional[float] = None# Bounded step/loss/lr history for the live loss + LR charts.metric_history: Optional[DiffusionMetricHistory] = None+ samples: List[DiffusionSampleImage] = Field(default_factory = list)class DiffusionTrainingRunSummary(BaseModel):@@ -1196,6 +1222,7 @@ class DiffusionTrainingRunDetail(DiffusionTrainingRunSummary):ema_path: Optional[str] = Noneconfig: Optional[dict] = Nonemetric_history: Optional[DiffusionMetricHistory] = None+ samples: List[DiffusionSampleImage] = Field(default_factory = list)class DiffusionTrainingRunsResponse(BaseModel):@@ -1237,6 +1264,7 @@ class DiffusionTrainableFamily(BaseModel):# control: save_steps is refused, not ignored, for a checkpointless family, so offering the control means# offering a value that rejects Start; defaults True so an older backend's payload keeps it.supports_checkpoints: bool = True+ supports_samples: bool = Falsesupports_bucketing: bool = True# 1 for a family whose forward covers one packed sequence: a value above the cap is refused rather# than clamped, and declaring it here is what stops Pydantic dropping it from the response.diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex b24f9e05b1f..275b57d2c6f 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -3799,6 +3799,50 @@ async def get_diffusion_training_run(raise HTTPException(status_code = 404, detail = "No such training run.")[email protected]("/diffusion/runs/{job_id}/sample")+async def get_diffusion_training_sample(+ job_id: str,+ path: str,+ current_subject: str = Depends(get_current_subject),+):+ """Serve one preview image a run reported (``samples[].path``). Only a path the run itself+ listed is served, from inside that run's output_dir under this account's outputs root: the+ live job answers through the service's owner check, a finished one through its run record."""+ from fastapi.responses import FileResponse++ from core.training.diffusion_samples import SAMPLE_PATH_RE+ from core.training.diffusion_training_service import (+ get_diffusion_run,+ get_diffusion_training_service,+ )+ from utils.paths import outputs_root++ not_found = HTTPException(status_code = 404, detail = "Sample image not found.")+ if not SAMPLE_PATH_RE.match(path or ""):+ raise not_found+ source = get_diffusion_training_service().sample_source(job_id)+ if source is None:+ rec = await asyncio.to_thread(get_diffusion_run, job_id)+ if not isinstance(rec, dict):+ raise not_found+ samples = rec.get("samples") if isinstance(rec.get("samples"), list) else []+ out_dir = rec.get("output_dir")+ else:+ out_dir, samples = source+ if not out_dir or path not in {e.get("path") for e in samples if isinstance(e, dict)}:+ raise not_found+ try:+ base = Path(out_dir).resolve(strict = True)+ base.relative_to(outputs_root().resolve())+ target = (base / path).resolve(strict = True)+ target.relative_to(base)+ except (OSError, ValueError):+ raise not_found+ if not target.is_file():+ raise not_found+ return FileResponse(str(target), media_type = "image/png")++# Extensions accepted into a diffusion-training dataset folder: the media the trainer reads, plus its caption sources# (per-item sidecars and metadata/captions jsonl)._DIFFUSION_DATASET_IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}diff --git a/studio/backend/tests/multi_account/factories_training.py b/studio/backend/tests/multi_account/factories_training.pyindex ef42f3553c6..5afb504d9b1 100644--- a/studio/backend/tests/multi_account/factories_training.py+++ b/studio/backend/tests/multi_account/factories_training.py@@ -10,6 +10,8 @@ EDITED = "training-matrix-edited"START_REQUEST_ID = "training-matrix-start-request"START_JOB_ID = "training-matrix-job"DIFFUSION_JOB_ID = "a1b2c3d4e5f607182930a4b5c6d7e8f9"+SAMPLE_JOB_ID = "b2c3d4e5f607182930a4b5c6d7e8f9a1"+SAMPLE_PATH = "samples/20260101-000000-abcdef/step-0-0.png"DATASET_NAME = "training-matrix-dataset"IMAGE_NAME = "training-matrix-image.png"RECIPE_JOB_ID = "f9e8d7c6b5a40312092a8b7c6d5e4f30"@@ -132,6 +134,39 @@ def seed_diffusion_run(account) -> dict[str, str]:return {"job_id": DIFFUSION_JOB_ID}+@seeder("training-diffusion-sample")+def seed_diffusion_sample(account) -> dict[str, str]:+ import base64+ import json++ from utils.account_context import run_as+ from utils.paths import outputs_root+ from utils.paths.storage_roots import tensorboard_root++ def install() -> None:+ out_dir = outputs_root() / "training-matrix-diffusion"+ image = out_dir / SAMPLE_PATH+ image.parent.mkdir(parents = True, exist_ok = True)+ image.write_bytes(base64.b64decode(PNG_1X1))+ folder = tensorboard_root() / "diffusion"+ folder.mkdir(parents = True, exist_ok = True)+ (folder / f"{SAMPLE_JOB_ID}.json").write_text(+ json.dumps(+ {+ "job_id": SAMPLE_JOB_ID,+ "status": "completed",+ "output_dir": str(out_dir),+ "samples": [{"step": 0, "index": 0, "path": SAMPLE_PATH}],+ "config": {},+ }+ ),+ encoding = "utf-8",+ )++ run_as(account, install)+ return {"job_id": SAMPLE_JOB_ID}++@seeder("training-diffusion-dataset")def seed_diffusion_dataset(account) -> dict[str, str]:import base64@@ -242,6 +277,9 @@ FACTORIES = {"routes.training:GET:/diffusion/runs/{job_id}": Factory("training-diffusion-run", fragment = SENTINEL),+ "routes.training:GET:/diffusion/runs/{job_id}/sample": Factory(+ "training-diffusion-sample", fragment = "IHDR", query = {"path": SAMPLE_PATH}+ ),"routes.training:GET:/diffusion/dataset/{name}/images": Factory("training-diffusion-dataset", fragment = SENTINEL),diff --git a/studio/backend/tests/test_diffusion_samples.py b/studio/backend/tests/test_diffusion_samples.pynew file mode 100644index 00000000000..0362920b6b4--- /dev/null+++ b/studio/backend/tests/test_diffusion_samples.py@@ -0,0 +1,598 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Sample images during diffusion LoRA training: config validation, RNG isolation (a round must+not move the training streams or the training scheduler), the flow sampler's sign convention,+the run state / record, and the route that serves the images (listed paths only, owner only)."""++from __future__ import annotations++import json+import random+from types import SimpleNamespace++import pytest+import torch+from fastapi import FastAPI+from fastapi.testclient import TestClient++from core.training import diffusion_samples as ds+from core.training.diffusion_train_common import DiffusionLoraConfig, _config_from_dict++_ZIMAGE = "unsloth/Z-Image-Turbo-unsloth-bnb-4bit"+++def _cfg(**kw):+ base = dict(base_model = _ZIMAGE, data_dir = "d", output_dir = "o")+ base.update(kw)+ return DiffusionLoraConfig(**base)+++def test_sampling_is_off_by_default():+ cfg = _cfg().normalized()+ assert cfg.sample_every == 0 and cfg.sample_prompts == ()+ assert ds.plan_samples(cfg, cfg.resolved_family, ["a dog"]) is None+++def test_sample_settings_normalised():+ cfg = _config_from_dict(+ {+ "base_model": _ZIMAGE,+ "data_dir": "d",+ "output_dir": "o",+ "sample_every": "50",+ "sample_prompts": [" a dog ", "", " "],+ }+ ).normalized()+ assert cfg.sample_every == 50+ assert cfg.sample_prompts == ("a dog",)+++ "kw, msg",+ [+ ({"sample_every": -1}, ">= 0"),+ ({"sample_every": "x"}, "whole number"),+ ({"sample_every": 10, "sample_prompts": ["p"] * 5}, "at most 4"),+ ({"sample_every": 10, "sample_prompts": ["x" * 1001]}, "1000 characters"),+ ],+)+def test_sample_settings_rejected(kw, msg):+ with pytest.raises(ValueError, match = msg):+ _cfg(**kw).normalized()++[email protected]("family", ["ltx-2", "minimax-h3"])+def test_video_families_refuse_sampling(family):+ with pytest.raises(ValueError, match = "not supported"):+ ds.validate_sample_settings(10, (), family)+ # 0 stays valid, so a replayed config from an image family never breaks a video start.+ assert ds.validate_sample_settings(0, (), family) == (0, ())+++def test_request_model_carries_sample_fields():+ from models.training import DiffusionTrainingStartRequest++ body = DiffusionTrainingStartRequest(+ base_model = _ZIMAGE,+ data_dir = "d",+ output_dir = "o",+ sample_every = 25,+ sample_prompts = ["a"],+ ).model_dump()+ assert body["sample_every"] == 25 and body["sample_prompts"] == ["a"]+ with pytest.raises(Exception):+ DiffusionTrainingStartRequest(+ base_model = _ZIMAGE, data_dir = "d", output_dir = "o", sample_prompts = ["a"] * 5+ )+++def test_family_info_reports_supports_samples():+ from core.training.diffusion_train_common import SAMPLE_FAMILIES+ assert "sdxl" in SAMPLE_FAMILIES and "z-image" in SAMPLE_FAMILIES+ assert not {"ltx-2", "minimax-h3"} & SAMPLE_FAMILIES+++def test_sampling_is_not_part_of_resume_identity():+ from core.training.diffusion_checkpoint import identity_for_config++ a = identity_for_config(_cfg().normalized())+ b = identity_for_config(_cfg(sample_every = 10, sample_prompts = ("x",)).normalized())+ assert a == b+++def test_plan_defaults_to_instance_prompt_then_first_caption(tmp_path):+ cfg = _cfg(output_dir = str(tmp_path), sample_every = 5, instance_prompt = "sks dog").normalized()+ plan = ds.plan_samples(cfg, "z-image", ["cap one", "cap two"])+ assert plan.prompts == ("sks dog",)+ cfg = _cfg(output_dir = str(tmp_path), sample_every = 5).normalized()+ assert ds.plan_samples(cfg, "z-image", ["", "cap one"]).prompts == ("cap one",)+++def test_plan_schedule_and_paths(tmp_path):+ cfg = _cfg(output_dir = str(tmp_path), sample_every = 50, resolution = 1024).normalized()+ plan = ds.plan_samples(cfg, "z-image", ["c"])+ assert [s for s in range(0, 131) if plan.due(s, 130)] == [50, 100, 130]+ assert plan.resolution == ds.MAX_SAMPLE_RESOLUTION+ rel = plan.relpath(plan.path_for(100, 0))+ assert ds.SAMPLE_PATH_RE.match(rel), rel+ # Turbo is distilled: no CFG, so no empty-prompt embedding is needed.+ assert plan.steps == 8 and not plan.uses_cfg and plan.encode_texts == ["c"]+ sdxl = ds.plan_samples(+ _cfg(+ base_model = "stabilityai/stable-diffusion-xl-base-1.0",+ output_dir = str(tmp_path),+ sample_every = 1,+ ).normalized(),+ "sdxl",+ ["c"],+ )+ assert sdxl.uses_cfg and sdxl.encode_texts == ["c", ""]+++ "bad",+ [+ "samples/../x.png",+ "/etc/passwd",+ "samples/20261010-014028-0993fe/step-1-0.jpg",+ "x/step-1-0.png",+ ],+)+def test_sample_path_regex_rejects(bad):+ assert not ds.SAMPLE_PATH_RE.match(bad)+++def test_isolated_sampling_restores_global_rng(tmp_path):+ plan = ds.plan_samples(+ _cfg(output_dir = str(tmp_path), sample_every = 1).normalized(), "z-image", ["c"]+ )+ torch.manual_seed(1234)+ expected = torch.rand(8)+ torch.manual_seed(1234)+ py_state = random.getstate()+ with ds.isolated_sampling("cpu", compiled = False):+ torch.randn(100) # anything the sampler (or a stochastic module) draws+ noise = ds.initial_noise(plan, 0, (1, 4, 8, 8), "cpu")+ assert not torch.is_grad_enabled()+ assert torch.equal(torch.rand(8), expected)+ assert random.getstate() == py_state+ assert torch.equal(noise, ds.initial_noise(plan, 0, (1, 4, 8, 8), "cpu"))+ assert not torch.equal(noise, ds.initial_noise(plan, 1, (1, 4, 8, 8), "cpu"))+++def test_initial_noise_never_touches_global_stream(tmp_path):+ plan = ds.plan_samples(+ _cfg(output_dir = str(tmp_path), sample_every = 1).normalized(), "z-image", ["c"]+ )+ torch.manual_seed(7)+ before = torch.get_rng_state()+ ds.initial_noise(plan, 0, (2, 3), "cpu")+ assert torch.equal(torch.get_rng_state(), before)+++def test_flow_sigmas_leave_training_scheduler_untouched():+ pytest.importorskip("diffusers")+ from diffusers import FlowMatchEulerDiscreteScheduler++ sched = FlowMatchEulerDiscreteScheduler(shift = 3.0)+ sig, ts = sched.sigmas.clone(), sched.timesteps.clone()+ sigmas, num_train = ds.flow_sigmas(sched.config, "z-image", 8, 1024)+ assert torch.equal(sched.sigmas, sig) and torch.equal(sched.timesteps, ts)+ assert len(sigmas) == 9 and float(sigmas[-1]) == 0.0 and float(sigmas[0]) == pytest.approx(1.0)+ assert num_train == 1000.0+ dyn = FlowMatchEulerDiscreteScheduler(use_dynamic_shifting = True)+ assert len(ds.flow_sigmas(dyn.config, "qwen-image", 4, 4096)[0]) == 5+++def test_euler_flow_sample_recovers_target_with_exact_velocity(tmp_path):+ """The training target is v = noise - latents; an oracle velocity must land exactly on x0,+ with and without CFG (identical cond/uncond predictions make CFG a no-op)."""+ pytest.importorskip("diffusers")+ from diffusers import FlowMatchEulerDiscreteScheduler++ x0 = torch.randn(1, 4, 8, 8, generator = torch.Generator().manual_seed(0))+ for guidance in (1.0, 4.0):+ plan = ds.plan_samples(+ _cfg(output_dir = str(tmp_path), sample_every = 1).normalized(), "z-image", ["c"]+ )+ plan.guidance = guidance+ noise = ds.initial_noise(plan, 0, x0.shape, "cpu")++ def velocity(x, t, sig, cond):+ return noise - x0++ out = ds.euler_flow_sample(+ plan = plan,+ index = 0,+ latent_shape = x0.shape,+ image_seq_len = 16,+ family = "z-image",+ scheduler_config = FlowMatchEulerDiscreteScheduler(shift = 3.0).config,+ velocity = velocity,+ cond = "c",+ uncond = "u",+ device = "cpu",+ weight_dtype = torch.float32,+ )+ assert torch.allclose(out, x0, atol = 1e-5)+++def test_round_saves_pngs_and_emits_event(tmp_path):+ plan = ds.plan_samples(+ _cfg(output_dir = str(tmp_path), sample_every = 1, sample_prompts = ("a", "b")).normalized(),+ "z-image",+ ["c"],+ )+ events = []+ ds.run_sample_round(+ plan,+ 10,+ lambda i, p: torch.zeros(1, 3, 16, 16),+ None,+ lambda _cb, t, **kw: events.append({"type": t, **kw}),+ )+ (ev,) = events+ assert ev["type"] == "sample" and ev["step"] == 10+ assert [e["prompt"] for e in ev["images"]] == ["a", "b"]+ for e in ev["images"]:+ assert ds.SAMPLE_PATH_RE.match(e["path"]) and (tmp_path / e["path"]).is_file()+ ds.discard_samples(plan)+ assert not (tmp_path / "samples").exists()+++def test_parent_discard_removes_the_whole_run_folder_only(tmp_path):+ other = tmp_path / "samples" / "20260101-000000-aaaaaa" / "step-1-0.png"+ mine = tmp_path / "samples" / "20260102-000000-bbbbbb" / "step-1-0.png"+ thinned = mine.parent / "step-2-0.png" # on disk but no longer listed+ for p in (other, mine, thinned):+ p.parent.mkdir(parents = True, exist_ok = True)+ p.write_bytes(b"x")+ ds.discard_sample_paths(str(tmp_path), [mine.relative_to(tmp_path).as_posix(), "../evil.png"])+ assert other.is_file() and not mine.parent.exists()+++def test_thinning_deletes_the_evicted_files(tmp_path):+ from core.training.diffusion_training_service import _SAMPLES_CAP, _append_samples++ state = {"samples": []}+ tag = "samples/20261010-014028-0993fe"+ (tmp_path / tag).mkdir(parents = True)+ for step in range(_SAMPLES_CAP + 1):+ rel = f"{tag}/step-{step}-0.png"+ (tmp_path / rel).write_bytes(b"x")+ _append_samples(state, step, [{"path": rel}], str(tmp_path))+ listed = {e["path"] for e in state["samples"]}+ on_disk = {p.relative_to(tmp_path).as_posix() for p in (tmp_path / tag).iterdir()}+ assert len(listed) < _SAMPLES_CAP + 1 and on_disk == listed+++def test_service_folds_sample_events_and_persists(monkeypatch, tmp_path):+ import core.training.diffusion_training_service as dts++ runs = tmp_path / "runs"+ runs.mkdir()+ monkeypatch.setattr(dts, "_runs_dir", lambda: runs)+ svc = dts.DiffusionTrainingService()+ svc._state.update(job_id = "a" * 32, status = "running", output_dir = str(tmp_path))+ good = "samples/20261010-014028-0993fe/step-50-0.png"+ svc._apply_event(+ {+ "type": "sample",+ "step": 50,+ "images": [{"path": good, "prompt": "p", "seed": 3}, {"path": "../x.png"}],+ }+ )+ assert svc.status()["samples"] == [{"step": 50, "path": good, "prompt": "p", "seed": 3}]+ svc._apply_event({"type": "complete", "output_dir": str(tmp_path), "lora_path": "x"})+ svc._persist_run_record()+ rec = json.loads((runs / f"{'a' * 32}.json").read_text())+ assert rec["samples"][0]["path"] == good+ assert dts.get_diffusion_run("a" * 32)["samples"][0]["path"] == good+ assert "samples" not in dts.list_diffusion_runs()[0]+++def test_a_discarded_run_lists_no_previews(tmp_path, monkeypatch):+ # Stop-without-saving deletes the previews (the child before its discarded completion, else the parent), so the+ # run must stop listing them or the UI renders cards whose image route 404s.+ import core.training.diffusion_training_service as dts++ monkeypatch.setattr(dts, "_runs_dir", lambda: tmp_path / "runs")+ good = "samples/20261010-014028-0993fe/step-50-0.png"+ for discard in ("event", "parent"):+ svc = dts.DiffusionTrainingService()+ svc._state.update(job_id = "b" * 32, status = "running", output_dir = str(tmp_path))+ svc._apply_event({"type": "sample", "step": 50, "images": [{"path": good, "prompt": "p"}]})+ assert svc.status()["samples"]+ if discard == "event":+ svc._apply_event({"type": "complete", "output_dir": str(tmp_path), "discarded": True})+ else:+ svc._apply_discard_intent(delete = True)+ assert svc.status()["samples"] == [], discard+++def test_sample_list_is_bounded():+ from core.training.diffusion_training_service import _SAMPLES_CAP, _append_samples++ state = {"samples": []}+ for step in range(0, 2000, 1):+ _append_samples(+ state, step, [{"path": f"samples/20261010-014028-0993fe/step-{step}-0.png"}]+ )+ steps = [e["step"] for e in state["samples"]]+ assert len(steps) <= _SAMPLES_CAP and steps[0] == 0 and steps[-1] == 1999+++def sample_client(monkeypatch, tmp_path):+ import core.training.diffusion_training_service as dts+ import utils.paths as up+ from auth.authentication import get_current_subject+ from routes.training import router++ runs = tmp_path / "runs"+ runs.mkdir()+ out_root = tmp_path / "outputs"+ run_dir = out_root / "my-lora"+ rel = "samples/20261010-014028-0993fe/step-50-0.png"+ (run_dir / rel).parent.mkdir(parents = True)+ (run_dir / rel).write_bytes(b"\x89PNG fake")+ (run_dir / "samples/20261010-014028-0993fe/step-60-0.png").write_bytes(b"unlisted")+ rec = {+ "job_id": "b" * 32,+ "status": "completed",+ "output_dir": str(run_dir),+ "samples": [{"step": 50, "path": rel, "prompt": "p"}],+ }+ (runs / f"{'b' * 32}.json").write_text(json.dumps(rec))+ monkeypatch.setattr(dts, "_runs_dir", lambda: runs)+ monkeypatch.setattr(up, "outputs_root", lambda: out_root)+ svc = dts.DiffusionTrainingService()+ monkeypatch.setattr(dts, "get_diffusion_training_service", lambda: svc)+ app = FastAPI()+ app.include_router(router, prefix = "/api/train")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return SimpleNamespace(+ client = TestClient(app), svc = svc, rel = rel, run_dir = run_dir, out_root = out_root+ )+++def _url(job, path):+ return f"/api/train/diffusion/runs/{job}/sample", {"path": path}+++def test_route_serves_listed_sample(sample_client):+ url, q = _url("b" * 32, sample_client.rel)+ r = sample_client.client.get(url, params = q)+ assert r.status_code == 200 and r.content == b"\x89PNG fake"+ assert r.headers["content-type"] == "image/png"+++ "job, path",+ [+ ("b" * 32, "samples/20261010-014028-0993fe/step-60-0.png"), # on disk, never reported+ ("b" * 32, "samples/../../../etc/passwd"),+ ("c" * 32, "samples/20261010-014028-0993fe/step-50-0.png"), # no such run+ ("../" * 3, "samples/20261010-014028-0993fe/step-50-0.png"),+ ],+)+def test_route_refuses_unlisted_or_foreign(sample_client, job, path):+ url, q = _url(job, path)+ assert sample_client.client.get(url, params = q).status_code == 404+++def test_route_refuses_record_outside_outputs_root(sample_client, tmp_path):+ rec_path = next((tmp_path / "runs").glob("*.json"))+ rec = json.loads(rec_path.read_text())+ outside = tmp_path / "elsewhere"+ (outside / sample_client.rel).parent.mkdir(parents = True)+ (outside / sample_client.rel).write_bytes(b"x")+ rec["output_dir"] = str(outside)+ rec_path.write_text(json.dumps(rec))+ url, q = _url("b" * 32, sample_client.rel)+ assert sample_client.client.get(url, params = q).status_code == 404+++def test_route_serves_live_job_and_hides_it_from_other_accounts(sample_client, monkeypatch):+ import core.training.account_jobs as aj++ svc = sample_client.svc+ live = "d" * 32+ svc._state.update(job_id = live, samples = [{"step": 50, "path": sample_client.rel}])+ svc._config = {"output_dir": str(sample_client.run_dir)}+ url, q = _url(live, sample_client.rel)+ assert sample_client.client.get(url, params = q).status_code == 200+ monkeypatch.setattr(aj, "job_is_foreign", lambda service: True)+ assert sample_client.client.get(url, params = q).status_code == 404+++def test_cfg_combination_matches_each_pipeline():+ c = torch.randn(1, 16, 1, 8, 8, generator = torch.Generator().manual_seed(1))+ u = torch.randn(1, 16, 1, 8, 8, generator = torch.Generator().manual_seed(2))+ g = 4.0+ # pipeline_stable_diffusion_xl.py / pipeline_flux2_klein.py: u + g(c - u)+ assert torch.allclose(ds.combine_cfg("uncond", g, c, u), u + g * (c - u))+ # pipeline_z_image.py:547, pipeline_krea2.py:666: c + g(c - u)+ assert torch.allclose(ds.combine_cfg("cond", g, c, u), c + g * (c - u))+ # pipeline_qwenimage.py:668-672 on the PACKED sequence, rescaled to the conditional norm per token.+ pytest.importorskip("diffusers")+ from diffusers import QwenImagePipeline++ pack = lambda t: QwenImagePipeline._pack_latents(t, 1, 16, 8, 8) # noqa: E731+ comb = pack(u) + g * (pack(c) - pack(u))+ ref = comb * (+ torch.norm(pack(c), dim = -1, keepdim = True) / torch.norm(comb, dim = -1, keepdim = True)+ )+ assert torch.allclose(pack(ds.combine_cfg("qwen", g, c, u)), ref, atol = 1e-5)+++ "family, base, steps, guidance, uses_cfg, mode, mu",+ [+ ("z-image", "unsloth/Z-Image-Turbo-unsloth-bnb-4bit", 8, 0.0, False, "cond", None),+ ("z-image", "Tongyi-MAI/Z-Image", 28, 4.0, True, "cond", None),+ ("krea-2", "krea/Krea-2-Turbo", 8, 0.0, False, "cond", 1.15),+ ("krea-2", "krea/Krea-2-Raw", 20, 4.5, True, "cond", None),+ ("qwen-image", "Qwen/Qwen-Image", 20, 4.0, True, "qwen", None),+ ("flux.2-klein", "black-forest-labs/FLUX.2-klein-base-4B", 28, 4.0, True, "uncond", None),+ ("sdxl", "stabilityai/stable-diffusion-xl-base-1.0", 20, 5.0, True, "uncond", None),+ ("sdxl", "stabilityai/sdxl-turbo", 4, 0.0, False, "uncond", None),+ ],+)+def test_family_sample_settings(family, base, steps, guidance, uses_cfg, mode, mu):+ st = ds.sample_inference_settings(family, base)+ assert (st.steps, st.guidance, st.uses_cfg, st.cfg_mode, st.mu) == (+ steps,+ guidance,+ uses_cfg,+ mode,+ mu,+ )+++def test_fixed_mu_reaches_the_schedule():+ pytest.importorskip("diffusers")+ from diffusers import FlowMatchEulerDiscreteScheduler++ sched = FlowMatchEulerDiscreteScheduler(use_dynamic_shifting = True)+ ref = FlowMatchEulerDiscreteScheduler.from_config(sched.config)+ import numpy as np++ ref.set_timesteps(sigmas = np.linspace(1.0, 1 / 8, 8).tolist(), mu = 1.15)+ got, _ = ds.flow_sigmas(sched.config, "krea-2", 8, 4096, mu = 1.15)+ assert torch.allclose(got, ref.sigmas.float())+++def test_stop_between_prompts_ends_the_round_keeping_finished_images(tmp_path):+ plan = ds.plan_samples(+ _cfg(output_dir = str(tmp_path), sample_every = 1, sample_prompts = ("a", "b", "c")).normalized(),+ "z-image",+ ["c"],+ )+ rendered, events = [], []++ def render(i, p):+ rendered.append(p)+ return torch.zeros(1, 3, 8, 8)++ stopped = ds.run_sample_round(+ plan, 5, render, None, lambda _cb, t, **kw: events.append(kw), lambda: len(rendered) >= 1+ )+ assert stopped and rendered == ["a"] and [e["prompt"] for e in events[0]["images"]] == ["a"]+++def test_stop_mid_denoise_aborts_the_image(tmp_path):+ pytest.importorskip("diffusers")+ from diffusers import FlowMatchEulerDiscreteScheduler++ plan = ds.plan_samples(+ _cfg(output_dir = str(tmp_path), sample_every = 1).normalized(), "z-image", ["c"]+ )+ calls = []++ def velocity(x, t, sig, cond):+ calls.append(1)+ return torch.zeros_like(x)++ with pytest.raises(ds.SampleRoundStopped):+ ds.euler_flow_sample(+ plan = plan,+ index = 0,+ latent_shape = (1, 4, 8, 8),+ image_seq_len = 16,+ family = "z-image",+ scheduler_config = FlowMatchEulerDiscreteScheduler(shift = 3.0).config,+ velocity = velocity,+ cond = "c",+ uncond = None,+ device = "cpu",+ weight_dtype = torch.float32,+ stop_requested = lambda: len(calls) >= 2,+ )+ assert len(calls) == 2+ events = []+ assert ds.run_sample_round(+ plan,+ 1,+ lambda i, p: (_ for _ in ()).throw(ds.SampleRoundStopped()),+ None,+ lambda *a, **k: events.append(k),+ )+ assert events == [] # nothing finished, nothing reported++[email protected]("module", ["diffusion_dit_trainer", "diffusion_lora_trainer"])+def test_trainers_latch_a_stop_seen_mid_round_and_render_a_resume_baseline(module):+ import importlib+ import inspect++ src = inspect.getsource(importlib.import_module(f"core.training.{module}"))+ assert "stop_now = stop_latched" in src and "if stop_latched:" in src+ assert src.index("_sample(resumed)") > src.index("restore_resume_state(")++[email protected]("module", ["diffusion_dit_trainer", "diffusion_lora_trainer"])+def test_sample_rounds_are_left_out_of_the_reported_rate(module):+ import importlib+ import inspect++ src = inspect.getsource(importlib.import_module(f"core.training.{module}"))+ sample = src[src.index("def _sample(step: int)") :]+ sample = sample[: sample.index("\n\n")]+ assert "t_rate += spent" in sample and "t_steady += spent" in sample+ assert "/ max(now - t_rate, 1e-6)" in src and "/ max(now - t_start, 1e-6)" not in src+++def test_flux2_dev_previews_use_the_pipeline_guidance_and_training_keeps_its_own(monkeypatch):+ pytest.importorskip("diffusers")+ import core.training.diffusion_dit_trainer as dit++ seen = []++ class _Transformer:+ config = SimpleNamespace(guidance_embeds = True)++ def __call__(self, *, hidden_states, guidance, **_):+ seen.append(float(guidance[0]))+ return (torch.zeros_like(hidden_states),)++ noisy = torch.zeros(1, 128, 4, 4)+ embeds = (torch.zeros(1, 2, 8), torch.zeros(1, 2, 4))+ args = (_Transformer(), noisy, torch.tensor([500.0]), None, embeds, None, "cpu", torch.float32)+ dit._flux2_forward(*args)+ dit._flux2_forward(*args, **dit._SPECS["flux.2-dev"].sample_forward_kwargs)+ # Flux2Pipeline defaults guidance_scale to 4.0; training stays on the reference 3.5.+ assert seen == [dit._FLUX2_TRAIN_GUIDANCE, 4.0]+++def test_sdxl_previews_zero_the_empty_negative_like_the_pipeline():+ import inspect++ import core.training.diffusion_lora_trainer as sdxl++ src = inspect.getsource(sdxl)+ render = src[src.index("def _render_sdxl(") :]+ render = render[: render.index("\n\n")]+ assert 'pipe.config.get("force_zeros_for_empty_prompt", False)' in render+ assert "torch.zeros_like(npe), torch.zeros_like(npooled)" in render+++def test_a_non_finite_preview_raises_instead_of_saving_a_black_image():+ good = ds.to_pil(torch.zeros(1, 3, 4, 4))+ assert len(good) == 1 and good[0].size == (4, 4)+ for bad in (float("nan"), float("inf")):+ with pytest.raises(ValueError, match = "NaN"):+ ds.to_pil(torch.full((1, 3, 4, 4), bad))+++def test_the_warm_cache_preview_load_is_rng_isolated():+ import inspect++ import core.training.diffusion_dit_trainer as dit++ src = inspect.getsource(dit)+ block = src[src.index("if caption_embeds is not None and sample_texts:") :]+ block = block[: block.index("sample_embeds = dict(")]+ assert "with isolated_sampling(device, False):" in block+ assert block.index("isolated_sampling") < block.index("spec.load_conditioners")diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 6e3cae434fd..34ca4489623 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -634,6 +634,9 @@ export interface DiffusionTrainingStartRequest {// stop-and-save always writes one, so Resume stays available either way.save_steps?: number;save_total_limit?: number;+ // Plus step 0 and the last step; 0 renders none.+ sample_every?: number;+ sample_prompts?: string[];// Continue a previous run: its output_dir, or one explicit checkpoint-<N> directory inside it. train_steps then// means the TARGET TOTAL, so a checkpoint at 11 with train_steps 500 runs 12..500.resume_from_checkpoint?: string | null;@@ -653,6 +656,19 @@ export interface DiffusionMetricHistory {grad_norm?: Array<number | null>;}+// One preview image a run rendered; `path` is relative to the run's output dir.+export interface DiffusionSampleImage {+ step: number;+ path: string;+ prompt?: string;+ seed?: number | null;+}++/** Auth-protected URL of one run's preview image; fetch it via fetchGalleryObjectUrl. */+export function diffusionSampleUrl(jobId: string, path: string): string {+ return `/api/train/diffusion/runs/${encodeURIComponent(jobId)}/sample?path=${encodeURIComponent(path)}`;+}+// A snapshot of the current diffusion training job (GET /api/train/diffusion/status).export interface DiffusionTrainingStatus {active: boolean;@@ -688,6 +704,8 @@ export interface DiffusionTrainingStatus {resumed_from_step?: number | null;// Bounded step/loss/lr history for the live charts.metric_history?: DiffusionMetricHistory | null;+ // Absent on an older backend.+ samples?: DiffusionSampleImage[];}export async function startDiffusionTraining(@@ -753,6 +771,7 @@ export interface DiffusionTrainingRunDetail extends DiffusionTrainingRunSummaryema_path?: string | null;config?: Record<string, unknown> | null;metric_history?: DiffusionMetricHistory | null;+ samples?: DiffusionSampleImage[];}export async function listDiffusionTrainingRuns(@@ -823,6 +842,8 @@ export interface DiffusionTrainableFamily {// Whether the family's loop writes checkpoint bundles (gates the "Checkpoint every" field).// Undefined on an older backend, which has no checkpointless family, so it reads as true.supports_checkpoints?: boolean;+ // Absent on an older backend: "Sample every" hidden.+ supports_samples?: boolean;// Undefined on an older backend (control hidden).supports_bucketing?: boolean;/** 1 for a family whose forward covers one packed sequence; null/absent means unrestricted. */diff --git a/studio/frontend/src/features/images/train/diffusion-samples-view.tsx b/studio/frontend/src/features/images/train/diffusion-samples-view.tsxnew file mode 100644index 00000000000..3f11943e03f--- /dev/null+++ b/studio/frontend/src/features/images/train/diffusion-samples-view.tsx@@ -0,0 +1,118 @@+// 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 { type ReactElement, useEffect, useMemo, useState } from "react";++import {+ type DiffusionSampleImage,+ diffusionSampleUrl,+ fetchGalleryObjectUrl,+} from "../api";+import { groupSamplesByStep } from "./diffusion-samples";++function SampleImage({+ jobId,+ image,+}: {+ jobId: string;+ image: DiffusionSampleImage;+}): ReactElement {+ const [src, setSrc] = useState<string | null>(null);+ useEffect(() => {+ let url: string | null = null;+ let cancelled = false;+ fetchGalleryObjectUrl(diffusionSampleUrl(jobId, image.path))+ .then(({ url: u }) => {+ if (cancelled) {+ URL.revokeObjectURL(u);+ return;+ }+ url = u;+ setSrc(u);+ })+ .catch(() => {+ /* a missing image keeps the placeholder */+ });+ return () => {+ cancelled = true;+ if (url) {+ URL.revokeObjectURL(url);+ }+ };+ }, [jobId, image.path]);+ return (+ <figure className="flex min-w-0 flex-col gap-1">+ <div className="aspect-square w-full overflow-hidden rounded-md bg-muted">+ {src ? (+ <img+ src={src}+ alt={image.prompt || "Sample"}+ className="size-full object-cover"+ />+ ) : null}+ </div>+ {image.prompt ? (+ <figcaption+ className="truncate text-ui-11 text-muted-foreground"+ title={image.prompt}+ >+ {image.prompt}+ </figcaption>+ ) : null}+ </figure>+ );+}++// Newest round by default (follows a live run until the user picks a step).+export function DiffusionSamples({+ jobId,+ samples,+}: {+ jobId: string;+ samples: DiffusionSampleImage[] | null | undefined;+}): ReactElement | null {+ const rounds = useMemo(() => groupSamplesByStep(samples), [samples]);+ // Keyed by job so another run's pick never carries over.+ const [picked, setPicked] = useState<{ jobId: string; step: number } | null>(+ null,+ );+ if (rounds.length === 0) {+ return null;+ }+ const pickedStep = picked?.jobId === jobId ? picked.step : null;+ const current =+ rounds.find((r) => r.step === pickedStep) ?? rounds[rounds.length - 1];+ return (+ <section className="flex flex-col gap-2">+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm font-semibold">+ Samples at step {current.step}+ </span>+ <span className="text-ui-11 text-muted-foreground">+ Same prompts and seeds every round+ </span>+ </div>+ <div className="flex flex-wrap gap-1">+ {rounds.map((r) => (+ <button+ key={r.step}+ type="button"+ onClick={() => setPicked({ jobId, step: r.step })}+ className={`rounded px-2 py-0.5 text-ui-11 tabular-nums ${+ r.step === current.step+ ? "bg-primary text-primary-foreground"+ : "bg-muted text-muted-foreground hover:text-foreground"+ }`}+ >+ {r.step}+ </button>+ ))}+ </div>+ <div className="grid max-w-3xl grid-cols-2 gap-3 @min-[720px]:grid-cols-4">+ {current.images.map((img) => (+ <SampleImage key={img.path} jobId={jobId} image={img} />+ ))}+ </div>+ </section>+ );+}diff --git a/studio/frontend/src/features/images/train/diffusion-samples.ts b/studio/frontend/src/features/images/train/diffusion-samples.tsnew file mode 100644index 00000000000..20809398d9d--- /dev/null+++ b/studio/frontend/src/features/images/train/diffusion-samples.ts@@ -0,0 +1,40 @@+// 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 type { DiffusionSampleImage } from "../api";++/** The backend refuses more than this many sample prompts. */+export const MAX_SAMPLE_PROMPTS = 4;++const LINE_BREAK = /\r?\n/;++export function parseSamplePrompts(text: string): string[] {+ return text+ .split(LINE_BREAK)+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ .slice(0, MAX_SAMPLE_PROMPTS);+}++export interface SampleRound {+ step: number;+ images: DiffusionSampleImage[];+}++/** Preview images grouped into rounds by step, oldest first; within a round in prompt order. */+export function groupSamplesByStep(+ samples: DiffusionSampleImage[] | null | undefined,+): SampleRound[] {+ const byStep = new Map<number, DiffusionSampleImage[]>();+ for (const s of samples ?? []) {+ if (!s || typeof s.path !== "string" || !Number.isFinite(s.step)) {+ continue;+ }+ const list = byStep.get(s.step) ?? [];+ list.push(s);+ byStep.set(s.step, list);+ }+ return Array.from(byStep.entries())+ .sort((a, b) => a[0] - b[0])+ .map(([step, images]) => ({ step, images }));+}diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsxindex 080571e6d4f..02cd80a64eb 100644--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx@@ -35,6 +35,7 @@ import { Button } from "@/components/ui/button";import { InfoHint } from "@/components/ui/info-hint";import { useScrollFades } from "@/hooks/use-scroll-fades";import { Input } from "@/components/ui/input";+import { Textarea } from "@/components/ui/textarea";import { Label } from "@/components/ui/label";import {Tooltip,@@ -97,6 +98,8 @@ import {} from "./dataset-files";import { DatasetShowcase } from "./dataset-showcase";import { DiffusionCharts } from "./diffusion-charts";+import { MAX_SAMPLE_PROMPTS, parseSamplePrompts } from "./diffusion-samples";+import { DiffusionSamples } from "./diffusion-samples-view";import {ExampleDatasetCards,runExampleImport,@@ -455,6 +458,8 @@ export function DiffusionTrainPanel({// Same for checkpoints: MiniMax-H3's loop writes no resume bundle and its validation REFUSES a// nonzero save_steps, so offering the field meant a rejected Start with nothing saying why.const supportsCheckpoints = reportedFamily?.supports_checkpoints ?? true;+ // Video families render no previews and REFUSE a nonzero sample_every; an older backend has none at all.+ const supportsSamples = reportedFamily?.supports_samples ?? false;// Same for buckets: MiniMax-H3 always trains one packed canvas, and an older backend drops the field.const supportsBucketing = reportedFamily?.supports_bucketing ?? false;// Same for the batch axis: MiniMax-H3's forward covers ONE packed sequence and its validation REFUSES a batch@@ -504,6 +509,8 @@ export function DiffusionTrainPanel({// Periodic resume points. 0 (off) keeps the default: only a stop-and-save writes one, so nothing// is spent on disk unless asked.const [saveSteps, setSaveSteps] = useState(0);+ const [sampleEvery, setSampleEvery] = useState(0);+ const [samplePromptsText, setSamplePromptsText] = useState("");// 0 keeps every checkpoint; backend default 2.const [saveTotalLimit, setSaveTotalLimit] = useState(2);// LR schedule. Warmup applies only to non-constant schedules. Seeded from the family, which is@@ -1206,6 +1213,9 @@ export function DiffusionTrainPanel({// Zero rather than the field's value when the family has none: the field is only hidden, not// reset, so a value typed for one family would otherwise still be sent and refused.save_steps: supportsCheckpoints ? Math.max(0, Math.floor(saveSteps)) : 0,+ sample_every: supportsSamples ? Math.max(0, Math.floor(sampleEvery)) : 0,+ sample_prompts:+ supportsSamples && sampleEvery > 0 ? parseSamplePrompts(samplePromptsText) : [],save_total_limit: supportsCheckpoints ? Math.max(0, Math.floor(saveTotalLimit)) : undefined,cfg_dropout: supportsCfgDropout ? cfgDropout : undefined,lora_dropout: loraDropout,@@ -1242,6 +1252,9 @@ export function DiffusionTrainPanel({gradAccum,seed,saveSteps,+ sampleEvery,+ samplePromptsText,+ supportsSamples,saveTotalLimit,gradCheckpoint,supportsBucketing,@@ -1480,6 +1493,11 @@ export function DiffusionTrainPanel({min: 0,hint: "Saves a resume point every this many steps, so a crash or a shutdown can be picked up where it left off. 0 turns it off; stopping and saving always leaves one either way.",})}+ {supportsSamples &&+ numberField("Sample every", sampleEvery, setSampleEvery, 0, {+ min: 0,+ hint: "Renders preview images with the same prompts and seeds every this many steps, so you can see when the LoRA has learned the subject and when it starts to overfit. 0 turns it off; each round adds a few seconds.",+ })}{supportsCheckpoints &&saveSteps > 0 &&numberField("Keep checkpoints", saveTotalLimit, setSaveTotalLimit, 2, {@@ -1489,6 +1507,23 @@ export function DiffusionTrainPanel({})}</div>+ {supportsSamples && sampleEvery > 0 && (+ <div className={fieldClass}>+ <FieldLabel+ hint={`One prompt per line, up to ${MAX_SAMPLE_PROMPTS}; each renders one image. Leave empty to use the trigger prompt or the first caption.`}+ >+ Sample prompts+ </FieldLabel>+ <Textarea+ value={samplePromptsText}+ placeholder={instancePrompt.trim() || "a photo in mystyle"}+ onChange={(e) => setSamplePromptsText(e.target.value)}+ rows={2}+ className="min-h-0 text-xs"+ />+ </div>+ )}+<div className="grid grid-cols-1 items-start gap-x-6 gap-y-5 @min-[324px]:grid-cols-2 @min-[498px]:grid-cols-3">{numberField("Learning rate", learningRate, setLearningRate, 0.0001, {min: 0,@@ -2226,6 +2261,7 @@ export function DiffusionTrainPanel({lossHistory={viewLossHistory}gradNormHistory={viewGradNormHistory}/>+ <DiffusionSamples jobId={viewRun.job_id} samples={viewRun.samples} /></>) : !hasRun ? (<>@@ -2465,6 +2501,9 @@ export function DiffusionTrainPanel({)}<DiffusionCharts lossHistory={lossHistory} gradNormHistory={gradNormHistory} />+ {status?.job_id ? (+ <DiffusionSamples jobId={status.job_id} samples={status.samples} />+ ) : null}</>)}</div>diff --git a/studio/frontend/tests/diffusion-train-samples.test.ts b/studio/frontend/tests/diffusion-train-samples.test.tsnew file mode 100644index 00000000000..d297fa6684a--- /dev/null+++ b/studio/frontend/tests/diffusion-train-samples.test.ts@@ -0,0 +1,65 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Sample images during training: the prompt parser matches the backend's limits, rounds group by+// step in order, and the panel only offers (and only sends) sampling for a family that renders it.++import assert from "node:assert/strict";+import test from "node:test";++import {+ MAX_SAMPLE_PROMPTS,+ groupSamplesByStep,+ parseSamplePrompts,+} from "../src/features/images/train/diffusion-samples.ts";+import { readSrcAsync } from "./helpers/kit.ts";++test("prompts: one per line, blanks dropped, capped at the backend limit", () => {+ assert.deepEqual(parseSamplePrompts(" a dog \n\n b dog\r\n "), [+ "a dog",+ "b dog",+ ]);+ assert.equal(+ parseSamplePrompts("1\n2\n3\n4\n5\n6").length,+ MAX_SAMPLE_PROMPTS,+ );+ assert.deepEqual(parseSamplePrompts(""), []);+});++test("rounds group by step, oldest first, prompt order kept", () => {+ const rounds = groupSamplesByStep([+ { step: 100, path: "samples/t/step-100-0.png" },+ { step: 0, path: "samples/t/step-0-0.png" },+ { step: 100, path: "samples/t/step-100-1.png" },+ ]);+ assert.deepEqual(+ rounds.map((r) => [r.step, r.images.map((i) => i.path)]),+ [+ [0, ["samples/t/step-0-0.png"]],+ [100, ["samples/t/step-100-0.png", "samples/t/step-100-1.png"]],+ ],+ );+ assert.deepEqual(groupSamplesByStep(undefined), []);+});++test("the panel gates and zeroes sampling on supports_samples", async () => {+ const source = await readSrcAsync(+ "features/images/train/diffusion-train-panel.tsx",+ );+ assert.match(+ source,+ /const supportsSamples = reportedFamily\?\.supports_samples \?\? false;/,+ );+ assert.match(+ source,+ /sample_every: supportsSamples \? Math\.max\(0, Math\.floor\(sampleEvery\)\) : 0/,+ );+ assert.match(+ source,+ /<DiffusionSamples jobId=\{viewRun\.job_id\} samples=\{viewRun\.samples\} \/>/,+ );+ assert.match(+ source,+ /<DiffusionSamples jobId=\{status\.job_id\} samples=\{status\.samples\} \/>/,+ );+});