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: fix FLUX.2 Klein LoRA training quality (#8267)
oobabooga0afb352bd4d4
diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex a98bdbd7d7e..5f6d59f33e4 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -95,6 +95,18 @@ class DiffusionFamily:train_base_repos: tuple[str, ...] = field(default_factory = tuple)# When set, deploying a LoRA trained on this family loads THIS repo instead (Krea: train on Raw, preview on Turbo). Same precision both sides.deploy_base_repo: Optional[str] = None+ # Variant-specific training-base to inference-base mappings. FLUX.2 Klein trains on an+ # undistilled base and runs the adapter on the matching 4-step checkpoint, so its 4B and 9B+ # variants cannot share the single family-wide deploy_base_repo above.+ deploy_base_repos: tuple[tuple[str, str], ...] = field(default_factory = tuple)++ def deploy_base_for(self, trained_base: str) -> str:+ """The inference checkpoint paired with ``trained_base``, or the input unchanged."""+ key = canonical_base(trained_base).lower()+ for training_repo, inference_repo in self.deploy_base_repos:+ if canonical_base(training_repo).lower() == key:+ return inference_repo+ return self.deploy_base_repo or trained_base# Keyed by architecture, not per variant: the base repo is read from the HF base_model tag at load time, so one entry covers Turbo/full, schnell/dev.@@ -144,9 +156,23 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (("fp8", "unsloth/FLUX.2-klein-4B-FP8"),),aliases = ("flux2-klein",),- # LoRA training via the DiT trainer (QLoRA nf4 by default); klein-4B is not gated.+ # Train the undistilled bases, then preview their adapters on the matching 4-step models.+ # Both vendor ids resolve through the ungated mirrors at fetch time.trainable = True,- train_base_repos = ("black-forest-labs/FLUX.2-klein-4B",),+ train_base_repos = (+ "black-forest-labs/FLUX.2-klein-base-4B",+ "black-forest-labs/FLUX.2-klein-base-9B",+ ),+ deploy_base_repos = (+ (+ "black-forest-labs/FLUX.2-klein-base-4B",+ "black-forest-labs/FLUX.2-klein-4B",+ ),+ (+ "black-forest-labs/FLUX.2-klein-base-9B",+ "black-forest-labs/FLUX.2-klein-9B",+ ),+ ),# Flux2KleinPipeline takes reference image(s) via `image`, so it exposes a "reference" workflow atop text-to-image. Inpaint but no img2img.reference = True,inpaint_pipeline_class = "Flux2KleinInpaintPipeline",@@ -521,10 +547,18 @@ _GATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (("ideogram-ai/ideogram-4-fp8", "unsloth/ideogram-4-fp8"),("ideogram-ai/ideogram-4-nf4", "unsloth/ideogram-4-nf4"),("ideogram-ai/ideogram-4-nf4-diffusers", "unsloth/ideogram-4-nf4-diffusers"),- # Ungated from here down: mirrored to drop the third-party fetch, not a gate. Every licence- # here permits redistribution, and each mirror carries the upstream licence text plus the- # notice that licence prescribes. Qwen-Image-2512 is the one no other redirect could reach:- # its companions are named by the artifact repo's base_model card tag, not the family table.+)++# Mirrored to drop the third-party fetch, NOT to route around a gate. Every licence here+# permits redistribution, and each mirror carries the upstream licence text plus the notice+# that licence prescribes. Qwen-Image-2512 is the one no other redirect could reach: its+# companions are named by the artifact repo's base_model card tag, not the family table.+#+# Kept apart from the gated pairs because the two answer different questions. Both redirect+# a fetch, but only a GATED upstream justifies overriding a user's existing cache: for these+# the upstream is reachable without credentials, so a complete local snapshot must keep being+# used rather than re-pulled from the mirror.+_UNGATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (("Qwen/Qwen-Image-2512", "unsloth/Qwen-Image-2512"),("Qwen/Qwen-Image", "unsloth/Qwen-Image"),("Qwen/Qwen-Image-Edit-2511", "unsloth/Qwen-Image-Edit-2511"),@@ -545,8 +579,10 @@ _GATED_MIRROR_PAIRS: tuple[tuple[str, str], ...] = (# excludes the EU, the UK and South Korea. A public Hub repo distributes worldwide, so that# mirror cannot be made compliant and the family keeps fetching upstream.)-_GATED_MIRRORS: dict[str, str] = {u.lower(): m for u, m in _GATED_MIRROR_PAIRS}-_MIRROR_UPSTREAM: dict[str, str] = {m.lower(): u for u, m in _GATED_MIRROR_PAIRS}+_MIRROR_PAIRS: tuple[tuple[str, str], ...] = _GATED_MIRROR_PAIRS + _UNGATED_MIRROR_PAIRS+_GATED_MIRRORS: dict[str, str] = {u.lower(): m for u, m in _MIRROR_PAIRS}+_MIRROR_UPSTREAM: dict[str, str] = {m.lower(): u for u, m in _MIRROR_PAIRS}+_GATED_UPSTREAMS: frozenset[str] = frozenset(u.lower() for u, _m in _GATED_MIRROR_PAIRS)def mirror_repo(repo_id: Optional[str]) -> Optional[str]:@@ -554,6 +590,15 @@ def mirror_repo(repo_id: Optional[str]) -> Optional[str]:return _GATED_MIRRORS.get((repo_id or "").strip().lower())+def upstream_is_gated(repo_id: Optional[str]) -> bool:+ """True when ``repo_id`` is a vendor base the Hub refuses without accepted terms.++ Distinct from "has a mirror": most of the mirror table is ungated and exists only to keep+ the fetch inside ``unsloth/*``. Only the gated half justifies overriding a user's cache.+ """+ return (repo_id or "").strip().lower() in _GATED_UPSTREAMS++def canonical_base(repo_id: Optional[str]) -> str:"""A mirror id mapped back to the upstream it copies, else ``repo_id`` unchanged.@@ -750,7 +795,10 @@ _GENERATION_DEFAULTS: tuple[tuple[str, int, float], ...] = (("flux.1-schnell", 4, 0.0),("kontext", 28, 2.5), # editing: before the generic flux.1("flux.1", 28, 3.5),- ("flux.2-klein", 4, 0.0),+ # The undistilled base variants need their model-card 50-step CFG recipe. Keep this before+ # the generic distilled key, which covers both 4B and 9B 4-step checkpoints.+ ("flux.2-klein-base", 50, 4.0),+ ("flux.2-klein", 4, 1.0),("flux.2-dev", 28, 4.0), # full (non-distilled)("qwen-image", 20, 4.0),("z-image", 20, 4.0),diff --git a/studio/backend/core/training/diffusion_checkpoint.py b/studio/backend/core/training/diffusion_checkpoint.pyindex a6b666eb6f8..cf2bfaffa5e 100644--- a/studio/backend/core/training/diffusion_checkpoint.py+++ b/studio/backend/core/training/diffusion_checkpoint.py@@ -191,6 +191,17 @@ def _revision_is_comparable(value: Any) -> bool:return isinstance(value, str) and value.startswith("rev-")+def _revision_repo(identity: "CheckpointIdentity") -> str:+ """The repo ``identity.base_revision`` was read from, normalised for comparison.++ A bundle written before mirrors existed has no ``base_revision_repo`` and always read the+ canonical base, so it falls back to ``base_model``: that keeps an old bundle comparable with+ a new one on a host that fetched the canonical repo, and only stops the comparison where it+ genuinely cannot be made.+ """+ return str(getattr(identity, "base_revision_repo", None) or identity.base_model or "").lower()++@dataclass(frozen = True)class CheckpointIdentity:"""What a checkpoint was trained as. Two bundles are interchangeable only when every@@ -253,6 +264,12 @@ class CheckpointIdentity:# Post-conversion, set by the DiT trainer once it knows whether fp8/mxfp8 took. None# everywhere else, which the optional rule reads as "cannot tell".base_precision_effective: Optional[str] = None+ # WHICH repo ``base_revision`` was read from, which is not always ``base_model``: a gated base+ # is fetched from its byte-identical ungated mirror, and the two repos have different commit+ # SHAs for the same weights. Not a mismatch reason of its own -- it only says whether the two+ # revisions are comparable at all. None means a bundle written before mirrors existed, whose+ # revision came from the canonical base, so it reads as ``base_model`` below.+ base_revision_repo: Optional[str] = Nonedef as_dict(self) -> dict[str, Any]:return {@@ -260,6 +277,7 @@ class CheckpointIdentity:"family": self.family,"base_model": self.base_model,"base_revision": self.base_revision,+ "base_revision_repo": self.base_revision_repo,"dataset_fingerprint": self.dataset_fingerprint,"lora_target_modules": list(self.lora_target_modules),"lora_rank": int(self.lora_rank),@@ -336,6 +354,7 @@ class CheckpointIdentity:resolution = int(data.get("resolution") or 0),kind = str(data.get("kind") or "image"),base_revision = _optional_str(data.get("base_revision")),+ base_revision_repo = _optional_str(data.get("base_revision_repo")),dataset_fingerprint = _optional_str(data.get("dataset_fingerprint")),)except (TypeError, ValueError):@@ -361,6 +380,12 @@ class CheckpointIdentity:_revision_is_comparable(a) and _revision_is_comparable(b)):continue+ # Two commit SHAs are only comparable when they name the same repo. A gated base is+ # fetched from its byte-identical ungated mirror, so the same weights carry a+ # different SHA depending on which repo the host happened to pull from, and comparing+ # across the two reports a revision change that did not happen.+ if field == "base_revision" and _revision_repo(self) != _revision_repo(other):+ continueif a == b:continueif field == "dataset_fingerprint":@@ -548,7 +573,10 @@ def with_resolved_revision(identity: "CheckpointIdentity", base_model: Any) -> "resolved = source_revision(base_model)if not _revision_is_comparable(resolved) or resolved == identity.base_revision:return identity- return replace(identity, base_revision = resolved)+ # The repo travels with the revision: callers pass the repo they FETCHED from, which for a+ # gated base is the ungated mirror, and a SHA without the repo that produced it cannot be+ # compared against one from the other repo.+ return replace(identity, base_revision = resolved, base_revision_repo = str(base_model or ""))def identity_for_config(@@ -569,6 +597,9 @@ def identity_for_config(from core.training.diffusion_train_extras import source_revisiontargets = tuple(resolved_targets) if resolved_targets else _resolve_lora_targets(cfg)+ # ``base_model`` stays canonical everywhere else in the identity; only the revision pair+ # below follows the repo the weights are pulled from.+ fetch_base_model = str(getattr(cfg, "fetch_base_model", None) or cfg.base_model or "")return CheckpointIdentity(family = str(getattr(cfg, "resolved_family", "") or ""),base_model = str(cfg.base_model or ""),@@ -601,7 +632,15 @@ def identity_for_config(base_precision = str(getattr(cfg, "base_precision", "") or ""),resolution = int(cfg.resolution),kind = kind,- base_revision = source_revision(cfg.base_model),+ # The revision of the repo actually FETCHED, recorded together with which repo that was.+ # Reading the canonical base instead loses the check entirely: the mirror is selected+ # precisely BECAUSE the canonical repo is not cached, so it has no local ref and every+ # mirror-backed bundle would record "unresolved", which mismatch_reason skips. Pairing+ # the revision with its repo keeps the comparison wherever it is meaningful (same repo+ # on both sides, including every pre-mirror bundle) and drops it only across a+ # canonical/mirror pair, whose SHAs differ for byte-identical weights.+ base_revision = source_revision(fetch_base_model),+ base_revision_repo = fetch_base_model,dataset_fingerprint = dataset_fingerprint(dataset_pairs) if dataset_pairs else None,)diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex ec04e0ca628..0c69ec18c9a 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -976,15 +976,25 @@ def _krea2_save(pipe_cls, out_dir, transformer_lora_layers):# ── FLUX.2 (dev + Klein) ──────────────────────────────────────────────────────# Both variants share Flux2Transformer2DModel and the upstream DreamBooth packing/forward conventions, differing only in the conditioning# stack (dev: Mistral-3-Small; Klein: Qwen3) and size. Latents train patchified and batch-norm-normalised, from the posterior MODE (deterministic).-_FLUX2_TARGETS = (+_FLUX2_COMMON_TARGETS = (# Double-stream blocks: separate q/k/v plus the ModuleList out proj."to_k","to_q","to_v","to_out.0",- # Single-stream blocks: the fused qkv+mlp input projection carries most of the capacity. Their out proj is a plain Linear named to_out, whose suffix also matches the double-stream container, so it stays dense.+ # Single-stream blocks use one fused qkv+mlp input projection."to_qkv_mlp_proj",)+# Their output projection is a plain Linear called ``to_out``. A bare suffix also matches the+# double-stream ModuleList, which PEFT cannot wrap, so the upstream trainers name each single block+# explicitly: 24 possible blocks for Klein and 48 for dev. Missing high indexes are harmless on the+# smaller Klein-4B layout, which has 20 single blocks.+_FLUX2_KLEIN_TARGETS = _FLUX2_COMMON_TARGETS + tuple(+ f"single_transformer_blocks.{i}.attn.to_out" for i in range(24)+)+_FLUX2_DEV_TARGETS = _FLUX2_COMMON_TARGETS + tuple(+ f"single_transformer_blocks.{i}.attn.to_out" for i in range(48)+)# The references train dev with its guidance-distillation vector at 3.5 (Klein applies it only when the variant config carries guidance_embeds)._FLUX2_TRAIN_GUIDANCE = 3.5@@ -1410,7 +1420,7 @@ _SPECS: dict[str, _FamilySpec] = {),"flux.2-klein": _FamilySpec(family = "flux.2-klein",- lora_targets = _FLUX2_TARGETS,+ lora_targets = _FLUX2_KLEIN_TARGETS,# The upstream references train in bf16; fp16 is unvalidated on the FLUX.2 stack.force_bf16 = True,dense_bf16_gb = 8.1,@@ -1425,7 +1435,7 @@ _SPECS: dict[str, _FamilySpec] = {),"flux.2-dev": _FamilySpec(family = "flux.2-dev",- lora_targets = _FLUX2_TARGETS,+ lora_targets = _FLUX2_DEV_TARGETS,force_bf16 = True,# 32B DiT; the Mistral conditioning stack (~46 GB bf16) is loaded, encoded and freed BEFORE this lands on the device (the shared phased load).dense_bf16_gb = 64.5,@@ -1464,7 +1474,13 @@ _GATED_TRAIN_REPOS = frozenset({"black-forest-labs/flux.1-dev", "black-forest-ladef _assert_gated_access(base_model: str, hf_token: Optional[str]) -> None:"""Raise a clear error before loading a gated base without a token."""+ from core.inference.diffusion_families import _is_local_path+name = str(base_model or "").strip().lower()+ # A local clone named like the vendor repo is weights on disk, not a Hub fetch: no gate+ # applies, and refusing it by name alone is what made that documented layout untrainable.+ if _is_local_path(base_model):+ returnif name in _GATED_TRAIN_REPOS and not (hf_token and str(hf_token).strip()):raise ValueError(f"'{base_model}' is a gated Hugging Face repo. Accept its license on the Hub "@@ -1840,7 +1856,11 @@ def run_dit_lora_training(weight_dtype = torch.bfloat16 if device == "cuda" else torch.float32_assert_trusted_base_model(cfg.base_model)- _assert_gated_access(cfg.base_model, cfg.hf_token)+ # The repo this run will FETCH, which is what the start route preflights. Checking the+ # canonical id instead would raise here for a gated base that normalization already+ # redirected to its ungated mirror -- after the route had answered 200 and freed the+ # resident models, so the request fails as a dead job rather than as a fast 400.+ _assert_gated_access(cfg.fetch_base_model or cfg.base_model, cfg.hf_token)pairs = discover_image_caption_pairs(cfg.data_dir, instance_prompt = cfg.instance_prompt, caption_column = cfg.caption_column)@@ -1918,6 +1938,10 @@ def _train_dit(use_lora_targets = _select_lora_targets(cfg.lora_target_modules, spec.lora_targets)out_dir = Path(cfg.output_dir).expanduser()+ # Load from the byte-identical public mirror selected during normalization, while keeping+ # cfg.base_model canonical for the adapter sidecar, completion event, and resume identity.+ # One fetch config covers the conditioning pipeline, transformer, and scheduler.+ fetch_cfg = replace(cfg, base_model = cfg.fetch_base_model or cfg.base_model)# Phase 0: the persistent conditioning cache (opt-in via cond_cache_dir). When every planned latent variant AND caption embedding is on disk, the run is "warm": the VAE and text encoders never load.image_paths = [p for p, _ in pairs]@@ -1934,7 +1958,7 @@ def _train_dit(try:# Namespace on the CHECKPOINT, not just the family: the keys carry only caption/image content, so one cache dir reused for two checkpoints would train on the other model's embeddings and latent stats.from .diffusion_train_extras import source_revision # noqa: PLC0415- namespace = f"{spec.family}_{cfg.base_model}_{source_revision(cfg.base_model)}"+ namespace = f"{spec.family}_{cfg.base_model}_{source_revision(fetch_cfg.base_model)}"pcache = PersistentConditioningCache(cfg.cond_cache_dir, namespace, cfg.resolution)except Exception as exc: # noqa: BLE001 -- the cache is an optimisation, never fatal_emit(on_event, "warning", message = f"conditioning cache disabled: {exc}")@@ -1962,7 +1986,7 @@ def _train_dit(if caption_embeds is None:# Phase 1 (cold): conditioning only. The pipeline loads WITHOUT its transformer, so the encoders + VAE never share VRAM with it. Captions are constant, so their embeddings are precomputed once and the encoders freed.latent_cache = None- pipe, vae = spec.load_conditioners(cfg, device, weight_dtype)+ pipe, vae = spec.load_conditioners(fetch_cfg, device, weight_dtype)encoded = _encode_prompts_cached(spec, pipe, to_encode, device, pcache)caption_embeds = {cap: emb for cap, emb in zip(to_encode, encoded)}_free_text_encoders(pipe)@@ -2016,7 +2040,7 @@ def _train_dit(# Phase 3: only now load the transformer, in the resolved base precision (nf4 QLoRA by default; bf16 / int8 / fp8 / mxfp8 are the dense speed modes; "auto" picks from free VRAM).base_precision = _resolve_base_precision(cfg, spec, device)- transformer = spec.load_transformer(cfg, device, weight_dtype, base_precision)+ transformer = spec.load_transformer(fetch_cfg, device, weight_dtype, base_precision)base_is_bnb = base_precision == "nf4"# Freeze the base; attach the trainable LoRA to the transformer.@@ -2061,7 +2085,7 @@ def _train_dit(optimizer = _make_optimizer(lora_params, cfg.learning_rate)scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(- cfg.base_model, subfolder = "scheduler", token = cfg.hf_token+ fetch_cfg.base_model, subfolder = "scheduler", token = cfg.hf_token)# Timestep-shift + loss-weighting setup (see _training_sigma_table). getattr defaults keep an un-normalized config on the historical behavior.flow_shift = getattr(cfg, "flow_shift", None)@@ -2088,7 +2112,11 @@ def _train_dit(# every bundle this run saves. The identity built before the load says "unresolved" on the# first run of an uncached repo, and an unresolved revision is not comparable, so a later# resume could not tell that the repo had moved underneath it.- identity = with_resolved_revision(identity, cfg.base_model)+ # The repo actually fetched, matching identity_for_config: the canonical base is not on disk+ # at all when the mirror was selected, so reading it here would pin "unresolved" forever.+ # with_resolved_revision records which repo the SHA came from, and mismatch_reason only+ # compares two revisions that came from the same one.+ identity = with_resolved_revision(identity, fetch_cfg.base_model)# See the SDXL trainer: the cache path the loop actually took, not the one requested.identity = with_cache_mode(identity, latent_cache is not None)# ...and the precision the frozen base ended up in. base_precision is still the request atdiff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.pyindex 8c9cbe81ff4..7710cd24e9b 100644--- a/studio/backend/core/training/diffusion_train_common.py+++ b/studio/backend/core/training/diffusion_train_common.py@@ -533,6 +533,17 @@ _FAMILY_TRAIN_SPECS: dict[str, dict[str, Any]] = {"note": "Video: trains a style LoRA on still images.",},}+# Facts that differ between selectable checkpoints inside one family. Keys are canonical+# upstream ids; family_train_infos also publishes the mirror aliases so a custom mirror pick+# gets the same guidance. Values overlay the family facts in the client.+_BASE_TRAIN_SPECS: dict[str, dict[str, Any]] = {+ "black-forest-labs/flux.2-klein-base-9b": {+ "params": "9B",+ # The auto policy measures 16.4 GB for the bf16 text encoder alone. Leave room for+ # the VAE and runtime state rather than inheriting the 4B checkpoint's 10 GB floor.+ "qlora_vram_gb": 18,+ },+}_GATED_NOTE = "Gated: needs its license and your HF token."@@ -723,7 +734,7 @@ def family_train_infos() -> list[dict[str, Any]]:the preflight and the start route all accepted it, but nothing ever offered it. A family whosepipeline class the installed diffusers lacks is dropped rather than advertised, since the startroute refuses it (``training_pipeline_import_error``) and no choice in the UI can fix that."""- from core.inference.diffusion_families import family_pipeline_available+ from core.inference.diffusion_families import family_pipeline_available, mirror_repofrom core.inference.diffusion_transformer_quant import _family_train_denieddit_modes, dit_recommended = train_precision_modes()@@ -750,6 +761,23 @@ def family_train_infos() -> list[dict[str, Any]]:else:fam_modes = [m for m in dit_modes if not _family_train_denied(name, m)]spec = _FAMILY_TRAIN_SPECS.get(name, {})+ deploy_bases: dict[str, str] = {}+ base_specs: dict[str, dict[str, Any]] = {}+ for repo in repos:+ base_spec = _BASE_TRAIN_SPECS.get(str(repo).strip().lower())+ if not base_spec:+ continue+ base_specs[repo] = dict(base_spec)+ repo_mirror = mirror_repo(repo)+ if repo_mirror:+ base_specs[repo_mirror] = dict(base_spec)+ for training_repo, inference_repo in getattr(fam, "deploy_base_repos", ()):+ deploy_bases[training_repo] = inference_repo+ # A custom base entered with the public mirror id must follow the same pairing as the+ # advertised vendor id. Return the inference mirror too, so Deploy stays ungated.+ training_mirror = mirror_repo(training_repo)+ if training_mirror:+ deploy_bases[training_mirror] = mirror_repo(inference_repo) or inference_repoinfos.append({"name": name,@@ -769,6 +797,15 @@ def family_train_infos() -> list[dict[str, Any]]:"supports_compile": bool(not dit_block),# Krea trains on Raw but previews adapters on Turbo; None elsewhere (and never for a video family)."deploy_base": getattr(fam, "deploy_base_repo", None),+ # Families with several train/deploy pairs cannot use the scalar above.+ "deploy_bases": deploy_bases,+ # Checkpoint-specific facts overlay the family facts in the Train UI. Dropped on a+ # dit_block for the same reason the family chips above are: the overlay wins in+ # resolveDiffusionTrainingFacts, so a per-base entry would put the 9B / 18 GB chips+ # back, and FamilyFacts renders vram_note only when there are NO chips. Leaving+ # these populated therefore replaces the actionable hardware reason (no CUDA, no+ # native bf16) with a size the host cannot act on.+ "base_specs": {} if dit_block else base_specs,})return infos@@ -807,6 +844,9 @@ class DiffusionLoraConfig:caption_column: str = "text" # column in metadata.jsonladapter_name: str = "default"hf_token: Optional[str] = None+ # Derived by normalized(): the byte-identical mirror used by from_pretrained while+ # base_model remains the canonical id stored in metadata and resume identity.+ fetch_base_model: Optional[str] = None# Precompute the VAE latents once (freeing the VAE) instead of re-encoding every step. ``cache_variants`` crop/flip draws are frozen per image; the per-step VAE sampling noise is preserved.cache_latents: bool = Truecache_variants: int = 4@@ -997,6 +1037,45 @@ class DiffusionLoraConfig:targets = tuple(self.lora_target_modules) or DEFAULT_LORA_TARGETS# A blank Hub token (the Studio default when none is configured) must load anonymously, not as an explicit empty credential.token = self.hf_token.strip() if isinstance(self.hf_token, str) else self.hf_token+ from core.inference.diffusion_families import (+ _is_local_path,+ mirror_repo,+ prefer_ungated_mirror,+ upstream_is_gated,+ )++ if resolved_family == "sdxl":+ fetch_base_model = self.base_model+ else:+ fetch_base_model = prefer_ungated_mirror(self.base_model, token or None)+ # For a GATED upstream and no token, the cache preference has to be overridden: the+ # credentials this run lacks are the credentials the fetch needs, so a partial+ # snapshot cannot be completed and the start route's HEAD refuses even a complete+ # one. prefer_ungated_mirror's probe counts any cached weight as a hit, so a single+ # leftover shard from an interrupted or previously authorized download was enough to+ # keep the vendor id and hard-block the very case the mirrors exist for.+ #+ # Only gated, though. Most of the mirror table is ungated, mirrored to keep the+ # fetch inside unsloth/*, and there the upstream is reachable anonymously: an+ # override would discard a complete local cache and re-pull gigabytes, or fail+ # outright offline. Those keep prefer_ungated_mirror's cache-aware answer.+ #+ # UNSLOTH_DIFFUSION_NO_MIRROR still wins, exactly as it does inside+ # prefer_ungated_mirror: it is the documented way to pin the vendor repo, and an+ # override that ignored it would make that switch a lie on the training path only.+ #+ # A local clone wins over both. A base can be a directory named exactly like the+ # vendor id (the loaders resolve `black-forest-labs/FLUX.1-dev` on disk when it+ # exists), and prefer_ungated_mirror carves that out for the same reason: rewriting+ # it sends the fetch to the Hub past weights the user already has, so the run trains+ # on a different repo, or fails offline.+ if (+ not token+ and upstream_is_gated(self.base_model)+ and not _is_local_path(self.base_model)+ and not os.environ.get("UNSLOTH_DIFFUSION_NO_MIRROR", "").strip()+ ):+ fetch_base_model = mirror_repo(self.base_model) or fetch_base_model# A blank caption_column means the default, as the start route's own preflight already# assumes ("or 'text'"). Without this the route and the trainer resolve different captions# from a metadata.jsonl, so their dataset fingerprints disagree and a resume that the@@ -1009,6 +1088,7 @@ class DiffusionLoraConfig:lora_target_modules = targets,max_grad_norm = float(self.max_grad_norm),hf_token = token or None,+ fetch_base_model = fetch_base_model,caption_column = caption_column,num_epochs = int(self.num_epochs),cache_variants = int(self.cache_variants),@@ -1369,6 +1449,8 @@ _TRAIN_EXTRA_TRUSTED_REPOS = frozenset({"black-forest-labs/flux.2-dev","black-forest-labs/flux.2-klein-4b",+ "black-forest-labs/flux.2-klein-base-4b",+ "black-forest-labs/flux.2-klein-base-9b",# LTX-2's official base. It is a video family, so the image-side inference allowlist# (_is_trusted_diffusion_repo) never covered it; safetensors-only, no remote code."lightricks/ltx-2",diff --git a/studio/backend/hub/tests/test_companion_assets.py b/studio/backend/hub/tests/test_companion_assets.pyindex e93f200b82a..5827faef4bb 100644--- a/studio/backend/hub/tests/test_companion_assets.py+++ b/studio/backend/hub/tests/test_companion_assets.py@@ -862,3 +862,19 @@ def test_the_preview_reads_a_path_qualified_variant(monkeypatch):)impact = asyncio.run(companion_cleanup.delete_impact_response(repo, variant))assert impact["reclaimed_bytes"] == 6_000_000+++def test_the_curated_bases_carry_the_whole_mirror_table():+ """Gated and ungated alike, both sides of every pair.++ Gating decides whether a fetch may override a user's cache; it has nothing to do with whether+ a base can strand an installed checkpoint's companions, and most of the table is ungated.+ Reading only the gated half dropped Klein 4B and base-4B, HiDream Dev / Fast, SDXL Turbo and+ the Qwen bases from the curated ids, so before a companion link is recorded the guards no+ longer recognised those cached bases.+ """+ from core.inference.diffusion_families import _MIRROR_PAIRS++ curated = companion_assets._curated_base_ids()+ missing = [rid for pair in _MIRROR_PAIRS for rid in pair if rid not in curated]+ assert missing == []diff --git a/studio/backend/hub/utils/companion_assets.py b/studio/backend/hub/utils/companion_assets.pyindex a1cf85277d8..6ab669a0f0a 100644--- a/studio/backend/hub/utils/companion_assets.py+++ b/studio/backend/hub/utils/companion_assets.py@@ -516,11 +516,17 @@ def known_companion_base_ids() -> set[str]:def _mirror_pair_ids() -> set[str]:+ # The WHOLE table, gated and ungated. Gating decides whether a fetch may override a user's+ # cache; it says nothing about whether a base can strand companions, and most of the table+ # is ungated (Klein 4B and base-4B, HiDream Dev / Fast, SDXL Turbo, ...). Reading only the+ # gated half would drop those from the curated ids, so before a companion link is recorded+ # the cleanup would not recognise them and could offer an installed checkpoint's companions+ # for deletion.try:- from core.inference.diffusion_families import _GATED_MIRROR_PAIRS+ from core.inference.diffusion_families import _MIRROR_PAIRSexcept Exception: # noqa: BLE001return set()- return {rid for pair in _GATED_MIRROR_PAIRS for rid in pair}+ return {rid for pair in _MIRROR_PAIRS for rid in pair}def is_companion_base(repo_id: str) -> bool:diff --git a/studio/backend/models/training.py b/studio/backend/models/training.pyindex 3773ae709b6..53242ee1521 100644--- a/studio/backend/models/training.py+++ b/studio/backend/models/training.py@@ -1106,6 +1106,10 @@ class DiffusionTrainableFamily(BaseModel):supports_compile: bool = False# When set, a LoRA trained on this family previews on this repo instead of the training base (Krea trains on Raw, runs on Turbo).deploy_base: Optional[str] = None+ # Variant-specific training-base to inference-base pairs, including public mirror ids.+ deploy_bases: Dict[str, str] = Field(default_factory = dict)+ # Per-checkpoint facts that overlay the family-level params/VRAM guidance.+ base_specs: Dict[str, dict] = Field(default_factory = dict)class DiffusionTrainingInfoResponse(BaseModel):diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex b0eaef87bb4..fe358d241ad 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -2598,13 +2598,19 @@ def _preflight_gated_base(base_model: str, hf_token: Optional[str]) -> None:import urllib.errorimport urllib.request+ from core.inference.diffusion_families import _is_local_path+repo = (base_model or "").strip()- # Only remote 'org/name' repos are gated; skip local paths and single-file names.+ # Only remote 'org/name' repos are gated; skip local paths and single-file names. A RELATIVE+ # clone counts: a directory named exactly like the vendor id is what the loaders and the+ # mirror override both resolve on disk, and it carries one slash and no leading marker, so+ # without the existence test this HEADs the gated repo and 400s a run that never leaves disk.if (not repoor repo.count("/") != 1or repo.startswith((".", "/", "~"))or repo.endswith(".gguf")+ or _is_local_path(repo)):returnurl = f"https://huggingface.co/{repo}/resolve/main/model_index.json"@@ -2838,10 +2844,13 @@ async def start_diffusion_training(except ValueError as e:raise HTTPException(status_code = 400, detail = str(e))- # Preflight access to a gated base repo with the user's token BEFORE freeing GPU residents,- # so a missing token fails fast (400). In a worker thread: blocking urlopen HEAD (5s).+ # Preflight the repo the trainer will actually fetch, not the canonical id retained in its+ # metadata. A gated canonical base may normalize to a byte-identical public mirror.+ # In a worker thread: blocking urlopen HEAD (5s).await asyncio.to_thread(- _preflight_gated_base, config.get("base_model", ""), config.get("hf_token")+ _preflight_gated_base,+ normalized_cfg.fetch_base_model or normalized_cfg.base_model,+ normalized_cfg.hf_token,)from core.training import diffusion_train_common as _dtcdiff --git a/studio/backend/tests/test_diffusion_auto_policy.py b/studio/backend/tests/test_diffusion_auto_policy.pyindex e11dc386300..5c23cd93734 100644--- a/studio/backend/tests/test_diffusion_auto_policy.py+++ b/studio/backend/tests/test_diffusion_auto_policy.py@@ -77,6 +77,11 @@ def test_base_repo_override_wins_over_the_family_default():assert nine_b is not None and default is not Noneassert nine_b[0] > 2 * default[0]+ base_nine_b = family_bf16_components_gb(+ _fam("flux.2-klein"), base_repo = "unsloth/FLUX.2-klein-base-9B"+ )+ assert base_nine_b == nine_b+def test_klein_base_9b_is_sized_like_the_9b_not_the_4b():# klein-base-9B is the undistilled 9B (18.2 GB transformer + the Qwen3-8B encoder), and it isdiff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 560f5c1ecad..f853331fd41 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -33,6 +33,8 @@ import core.inference.diffusion_eager_patches # noqa: E402,F401import core.inference.diffusion_arch_patches # noqa: E402,F401from core.inference.diffusion_families import (_GATED_MIRROR_PAIRS,+ _MIRROR_PAIRS,+ _UNGATED_MIRROR_PAIRS,assert_flux2_gguf_matches_base,canonical_base,detect_family,@@ -43,6 +45,7 @@ from core.inference.diffusion_families import (resolve_local_gguf_child,sd_cpp_companion_only_repo_ids,supported_family_names,+ upstream_is_gated,)@@ -177,8 +180,8 @@ def _all_cached(monkeypatch):def test_gated_mirror_table_round_trips():"""Both directions, exact case: canonical_base must hand back a real repo id."""- assert len(_GATED_MIRROR_PAIRS) == 24- for upstream, mirror in _GATED_MIRROR_PAIRS:+ assert len(_MIRROR_PAIRS) == 24+ for upstream, mirror in _MIRROR_PAIRS:assert mirror_repo(upstream) == mirrorassert canonical_base(mirror) == upstream# Case-insensitive in, since a card tag may carry any casing.@@ -191,6 +194,28 @@ def test_gated_mirror_table_round_trips():assert canonical_base(hunyuan) == hunyuan+def test_only_the_genuinely_gated_half_reads_as_gated():+ """Redirecting a fetch and needing credentials are different questions.++ Most of the table is mirrored to keep the fetch inside ``unsloth/*``, not to route around a+ gate, and callers that override a user's cache must key on the gate rather than on "a mirror+ exists". Klein base-4B is the one that makes this concrete: a default trainable base, which+ is mirrored, and which the Hub serves anonymously.+ """+ assert len(_GATED_MIRROR_PAIRS) == 12+ assert len(_UNGATED_MIRROR_PAIRS) == 12+ for upstream, _mirror in _GATED_MIRROR_PAIRS:+ assert upstream_is_gated(upstream), upstream+ assert upstream_is_gated(upstream.upper()), upstream+ for upstream, _mirror in _UNGATED_MIRROR_PAIRS:+ assert not upstream_is_gated(upstream), upstream+ assert mirror_repo("black-forest-labs/FLUX.2-klein-base-4B")+ assert not upstream_is_gated("black-forest-labs/FLUX.2-klein-base-4B")+ # A repo outside the table entirely is not gated either.+ assert not upstream_is_gated("hunyuanvideo-community/HunyuanImage-2.1-Diffusers")+ assert not upstream_is_gated(None)++def test_no_mirror_is_a_companion_only_repo():"""A mirror substitutes for the WHOLE base, so it must never be a components-only repo.@@ -199,7 +224,7 @@ def test_no_mirror_is_a_companion_only_repo():missing-weights error. The companion-only set is exactly that list of repos."""companions = sd_cpp_companion_only_repo_ids()- for _upstream, mirror in _GATED_MIRROR_PAIRS:+ for _upstream, mirror in _MIRROR_PAIRS:assert mirror.lower() not in companions, mirror@@ -222,7 +247,7 @@ def test_every_third_party_bf16_pipeline_the_catalog_offers_is_mirrored():"export const VIDEO_CATALOG", 1)[0]offered = set(re.findall(r'bf16Pipeline\(\s*"([^"]+)"', images))- mirrored = {u.lower() for u, _m in _GATED_MIRROR_PAIRS}+ mirrored = {u.lower() for u, _m in _MIRROR_PAIRS}# Anything under unsloth/ is already ours, and the deliberate Hunyuan exception is recorded# beside the table with the territorial reason it cannot be mirrored.missing = sorted(@@ -254,7 +279,7 @@ def test_the_qwen_2512_mirror_covers_the_card_tag_route(monkeypatch):def test_prefer_ungated_mirror_swaps_gated_bases(monkeypatch):_no_cache(monkeypatch)- for upstream, mirror in _GATED_MIRROR_PAIRS:+ for upstream, mirror in _MIRROR_PAIRS:assert prefer_ungated_mirror(upstream) == mirror# A base outside the table is untouched.hunyuan = "hunyuanvideo-community/HunyuanImage-2.1-Diffusers"diff --git a/studio/backend/tests/test_diffusion_base_precision.py b/studio/backend/tests/test_diffusion_base_precision.pyindex 1704e1d1084..b015acdcc0f 100644--- a/studio/backend/tests/test_diffusion_base_precision.py+++ b/studio/backend/tests/test_diffusion_base_precision.py@@ -66,6 +66,32 @@ def test_base_precision_validation():assert _cfg(base_model = _Z_PREQUANT, base_precision = "auto").normalized().base_precision == "auto"+def test_normalized_config_keeps_the_canonical_base_and_pins_its_fetch_mirror(monkeypatch):+ from core.inference import diffusion_families++ upstream = "black-forest-labs/FLUX.2-klein-base-9B"+ mirror = "unsloth/FLUX.2-klein-base-9B"+ seen = []++ def _prefer(base, token = None):+ seen.append((base, token))+ return mirror++ monkeypatch.setattr(diffusion_families, "prefer_ungated_mirror", _prefer)+ norm = _cfg(base_model = upstream, hf_token = " token ").normalized()++ assert norm.base_model == upstream+ assert norm.fetch_base_model == mirror+ assert norm.hf_token == "token"+ assert seen == [(upstream, "token")]++ # SDXL has its own trainer and still loads base_model directly, so its revision source must+ # not be redirected until that loader opts into the same fetch field.+ sdxl = _cfg(base_model = "stabilityai/stable-diffusion-xl-base-1.0").normalized()+ assert sdxl.fetch_base_model == sdxl.base_model+ assert seen == [(upstream, "token")]++def test_base_precision_denies_fp8_for_corrupted_family():# fp8 corrupts the Qwen-Image DiT, so a dense Qwen base with base_precision="fp8" is refused up front.with pytest.raises(ValueError, match = "fp8"):@@ -246,6 +272,29 @@ def test_family_train_infos_empties_dit_modes_on_non_bf16(monkeypatch):assert dit_seen # the registry must still expose at least one DiT family to have covered it+def test_family_train_infos_drops_base_specs_on_a_dit_block(monkeypatch, dit_train_host):+ # The per-base overlay wins in resolveDiffusionTrainingFacts, and FamilyFacts renders+ # vram_note only when there are NO chips. So a blocked host that still published base_specs+ # would put the 9B / 18 GB chips back the moment Klein base-9B is selected, and swap the+ # actionable reason (no CUDA, no native bf16) for a size the user cannot act on. Clearing the+ # family chips is not enough on a family whose bases carry their own.+ from core.training.diffusion_train_common import _DIT_TRAIN_FAMILIES, family_train_infos++ unblocked = {info["name"]: info for info in family_train_infos()}+ # At least one DiT family must ship a per-base overlay, or this asserts nothing.+ assert any(unblocked[n]["base_specs"] for n in _DIT_TRAIN_FAMILIES if n in unblocked)++ monkeypatch.setattr(common, "bf16_unsupported_reason", lambda name: "no bfloat16 on this GPU")+ for name, info in (+ (n, i)+ for n, i in ((i["name"], i) for i in family_train_infos())+ if n in _DIT_TRAIN_FAMILIES+ ):+ assert info["base_specs"] == {}, name+ # The reason survives, which is the whole point of dropping the chips.+ assert info["vram_note"] == "no bfloat16 on this GPU", name++def test_base_precision_gates_skip_sdxl():# SDXL ignores base_precision, so the dense-mode gates must not fire for it even on a prequant-looking name.norm = _cfg(base_model = _SDXL_PREQUANT_NAME, base_precision = "bf16").normalized()@@ -365,6 +414,38 @@ def test_resolve_auto_int8_band_gates_on_torchao(monkeypatch):assert dit._resolve_base_precision(cfg, spec, "cuda") == "int8"+def test_resolve_auto_uses_klein_variant_size(monkeypatch):+ import torch++ spec = dit._SPECS["flux.2-klein"]++ class _FakeCuda:+ @staticmethod+ def mem_get_info():+ return (int(20 * 1e9), int(24 * 1e9))++ @staticmethod+ def get_device_capability():+ return (10, 0)++ monkeypatch.setattr(torch, "cuda", _FakeCuda)+ monkeypatch.setattr(dit, "has_functional_torchao", lambda: True)++ four_b = _cfg(+ base_model = "black-forest-labs/FLUX.2-klein-base-4B",+ base_precision = "auto",+ mixed_precision = "bf16",+ )+ nine_b = _cfg(+ base_model = "unsloth/FLUX.2-klein-base-9B",+ base_precision = "auto",+ mixed_precision = "bf16",+ )++ assert dit._resolve_base_precision(four_b, spec, "cuda") == "bf16"+ assert dit._resolve_base_precision(nine_b, spec, "cuda") == "nf4"++def test_resolve_auto_int8_band_treats_stub_as_absent(monkeypatch):# Simulate the Windows-ROCm torchao STUB (find_spec succeeds but quantize_ is a no-op), so the int8 band must fall to nf4.import torchdiff --git a/studio/backend/tests/test_diffusion_checkpoint_resume.py b/studio/backend/tests/test_diffusion_checkpoint_resume.pyindex 6177fc765cd..f5949bd5216 100644--- a/studio/backend/tests/test_diffusion_checkpoint_resume.py+++ b/studio/backend/tests/test_diffusion_checkpoint_resume.py@@ -2362,6 +2362,71 @@ def test_the_revision_is_pinned_once_the_base_is_on_disk(monkeypatch, run_dir):assert dc.with_resolved_revision(unresolved, cfg.base_model).base_revision == "unresolved"+def test_a_mirror_backed_run_pairs_the_revision_with_the_repo_it_came_from(monkeypatch, run_dir):+ """The revision follows the FETCHED repo, and carries which repo that was.++ Both single-value shapes are wrong. Recording the canonical repo loses the check+ completely, because the mirror is selected precisely WHEN the canonical repo is not+ cached, so it has no local ref and every mirror-backed bundle reads "unresolved" --+ which ``mismatch_reason`` skips, so a mirror that advanced under a resume goes+ unnoticed. Recording the mirror alone refuses byte-identical weights the moment the+ fetch repo changes, and refuses every bundle written before mirrors existed.++ Pairing the two keeps the comparison wherever it can be made and drops it only where+ it genuinely cannot.+ """+ import dataclasses++ from core.training import diffusion_train_extras as dte++ source = "black-forest-labs/FLUX.2-klein-base-9B"+ mirror = "unsloth/FLUX.2-klein-base-9B"+ base = dataclasses.replace(_Run(run_dir).cfg, base_model = source, resolved_family = "flux.2-klein")+ seen = []++ def _revision(ref):+ seen.append(ref)+ # The real-world shape: the canonical repo is NOT cached, which is what selected the+ # mirror in the first place, so only the mirror resolves to a commit.+ return "rev-mirror111" if ref == mirror else "unresolved"++ monkeypatch.setattr(dte, "source_revision", _revision)+ via_mirror = dc.identity_for_config(dataclasses.replace(base, fetch_base_model = mirror))++ # The canonical id is what the run is ABOUT; only the revision pair follows the fetch.+ assert via_mirror.base_model == source+ assert seen == [mirror]+ assert via_mirror.base_revision == "rev-mirror111"+ assert via_mirror.base_revision_repo == mirror++ # 1. The check this exists for: the mirror advanced under a resume. Recording the+ # canonical repo made both sides "unresolved" and this went undetected.+ moved = dataclasses.replace(via_mirror, base_revision = "rev-mirror222")+ reason = via_mirror.mismatch_reason(moved)+ assert reason and "base model revision" in reason++ # 2. And the refusal that must NOT happen: the same weights fetched from the other repo.+ direct = dataclasses.replace(+ via_mirror, base_revision = "rev-canonical1", base_revision_repo = source+ )+ assert via_mirror.mismatch_reason(direct) is None+ assert direct.mismatch_reason(via_mirror) is None++ # 3. A bundle written before the field existed read the canonical repo, so it stays+ # comparable with a new canonical-fetched one rather than silently opting out.+ legacy = dataclasses.replace(+ via_mirror, base_revision = "rev-canonical9", base_revision_repo = None+ )+ legacy_reason = legacy.mismatch_reason(direct)+ assert legacy_reason and "base model revision" in legacy_reason++ # 4. And it survives a manifest round trip, or the pairing is lost on reload.+ reloaded = dc.CheckpointIdentity.from_dict(via_mirror.as_dict())+ assert reloaded is not None+ assert reloaded.base_revision_repo == mirror+ assert reloaded.mismatch_reason(moved) is not None++def test_both_trainers_pin_the_revision_after_the_load():"""Source-ordered: the loop needs a GPU, so this asserts the call sits after the load eventand before the restore that validates against it."""diff --git a/studio/backend/tests/test_diffusion_dit_trainer.py b/studio/backend/tests/test_diffusion_dit_trainer.pyindex 546627f0df0..eda4c7ffbe6 100644--- a/studio/backend/tests/test_diffusion_dit_trainer.py+++ b/studio/backend/tests/test_diffusion_dit_trainer.py@@ -15,7 +15,8 @@ import typesimport pytestfrom core.training.diffusion_dit_trainer import (- _FLUX2_TARGETS,+ _FLUX2_DEV_TARGETS,+ _FLUX2_KLEIN_TARGETS,_FLUX_TARGETS,_GATED_TRAIN_REPOS,_QWEN_TARGETS,@@ -63,13 +64,16 @@ def test_specs_cover_the_dit_families():def test_flux2_specs_share_targets_and_split_conditioners():- # dev and Klein share the transformer (so the LoRA target set) but load different conditioning pipelines and save through their own class.+ # dev and Klein share the transformer class but have different single-block counts.klein, dev = _SPECS["flux.2-klein"], _SPECS["flux.2-dev"]- assert klein.lora_targets == dev.lora_targets == _FLUX2_TARGETS- # The fused single-stream projection is targeted; the plain to_out suffix is not (it also matches the double-stream ModuleList, which peft cannot wrap).- assert "to_qkv_mlp_proj" in _FLUX2_TARGETS- assert "to_out.0" in _FLUX2_TARGETS- assert "to_out" not in _FLUX2_TARGETS+ assert klein.lora_targets == _FLUX2_KLEIN_TARGETS+ assert dev.lora_targets == _FLUX2_DEV_TARGETS+ # The upstream trainers pair the fused input with every plain single-stream output projection.+ assert "to_qkv_mlp_proj" in _FLUX2_KLEIN_TARGETS+ assert "to_out.0" in _FLUX2_KLEIN_TARGETS+ assert "single_transformer_blocks.23.attn.to_out" in _FLUX2_KLEIN_TARGETS+ assert "single_transformer_blocks.24.attn.to_out" not in _FLUX2_KLEIN_TARGETS+ assert "single_transformer_blocks.47.attn.to_out" in _FLUX2_DEV_TARGETSassert klein.load_conditioners is not dev.load_conditionersassert klein.save is not dev.saveassert klein.load_transformer is dev.load_transformer@@ -151,6 +155,8 @@ def test_flux2_bases_pass_the_trusted_base_gate():# The FLUX.2 bases are training-side additions to the loader's trust allowlist, so the pre-download trust gate must accept them.from core.training.diffusion_train_common import _assert_trusted_base_model+ _assert_trusted_base_model("black-forest-labs/FLUX.2-klein-base-4B")+ _assert_trusted_base_model("black-forest-labs/FLUX.2-klein-base-9B")_assert_trusted_base_model("black-forest-labs/FLUX.2-klein-4B")_assert_trusted_base_model("black-forest-labs/FLUX.2-dev")with pytest.raises(ValueError, match = "untrusted"):@@ -190,7 +196,7 @@ def test_every_train_base_is_deployable_as_an_inference_pipeline():if not fam.trainable:continuefor base in fam.train_base_repos:- deploy_base = fam.deploy_base_repo or base+ deploy_base = fam.deploy_base_for(base)assert _is_trusted_diffusion_repo(deploy_base), f"{fam.name}: deploy base {deploy_base!r} is not loadable for inference"@@ -213,6 +219,63 @@ def test_gated_access_requires_token():_assert_gated_access("black-forest-labs/FLUX.2-klein-4B", None) # Klein is open+def test_the_gate_lets_a_local_clone_named_like_a_gated_repo_through(monkeypatch, tmp_path):+ """A directory on disk carries no gate, whatever it is called.++ A base can be a relative clone named exactly like the vendor repo, which the loaders and the+ token-less mirror override both resolve on disk. Matching \`_GATED_TRAIN_REPOS\` by name alone+ refused that layout without a token, for weights the run never fetches.+ """+ local = "black-forest-labs/FLUX.1-dev"+ assert local.lower() in _GATED_TRAIN_REPOS, "precondition: the name is gated"+ monkeypatch.chdir(tmp_path)+ (tmp_path / local).mkdir(parents = True)++ _assert_gated_access(local, None)+++def test_the_gate_reads_the_repo_the_run_will_fetch(monkeypatch, tmp_path):+ """A gated base redirected to its ungated mirror must not be refused by name.++ The start route preflights the FETCH repo, so a child that checked the canonical id+ would raise for a request the route had already answered 200 to, after freeing the+ resident models: a dead job instead of a fast 400.+ """+ from core.inference import diffusion_families++ seen: list[str] = []+ monkeypatch.setattr(+ "core.training.diffusion_dit_trainer._assert_gated_access",+ lambda base, token: seen.append(base),+ )+ monkeypatch.setattr(+ diffusion_families,+ "prefer_ungated_mirror",+ lambda base, token = None: "unsloth/FLUX.1-dev"+ if base.lower() == "black-forest-labs/flux.1-dev"+ else base,+ )+ cfg = DiffusionLoraConfig(+ base_model = "black-forest-labs/FLUX.1-dev",+ data_dir = str(tmp_path / "empty"), # the next step after the gate, so it stops here+ output_dir = str(tmp_path / "out"),+ )+ with pytest.raises(Exception): # noqa: B017, PT011 -- the dataset, not the gate+ run_dit_lora_training(cfg)+ assert seen == ["unsloth/FLUX.1-dev"]++ # Control: with no mirror at all the canonical id is still what gets checked, so a+ # genuinely gated fetch without a token keeps failing here rather than mid-download.+ # mirror_repo has to go too: a token-less run overrides the cache preference on any repo+ # the mirror table covers, so stubbing only the preference would still redirect.+ seen.clear()+ monkeypatch.setattr(diffusion_families, "prefer_ungated_mirror", lambda base, token = None: base)+ monkeypatch.setattr(diffusion_families, "mirror_repo", lambda base: None)+ with pytest.raises(Exception): # noqa: B017, PT011+ run_dit_lora_training(cfg)+ assert seen == ["black-forest-labs/FLUX.1-dev"]++def test_family_train_infos_lists_dit_families(dit_train_host):infos = {i["name"]: i for i in family_train_infos()}for fam in ("sdxl", "flux.1", "qwen-image", "z-image", "flux.2-klein", "flux.2-dev"):@@ -225,8 +288,29 @@ def test_family_train_infos_lists_dit_families(dit_train_host):assert "gated" in infos["flux.1"]["vram_note"].lower()assert infos["flux.2-dev"]["default_base"] == "black-forest-labs/FLUX.2-dev"assert "gated" in infos["flux.2-dev"]["vram_note"].lower()- # Klein-4B is open.- assert infos["flux.2-klein"]["default_base"] == "black-forest-labs/FLUX.2-klein-4B"+ # Klein trains on the undistilled bases and deploys each size on its distilled partner.+ klein = infos["flux.2-klein"]+ assert klein["default_base"] == "black-forest-labs/FLUX.2-klein-base-4B"+ assert klein["base_repos"] == [+ "black-forest-labs/FLUX.2-klein-base-4B",+ "black-forest-labs/FLUX.2-klein-base-9B",+ ]+ assert klein["deploy_bases"]["black-forest-labs/FLUX.2-klein-base-4B"] == (+ "black-forest-labs/FLUX.2-klein-4B"+ )+ assert klein["deploy_bases"]["black-forest-labs/FLUX.2-klein-base-9B"] == (+ "black-forest-labs/FLUX.2-klein-9B"+ )+ assert klein["deploy_bases"]["unsloth/FLUX.2-klein-base-9B"] == ("unsloth/FLUX.2-klein-9B")+ assert klein["base_specs"]["black-forest-labs/FLUX.2-klein-base-9B"] == {+ "params": "9B",+ "qlora_vram_gb": 18,+ }+ assert klein["base_specs"]["unsloth/FLUX.2-klein-base-9B"] == {+ "params": "9B",+ "qlora_vram_gb": 18,+ }+ assert "black-forest-labs/FLUX.2-klein-base-4B" not in klein["base_specs"]assert "gated" not in infos["flux.2-klein"]["vram_note"].lower()# Z-Image defaults to the prequant nf4 repo for QLoRA.assert "4bit" in infos["z-image"]["default_base"].lower()diff --git a/studio/backend/tests/test_diffusion_more_families.py b/studio/backend/tests/test_diffusion_more_families.pyindex 29e06b25a0e..c5b59c13fe8 100644--- a/studio/backend/tests/test_diffusion_more_families.py+++ b/studio/backend/tests/test_diffusion_more_families.py@@ -84,6 +84,12 @@ def test_flux1_krea_dev_generation_defaults():assert default_generation_params("krea/Krea-2-Raw") == (52, 3.5)+def test_flux2_klein_generation_defaults_distinguish_base_from_distilled():+ for size in ("4B", "9B"):+ assert default_generation_params(f"unsloth/FLUX.2-klein-base-{size}") == (50, 4.0)+ assert default_generation_params(f"unsloth/FLUX.2-klein-{size}") == (4, 1.0)++# ── z-image: the undistilled base ────────────────────────────────────────────def test_zimage_base_is_trusted_so_the_gguf_keeps_its_companion_base():# unsloth/Z-Image-GGUF carries base_model: Tongyi-MAI/Z-Image, and _resolve_base_repo drops adiff --git a/studio/backend/tests/test_diffusion_training.py b/studio/backend/tests/test_diffusion_training.pyindex 61057ad39dd..635e09bf772 100644--- a/studio/backend/tests/test_diffusion_training.py+++ b/studio/backend/tests/test_diffusion_training.py@@ -589,6 +589,167 @@ def test_route_start_preflights_gated_base_off_the_coroutine_thread(client, monkassert threads["preflight"] is not threads["inline"] # offloaded to a worker, not run inline+ ("hf_token", "authorization"),+ [(None, None), (" hf_test ", "Bearer hf_test")],+)+def test_route_start_preflights_the_normalized_fetch_mirror(+ client, monkeypatch, dit_train_host, healthy_diffusers, hf_token, authorization+):+ import urllib.error+ import urllib.request++ from core.inference import diffusion_families++ source = "black-forest-labs/FLUX.2-klein-base-9B"+ mirror = "unsloth/FLUX.2-klein-base-9B"+ monkeypatch.setattr(+ diffusion_families,+ "prefer_ungated_mirror",+ lambda base, token = None: mirror if base.lower() == source.lower() else base,+ )+ requests = []++ def _fake_urlopen(req, timeout = None):+ requests.append(req)+ if source in req.full_url:+ raise urllib.error.HTTPError(req.full_url, 401, "Unauthorized", {}, None)+ assert mirror in req.full_url+ return object()++ monkeypatch.setattr(urllib.request, "urlopen", _fake_urlopen)+ r = client.post(+ "/api/train/diffusion/start",+ json = {**_BODY, "base_model": source, "hf_token": hf_token},+ )++ assert r.status_code == 200, r.text+ assert len(requests) == 1+ assert requests[0].get_header("Authorization") == authorization+ # The fetch-only mirror must not replace the canonical id persisted with the run.+ assert client._fake.started_with["base_model"] == source++[email protected]("no_mirror_env", [False, True])+def test_a_tokenless_run_takes_the_mirror_even_with_the_vendor_repo_cached(+ monkeypatch, no_mirror_env+):+ """Cache preference must not strand a token-less run on a GATED vendor repo.++ The credentials this run lacks are the credentials the fetch needs, so the cached snapshot+ is unusable however complete it looks. prefer_ungated_mirror's probe counts ANY cached+ weight as a hit, so one leftover shard from an interrupted or previously authorized download+ kept the vendor id, and the start route's HEAD then refused the request outright: the exact+ case the mirrors exist for became the one that could not train.+ """+ from core.inference import diffusion_families+ from core.training.diffusion_train_common import DiffusionLoraConfig++ source = "black-forest-labs/FLUX.1-dev"+ mirror = "unsloth/FLUX.1-dev"+ # The vendor repo looks cached, which is what made the old code keep it.+ monkeypatch.setattr(diffusion_families, "prefer_ungated_mirror", lambda base, token = None: base)+ if no_mirror_env:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")+ else:+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)++ def _cfg(token):+ return DiffusionLoraConfig(+ base_model = source, data_dir = "d", output_dir = "o", hf_token = token+ ).normalized()++ # The documented pin still wins, on this path as everywhere else.+ expected = source if no_mirror_env else mirror+ assert _cfg(None).fetch_base_model == expected+ assert _cfg(" ").fetch_base_model == expected+ # WITH a token the vendor repo is genuinely usable, so the cache preference stands.+ assert _cfg("hf_realtoken").fetch_base_model == source+ # And the canonical id is untouched either way: only the fetch moves.+ assert _cfg(None).base_model == source++[email protected]("no_mirror_env", [False, True])+def test_a_tokenless_run_keeps_a_cached_ungated_base(monkeypatch, no_mirror_env):+ """The override is for gates, not for mirrors in general.++ Most of the mirror table is ungated: those exist to keep the fetch inside unsloth/*, and the+ upstream answers anonymously. Overriding the cache preference there would throw away a+ complete local snapshot and re-pull gigabytes, or fail outright with no network. Klein base-4B+ is the one that matters most here, since it is a default trainable base AND mirrored.+ """+ from core.inference import diffusion_families+ from core.training.diffusion_train_common import DiffusionLoraConfig++ source = "black-forest-labs/FLUX.2-klein-base-4B"+ assert diffusion_families.mirror_repo(source), "precondition: this base is mirrored"+ assert not diffusion_families.upstream_is_gated(source), "precondition: and it is ungated"+ # Cached, so the cache-aware answer is the vendor repo. It must survive.+ monkeypatch.setattr(diffusion_families, "prefer_ungated_mirror", lambda base, token = None: base)+ if no_mirror_env:+ monkeypatch.setenv("UNSLOTH_DIFFUSION_NO_MIRROR", "1")+ else:+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)++ def _cfg(token):+ return DiffusionLoraConfig(+ base_model = source, data_dir = "d", output_dir = "o", hf_token = token+ ).normalized()++ assert _cfg(None).fetch_base_model == source+ assert _cfg(" ").fetch_base_model == source+ assert _cfg("hf_realtoken").fetch_base_model == source+++def test_the_start_preflight_never_heads_the_hub_for_a_local_clone(monkeypatch, tmp_path):+ """The preflight has to make the same exception the mirror override does.++ A relative clone named like the vendor repo has one slash and no leading marker, so the+ remote/local split by string shape alone sent it to a token-less HEAD of the gated repo and+ turned the preserved local path into a 400 the run could not clear.+ """+ import urllib.request++ from routes.training import _preflight_gated_base++ local = "black-forest-labs/FLUX.1-dev"+ monkeypatch.chdir(tmp_path)+ (tmp_path / local).mkdir(parents = True)++ def _explode(*a, **k):+ pytest.fail("a local clone must never be probed over the network")++ monkeypatch.setattr(urllib.request, "urlopen", _explode)++ _preflight_gated_base(local, None)+++def test_a_tokenless_run_keeps_a_local_clone_named_like_a_gated_base(monkeypatch, tmp_path):+ """A directory on disk is not a Hub id, even when it is spelled like a gated one.++ The loaders resolve a relative `black-forest-labs/FLUX.1-dev` directory locally, and+ prefer_ungated_mirror carves that out deliberately. The token-less gated override has to+ make the same exception: rewriting a local clone to the mirror sends the fetch to the Hub+ past the weights the user already has, so the run trains on a different repo or fails+ outright with no network.+ """+ from core.inference import diffusion_families+ from core.training.diffusion_train_common import DiffusionLoraConfig++ source = "black-forest-labs/FLUX.1-dev"+ assert diffusion_families.upstream_is_gated(source), "precondition: this base is gated"+ monkeypatch.chdir(tmp_path)+ (tmp_path / source).mkdir(parents = True)+ monkeypatch.delenv("UNSLOTH_DIFFUSION_NO_MIRROR", raising = False)++ cfg = DiffusionLoraConfig(+ base_model = source, data_dir = "d", output_dir = "o", hf_token = None+ ).normalized()++ assert cfg.fetch_base_model == source+ assert cfg.base_model == source++def test_route_start_forwards_extra_training_knobs(client):# max_grad_norm and lora_target_modules must reach the service, not be silently dropped.body = {**_BODY, "max_grad_norm": 0.5, "lora_target_modules": ["to_q", "to_v"]}diff --git a/studio/backend/tests/test_openai_images_generations_route.py b/studio/backend/tests/test_openai_images_generations_route.pyindex 916fc3d8aaf..6c470469316 100644--- a/studio/backend/tests/test_openai_images_generations_route.py+++ b/studio/backend/tests/test_openai_images_generations_route.py@@ -34,7 +34,7 @@ from utils.api_errors import install_api_error_handlers("unsloth/Z-Image-GGUF", (20, 4.0)),("unsloth/FLUX.1-schnell-GGUF", (4, 0.0)), # schnell entry, before the flux.1 entry("black-forest-labs/FLUX.1-dev", (28, 3.5)),- ("unsloth/FLUX.2-klein-4B-GGUF", (4, 0.0)),+ ("unsloth/FLUX.2-klein-4B-GGUF", (4, 1.0)),("unsloth/Qwen-Image-2512-GGUF", (20, 4.0)),("some/unknown-model", (9, 0.0)), # fallback("", (9, 0.0)),diff --git a/studio/frontend/src/features/images/api.ts b/studio/frontend/src/features/images/api.tsindex 0a4567f43ef..e152a0e1f8d 100644--- a/studio/frontend/src/features/images/api.ts+++ b/studio/frontend/src/features/images/api.ts@@ -643,6 +643,18 @@ export interface DiffusionTrainableFamily {supports_compile?: boolean;// When set, deploying a LoRA trained on this family previews it on this repo instead of the checkpoint it trained on (Krea trains on Raw, runs on Turbo).deploy_base?: string | null;+ // Variant-specific training-base to inference-base pairs, including public mirror ids.+ deploy_bases?: Record<string, string>;+ // Per-checkpoint facts that overlay the family-level chips for multi-size families.+ base_specs?: Record<+ string,+ {+ params?: string | null;+ qlora_vram_gb?: number | null;+ gated?: boolean | null;+ note?: string | null;+ }+ >;}// Where diffusion training reads/writes on this Studio, plus usable dataset folders.diff --git a/studio/frontend/src/features/images/image-generation-defaults.ts b/studio/frontend/src/features/images/image-generation-defaults.tsnew file mode 100644index 00000000000..24ec13382a7--- /dev/null+++ b/studio/frontend/src/features/images/image-generation-defaults.ts@@ -0,0 +1,47 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Generation defaults when the model is unrecognised. Also seeds the Create sliders.+export const DEFAULT_GEN = { steps: 9, guidance: 0 };++const MODEL_DEFAULTS: Array<{+ match: string;+ steps: number;+ guidance: number;+}> = [+ { match: "z-image-turbo", steps: 9, guidance: 0 },+ // Krea 2 Raw is the undistilled base, so it must precede the distilled Krea key below.+ { match: "krea-2-raw", steps: 52, guidance: 3.5 },+ { match: "krea-2", steps: 8, guidance: 0 },+ { match: "flux.1-schnell", steps: 4, guidance: 0 },+ // Kontext and the Krea dev finetune must precede generic FLUX.1.+ { match: "kontext", steps: 28, guidance: 2.5 },+ { match: "flux.1-krea", steps: 28, guidance: 4.5 },+ { match: "flux.1", steps: 28, guidance: 3.5 },+ // Klein base is undistilled. The generic key below covers both distilled sizes.+ { match: "flux.2-klein-base", steps: 50, guidance: 4 },+ { match: "flux.2-klein", steps: 4, guidance: 1 },+ { match: "flux.2-dev", steps: 28, guidance: 4 },+ { match: "qwen-image", steps: 20, guidance: 4 },+ { match: "z-image", steps: 20, guidance: 4 },+ { match: "ideogram", steps: 48, guidance: 7 },+ { match: "lumina", steps: 50, guidance: 4 },+ { match: "hunyuanimage", steps: 50, guidance: 3.25 },+ { match: "hidream-i1-dev", steps: 28, guidance: 0 },+ { match: "hidream-i1-fast", steps: 16, guidance: 0 },+ { match: "hidream", steps: 50, guidance: 5 },+ { match: "sdxl-turbo", steps: 3, guidance: 0 },+ { match: "stable-diffusion-xl", steps: 30, guidance: 7 },+ { match: "sdxl", steps: 30, guidance: 7 },+];++export function defaultsFor(repoId: string): {+ steps: number;+ guidance: number;+} {+ const id = repoId.toLowerCase();+ const matched = MODEL_DEFAULTS.find((entry) => id.includes(entry.match));+ return matched+ ? { steps: matched.steps, guidance: matched.guidance }+ : DEFAULT_GEN;+}diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex b8e6aba04ee..62402843916 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -97,6 +97,7 @@ import {} from "@/lib/diffusion-route-search";import { toast } from "@/lib/toast";import { subscribeModelEjected } from "@/lib/model-lifecycle-events";+import { DEFAULT_GEN, defaultsFor } from "./image-generation-defaults";import {type ControlNetSpecInput,@@ -151,48 +152,6 @@ const CONDITIONED_WORKFLOW_INPUTS: Record<string, string> = {controlnet: "the control image",};-// Generation defaults when the model is unrecognised: the distilled few-step / no-CFG shape. Also seeds the sliders.-const DEFAULT_GEN = { steps: 9, guidance: 0 };--const MODEL_DEFAULTS: Array<{ match: string; steps: number; guidance: number }> = [- { match: "z-image-turbo", steps: 9, guidance: 0 },- // Krea 2 Raw is the undistilled base: 52 steps at guidance 3.5, so it must precede the distilled "krea-2" key below.- { match: "krea-2-raw", steps: 52, guidance: 3.5 },- // Krea 2 Turbo is distilled (TDM): 8 steps, no CFG. "krea-2" covers Turbo and any other krea id but Raw, matched above.- { match: "krea-2", steps: 8, guidance: 0 },- { match: "flux.1-schnell", steps: 4, guidance: 0 },- // Kontext (editing) before the generic flux.1: ~28 steps, lower guidance (~2.5).- { match: "kontext", steps: 28, guidance: 2.5 },- // Krea FLUX.1-dev finetune runs its card recipe (28 steps, guidance 4.5); before the generic flux.1 key.- { match: "flux.1-krea", steps: 28, guidance: 4.5 },- { match: "flux.1", steps: 28, guidance: 3.5 },- { match: "flux.2-klein", steps: 4, guidance: 0 },- // FLUX.2-dev is the full (non-distilled) model: more steps + real guidance, unlike klein.- { match: "flux.2-dev", steps: 28, guidance: 4 },- { match: "qwen-image", steps: 20, guidance: 4 },- { match: "z-image", steps: 20, guidance: 4 },- // Ideogram 4 card settings (48 steps, guidance 7). At exactly these the backend keeps its tapered guidance schedule.- { match: "ideogram", steps: 48, guidance: 7 },- // Lumina Image 2.0 model-card recipe (the backend adds cfg_trunc_ratio itself).- { match: "lumina", steps: 50, guidance: 4 },- // HunyuanImage 2.1: 50 steps; guidance feeds distilled_guidance_scale, real CFG runs in the repo guiders.- { match: "hunyuanimage", steps: 50, guidance: 3.25 },- // HiDream-I1: Full runs 50 steps at guidance 5; the Dev/Fast distillations are guidance-free.- { match: "hidream-i1-dev", steps: 28, guidance: 0 },- { match: "hidream-i1-fast", steps: 16, guidance: 0 },- { match: "hidream", steps: 50, guidance: 5 },- // SDXL: Turbo is distilled (few steps, no CFG), base wants ~30 steps and CFG ~7; "sdxl-turbo" precedes "sdxl".- { match: "sdxl-turbo", steps: 3, guidance: 0 },- { match: "stable-diffusion-xl", steps: 30, guidance: 7 },- { match: "sdxl", steps: 30, guidance: 7 },-];--function defaultsFor(repoId: string): { steps: number; guidance: number } {- const id = repoId.toLowerCase();- // The fallback is only hit for an unrecognised on-device image GGUF; a curated entry covers every model in MODELS.- return MODEL_DEFAULTS.find((d) => id.includes(d.match)) ?? DEFAULT_GEN;-}-// Common aspect ratios (landscape; Flip mirrors to portrait). Picking one locks the W:H proportion; the sliders set the size.const ASPECT_RATIOS: Record<string, [number, number]> = {"1:1": [1, 1],diff --git a/studio/frontend/src/features/images/train/diffusion-train-deploy.ts b/studio/frontend/src/features/images/train/diffusion-train-deploy.tsnew file mode 100644index 00000000000..d2addad94d5--- /dev/null+++ b/studio/frontend/src/features/images/train/diffusion-train-deploy.ts@@ -0,0 +1,68 @@+// 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 { DiffusionTrainableFamily } from "../api";++function normalizedRepo(repo: string): string {+ return repo.trim().toLowerCase();+}++/** Resolve the inference checkpoint paired with the base a diffusion adapter trained on. */+export function resolveDiffusionDeployBase(+ family: DiffusionTrainableFamily | undefined,+ trainedBase: string,+): string {+ const key = normalizedRepo(trainedBase);+ const variant = Object.entries(family?.deploy_bases ?? {}).find(+ ([trainingRepo]) => normalizedRepo(trainingRepo) === key,+ );+ if (variant) return variant[1];++ // Backward-compatible family-wide mapping used by Krea 2 and older backends.+ if (+ family?.deploy_base &&+ family.base_repos.some((repo) => normalizedRepo(repo) === key)+ ) {+ return family.deploy_base;+ }+ return trainedBase;+}++/**+ * The TRAINING base paired with a checkpoint that is currently loaded for inference, or null.+ *+ * The inverse of the mapping above, and it is what the Train panel needs to preselect: the+ * distilled variants a user generates with are not trainable, so a loaded `...klein-9B` never+ * appears in `base_repos` and an exact-match preselect silently falls through to the FIRST entry.+ * For FLUX.2 Klein that is the 4B base, so opening Train with the 9B model loaded started a 9B+ * workflow from 4B weights unless the user noticed the selector.+ *+ * Only a pairing the family actually declares is returned, and only when the paired training repo+ * is offered, so this can never invent a base the backend would refuse.+ */+export function resolveDiffusionTrainingBase(+ family: DiffusionTrainableFamily | undefined,+ loadedBase: string,+): string | null {+ const key = normalizedRepo(loadedBase);+ if (!family || !key) return null;+ const pair = Object.entries(family.deploy_bases ?? {}).find(+ ([, inferenceRepo]) => normalizedRepo(inferenceRepo) === key,+ );+ const trainingRepo = pair?.[0];+ if (!trainingRepo) return null;+ const exact = family.base_repos.find(+ (repo) => normalizedRepo(repo) === normalizedRepo(trainingRepo),+ );+ if (exact) return exact;+ // A checkpoint loaded from the ungated MIRROR pairs with the mirror training id, and+ // /diffusion/info offers only the vendor ids, so the exact match above finds nothing and the+ // panel falls back to the first base -- for Klein the 4B, which is the very mix-up this+ // function exists to prevent, reached through Deploy's own mirror pairing. A mirror keeps the+ // upstream repo NAME, so fold to that; still only ever returning a base the backend offers.+ const name = normalizedRepo(trainingRepo.split("/").pop() ?? "");+ if (!name) return null;+ return (+ family.base_repos.find((repo) => normalizedRepo(repo.split("/").pop() ?? "") === name) ?? null+ );+}diff --git a/studio/frontend/src/features/images/train/diffusion-train-family-facts.ts b/studio/frontend/src/features/images/train/diffusion-train-family-facts.tsnew file mode 100644index 00000000000..bf82dbbd85a--- /dev/null+++ b/studio/frontend/src/features/images/train/diffusion-train-family-facts.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export type DiffusionTrainingFacts = {+ params?: string | null;+ qlora_vram_gb?: number | null;+ gated?: boolean | null;+ note?: string | null;+};++type FamilyWithBaseFacts = DiffusionTrainingFacts & {+ base_specs?: Record<string, DiffusionTrainingFacts>;+};++/** Resolve the chips for the selected checkpoint, falling back to its family facts. */+export function resolveDiffusionTrainingFacts(+ family: FamilyWithBaseFacts,+ baseModel?: string | null,+): DiffusionTrainingFacts {+ const wanted = (baseModel ?? "").trim().toLowerCase();+ const override = Object.entries(family.base_specs ?? {}).find(+ ([repo]) => repo.trim().toLowerCase() === wanted,+ )?.[1];+ if (!override) return family;+ return {+ params: override.params ?? family.params,+ qlora_vram_gb: override.qlora_vram_gb ?? family.qlora_vram_gb,+ gated: override.gated ?? family.gated,+ note: override.note ?? family.note,+ };+}diff --git a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx b/studio/frontend/src/features/images/train/diffusion-train-panel.tsxindex 7caa9d494a7..ec32fb47476 100644--- a/studio/frontend/src/features/images/train/diffusion-train-panel.tsx+++ b/studio/frontend/src/features/images/train/diffusion-train-panel.tsx@@ -101,6 +101,11 @@ import {buildDiffusionResumePayload,resumeActionLabel,} from "./resume-diffusion-run";+import {+ resolveDiffusionDeployBase,+ resolveDiffusionTrainingBase,+} from "./diffusion-train-deploy";+import { resolveDiffusionTrainingFacts } from "./diffusion-train-family-facts";// The families the Train tab can train, in popularity order; a fallback for an older backend whose /info reports none.type FamilyPreset = {@@ -114,6 +119,7 @@ type FamilyPreset = {params?: string;qlora_vram_gb?: number | null;note?: string;+ base_specs?: DiffusionTrainableFamily["base_specs"];};const FAMILY_PRESETS: FamilyPreset[] = [@@ -245,11 +251,10 @@ function FieldLabel({/** The family's training facts as chips: size, QLoRA VRAM floor, access. What a chip cannot* carry stays as a line below, as does the prose from a backend too old to send the fields. */-function FamilyFacts({ family }: { family?: FamilyPreset }) {+function FamilyFacts({ family, baseModel }: { family?: FamilyPreset; baseModel?: string }) {if (!family) return null;- const hasChips = Boolean(- family.params || family.qlora_vram_gb || family.gated,- );+ const facts = resolveDiffusionTrainingFacts(family, baseModel);+ const hasChips = Boolean(facts.params || facts.qlora_vram_gb || facts.gated);if (!hasChips) {return family.vram_note ? (<p className="text-ui-11 leading-snug text-muted-foreground">@@ -260,18 +265,18 @@ function FamilyFacts({ family }: { family?: FamilyPreset }) {return (<div className="flex flex-col gap-1.5"><div className="flex flex-wrap items-center gap-1.5">- {family.params ? (+ {facts.params ? (<Badge variant="secondary" className="font-normal">- {family.params}+ {facts.params}</Badge>) : null}- {family.qlora_vram_gb != null ? (+ {facts.qlora_vram_gb != null ? (<Badge variant="secondary" className="font-normal">- QLoRA {family.qlora_vram_gb}GB+ VRAM+ QLoRA {facts.qlora_vram_gb}GB+ VRAM</Badge>) : null}{/* Access, not a spec: a neutral fill sets it apart from the capability chips. */}- {family.gated ? (+ {facts.gated ? (<Badgevariant="secondary"className="bg-muted font-normal text-muted-foreground"@@ -280,11 +285,11 @@ function FamilyFacts({ family }: { family?: FamilyPreset }) {</Badge>) : null}</div>- {(family.gated || family.note) && (+ {(facts.gated || facts.note) && (<p className="text-ui-11 leading-snug text-muted-foreground">- {family.gated ? "Needs its license and your HF token." : null}- {family.gated && family.note ? " " : null}- {family.note}+ {facts.gated ? "Needs its license and your HF token." : null}+ {facts.gated && facts.note ? " " : null}+ {facts.note}</p>)}</div>@@ -310,6 +315,7 @@ function mergeFamilies(reported?: DiffusionTrainableFamily[]): FamilyPreset[] {},vram_note: r.vram_note || p.vram_note,gated: r.gated ?? p.gated,+ base_specs: r.base_specs,// The chips travel together: a backend reporting any of them owns the whole set, so a// preset value cannot sit beside a live one describing a different build....(r.params != null || r.qlora_vram_gb != null || r.note != null@@ -337,6 +343,7 @@ function mergeFamilies(reported?: DiffusionTrainableFamily[]): FamilyPreset[] {params: r.params ?? "",qlora_vram_gb: r.qlora_vram_gb ?? null,note: r.note ?? "",+ base_specs: r.base_specs,});}return merged;@@ -584,11 +591,20 @@ export function DiffusionTrainPanel({baseDirty.current = false;}// An already-valid base wins: the top bar sets family and base together, so this must not snap back to the family's first repo.+ // A loaded checkpoint may be the DISTILLED half of a pair, which is not trainable and so is+ // never in base_repos. Fall back to the training base the family pairs it with before+ // dropping to base_repos[0], or opening Train with the 9B model loaded seeds the 4B base.+ // reportedFamily, not family: the pairing lives in deploy_bases, which only the backend+ // reports. The static presets have no pairings, so an older backend simply keeps today's+ // behaviour here.+ const pairedTrainingBase = loadedBaseRepo+ ? resolveDiffusionTrainingBase(reportedFamily, loadedBaseRepo)+ : null;const preferLoaded = family.base_repos.includes(baseChoice)? baseChoice: loadedBaseRepo && family.base_repos.includes(loadedBaseRepo)? loadedBaseRepo- : family.base_repos[0] ?? CUSTOM_BASE;+ : (pairedTrainingBase ?? family.base_repos[0] ?? CUSTOM_BASE);if (!baseDirty.current) setBaseChoice(preferLoaded);if (!settingsDirty.current) {setLearningRate(family.defaults.lr);@@ -604,7 +620,7 @@ export function DiffusionTrainPanel({: "auto",);}- }, [family, loadedBaseRepo, reportedFamily?.recommended_precision]);+ }, [family, loadedBaseRepo, reportedFamily]);// mixed_precision is an SDXL-only lever. A dense DiT base precision requires bf16 compute and every DiT family trains in bf16,// so reset to bf16 on a change to a DiT family, or an fp16 value left from SDXL rides along and the backend rejects it.@@ -1155,13 +1171,12 @@ export function DiffusionTrainPanel({[poll],);- // Resolve the repo an adapter should be PREVIEWED on: a family that trains on one checkpoint but runs adapters on another- // declares a deploy_base. Only a recognised training base is overridden; a custom typed repo is respected as-is.+ // Resolve the repo an adapter should be previewed on. Variant-specific pairs cover FLUX.2+ // Klein's 4B and 9B bases; the scalar fallback keeps older backends and Krea 2 working.const deployBaseFor = useCallback((trainedBase: string, famName: string): string => {const rec = info?.families?.find((f) => f.name === famName);- if (rec?.deploy_base && rec.base_repos.includes(trainedBase)) return rec.deploy_base;- return trainedBase;+ return resolveDiffusionDeployBase(rec, trainedBase);},[info?.families],);@@ -1490,7 +1505,7 @@ export function DiffusionTrainPanel({))}</SelectContent></Select>- <FamilyFacts family={family} />+ <FamilyFacts family={family} baseModel={resolvedBase} /></div><div className={fieldClass}>diff --git a/studio/frontend/tests/diffusion-train-deploy.test.ts b/studio/frontend/tests/diffusion-train-deploy.test.tsnew file mode 100644index 00000000000..52c0f396e37--- /dev/null+++ b/studio/frontend/tests/diffusion-train-deploy.test.ts@@ -0,0 +1,111 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";++import {+ resolveDiffusionDeployBase,+ resolveDiffusionTrainingBase,+} from "../src/features/images/train/diffusion-train-deploy.ts";++const klein = {+ name: "flux.2-klein",+ label: "FLUX.2 Klein",+ default_base: "black-forest-labs/FLUX.2-klein-base-4B",+ base_repos: [+ "black-forest-labs/FLUX.2-klein-base-4B",+ "black-forest-labs/FLUX.2-klein-base-9B",+ ],+ deploy_bases: {+ "black-forest-labs/FLUX.2-klein-base-4B":+ "black-forest-labs/FLUX.2-klein-4B",+ "black-forest-labs/FLUX.2-klein-base-9B":+ "black-forest-labs/FLUX.2-klein-9B",+ "unsloth/FLUX.2-klein-base-9B": "unsloth/FLUX.2-klein-9B",+ },+};++test("deploys each Klein base adapter on its matching distilled checkpoint", () => {+ assert.equal(+ resolveDiffusionDeployBase(klein, "black-forest-labs/FLUX.2-klein-base-4B"),+ "black-forest-labs/FLUX.2-klein-4B",+ );+ assert.equal(+ resolveDiffusionDeployBase(klein, "BLACK-FOREST-LABS/FLUX.2-KLEIN-BASE-9B"),+ "black-forest-labs/FLUX.2-klein-9B",+ );+ assert.equal(+ resolveDiffusionDeployBase(klein, "unsloth/FLUX.2-klein-base-9B"),+ "unsloth/FLUX.2-klein-9B",+ );+});++test("keeps custom bases and the legacy family-wide mapping working", () => {+ assert.equal(+ resolveDiffusionDeployBase(klein, "/models/custom-klein"),+ "/models/custom-klein",+ );+ assert.equal(+ resolveDiffusionDeployBase(+ {+ ...klein,+ base_repos: ["krea/Krea-2-Raw"],+ deploy_bases: {},+ deploy_base: "krea/Krea-2-Turbo",+ },+ "krea/Krea-2-Raw",+ ),+ "krea/Krea-2-Turbo",+ );+});++test("preselects the training base paired with a loaded distilled checkpoint", () => {+ assert.equal(+ resolveDiffusionTrainingBase(klein, "black-forest-labs/FLUX.2-klein-9B"),+ "black-forest-labs/FLUX.2-klein-base-9B",+ );+ assert.equal(+ resolveDiffusionTrainingBase(klein, "BLACK-FOREST-LABS/FLUX.2-KLEIN-4B"),+ "black-forest-labs/FLUX.2-klein-base-4B",+ );+});++test("returns null rather than inventing a base the backend would refuse", () => {+ assert.equal(resolveDiffusionTrainingBase(undefined, "black-forest-labs/FLUX.2-klein-9B"), null);+ assert.equal(resolveDiffusionTrainingBase(klein, ""), null);+ // Loaded checkpoint the family declares no pairing for.+ assert.equal(resolveDiffusionTrainingBase(klein, "krea/Krea-2-Turbo"), null);+ // A repo whose name matches nothing the family offers stays null.+ assert.equal(resolveDiffusionTrainingBase(klein, "unsloth/FLUX.2-klein-42B"), null);+});++test("a mirror-loaded checkpoint preselects the vendor base it copies", () => {+ // Deploy hands a LoRA trained on unsloth/FLUX.2-klein-base-9B the mirror checkpoint+ // unsloth/FLUX.2-klein-9B, so that is what /images/status reports afterwards. Its pairing names+ // the mirror TRAINING id, which base_repos does not offer, and the panel then fell back to the+ // first base: the 4B, seeding a 9B workflow from 4B weights. A mirror keeps the upstream name.+ assert.equal(+ resolveDiffusionTrainingBase(klein, "unsloth/FLUX.2-klein-9B"),+ "black-forest-labs/FLUX.2-klein-base-9B",+ );+ assert.equal(+ resolveDiffusionTrainingBase(klein, "UNSLOTH/FLUX.2-KLEIN-9B"),+ "black-forest-labs/FLUX.2-klein-base-9B",+ );+});++test("the Train panel preselect actually consults the pairing", async () => {+ // The helper on its own changes nothing: the bug was in the preselect chain, which fell from an+ // exact base_repos match straight to base_repos[0]. Assert the pairing sits BETWEEN the two.+ const source = await readFile(+ new URL("../src/features/images/train/diffusion-train-panel.tsx", import.meta.url),+ "utf8",+ );+ const paired = source.indexOf("pairedTrainingBase ??");+ const first = source.indexOf("family.base_repos[0]");+ assert.ok(paired > 0, "the preselect no longer falls back to the paired training base");+ assert.ok(paired < first && first - paired < 40, "base_repos[0] is no longer the last resort");+ assert.match(source, /resolveDiffusionTrainingBase\(reportedFamily, loadedBaseRepo\)/);+});diff --git a/studio/frontend/tests/diffusion-train-family-facts.test.ts b/studio/frontend/tests/diffusion-train-family-facts.test.tsnew file mode 100644index 00000000000..a895d4f3608--- /dev/null+++ b/studio/frontend/tests/diffusion-train-family-facts.test.ts@@ -0,0 +1,52 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { resolveDiffusionTrainingFacts } from "../src/features/images/train/diffusion-train-family-facts.ts";++const klein = {+ params: "4B",+ qlora_vram_gb: 10,+ gated: false,+ note: "",+ base_specs: {+ "black-forest-labs/FLUX.2-klein-base-9B": {+ params: "9B",+ qlora_vram_gb: 18,+ },+ "unsloth/FLUX.2-klein-base-9B": {+ params: "9B",+ qlora_vram_gb: 18,+ },+ },+};++test("shows checkpoint-specific Klein facts for the 9B vendor and mirror ids", () => {+ for (const repo of [+ "black-forest-labs/FLUX.2-klein-base-9B",+ "UNSLOTH/FLUX.2-KLEIN-BASE-9B",+ ]) {+ assert.deepEqual(resolveDiffusionTrainingFacts(klein, repo), {+ params: "9B",+ qlora_vram_gb: 18,+ gated: false,+ note: "",+ });+ }+});++test("keeps the family facts for Klein 4B and unknown custom bases", () => {+ assert.equal(+ resolveDiffusionTrainingFacts(+ klein,+ "black-forest-labs/FLUX.2-klein-base-4B",+ ).qlora_vram_gb,+ 10,+ );+ assert.equal(+ resolveDiffusionTrainingFacts(klein, "/models/custom").params,+ "4B",+ );+});diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.tsnew file mode 100644index 00000000000..cad3b57f7ab--- /dev/null+++ b/studio/frontend/tests/image-generation-defaults.test.ts@@ -0,0 +1,35 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import { defaultsFor } from "../src/features/images/image-generation-defaults.ts";++test("distinguishes Klein base checkpoints from distilled checkpoints", () => {+ for (const size of ["4B", "9B"]) {+ assert.deepEqual(defaultsFor(`unsloth/FLUX.2-klein-base-${size}`), {+ steps: 50,+ guidance: 4,+ });+ assert.deepEqual(defaultsFor(`unsloth/FLUX.2-klein-${size}`), {+ steps: 4,+ guidance: 1,+ });+ }+});++test("keeps the existing family defaults and fallback", () => {+ assert.deepEqual(defaultsFor("krea/Krea-2-Raw"), {+ steps: 52,+ guidance: 3.5,+ });+ assert.deepEqual(defaultsFor("black-forest-labs/FLUX.1-dev"), {+ steps: 28,+ guidance: 3.5,+ });+ assert.deepEqual(defaultsFor("local/unknown-image-model"), {+ steps: 9,+ guidance: 0,+ });+});