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: size FLUX.2-klein 9B LoRA training from its own weights, not the 4B family number (#8263)
Daniel Han5a8e4efa3791
diff --git a/studio/backend/core/inference/diffusion_auto_policy.py b/studio/backend/core/inference/diffusion_auto_policy.pyindex b456917ba8d..ff6b437aa40 100644--- a/studio/backend/core/inference/diffusion_auto_policy.py+++ b/studio/backend/core/inference/diffusion_auto_policy.py@@ -70,22 +70,39 @@ _FAMILY_HUB_DOWNLOAD_FACTOR: dict[str, float] = {}# Base-repo overrides for families offering multiple sizes under one entry (the table carries the family default).+# flux.2-klein ships FOUR checkpoints under one entry: 4B / base-4B (the family default, Qwen3-4B encoder) and+# 9B / base-9B (18.2 GB transformer, Qwen3-8B encoder). The 9B pair needs an override on BOTH ids: sizing+# klein-BASE-9B off the family default understates it by 2.3x, and the base variants are the ones the upstream+# guidance points fine-tuning at, so it is the likelier of the two to be loaded._BASE_REPO_BF16_GB: dict[str, tuple[float, float, float]] = {"black-forest-labs/FLUX.2-klein-9B": (18.2, 16.4, 0.2),+ "black-forest-labs/FLUX.2-klein-base-9B": (18.2, 16.4, 0.2),}+def base_repo_bf16_components_gb(base_repo: Optional[str]) -> Optional[tuple[float, float, float]]:+ """The per-base override for ``base_repo``, or None when it has none.++ No family fallback, unlike ``family_bf16_components_gb``: a caller that already holds a+ better number for the family default needs to know whether this particular base was+ actually named in the table, not receive the family figure back."""+ if not base_repo:+ return None+ # Keyed on UPSTREAM ids, so mirrors have to be normalised before the lookup.+ from .diffusion_families import canonical_base++ return _BASE_REPO_BF16_GB.get(canonical_base(base_repo))++def family_bf16_components_gb(fam: Any, base_repo: Optional[str] = None) -> Optional[tuple[float, float, float]]:"""(transformer, text encoders, VAE) bf16-resident sizes in GB, or None when the family isn'tin the table (callers fall back to file-size estimates)."""- if base_repo:- # Keyed on UPSTREAM ids, and a miss falls through quietly to the coarser family table.- from .diffusion_families import canonical_base- override = _BASE_REPO_BF16_GB.get(canonical_base(base_repo))- if override is not None:- return override+ # A per-base miss falls through quietly to the coarser family table.+ override = base_repo_bf16_components_gb(base_repo)+ if override is not None:+ return overridename = getattr(fam, "name", None)return _FAMILY_BF16_GB.get(name) if name else Nonediff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.pyindex 1c03917a58c..b85937bfc6e 100644--- a/studio/backend/core/training/diffusion_dit_trainer.py+++ b/studio/backend/core/training/diffusion_dit_trainer.py@@ -134,7 +134,9 @@ class _FamilySpec:lora_targets: tuple[str, ...]# bf16 only (Z-Image overflows fp16 and its RoPE/embedder run in fp32).force_bf16: bool- # Approximate dense-bf16 transformer weight size, used by base_precision="auto" to pick a mode that fits free VRAM.+ # Approximate dense-bf16 transformer weight size for the family's DEFAULT base, used by+ # base_precision="auto" to pick a mode that fits free VRAM. A family covering more than one+ # size (flux.2-klein is 4B and 9B) must not be sized off this alone -- see _dense_bf16_gb.dense_bf16_gb: float# Phased load so the multi-GB transformer never coexists with the text encoders + VAE: ``load_conditioners`` builds the# pipeline WITHOUT it and returns (pipe, vae); ``load_transformer`` then loads it alone once the conditioners are freed.@@ -476,6 +478,32 @@ def _pick_auto_precision(return "nf4"+def _dense_bf16_gb(spec, base_model: str) -> float:+ """The dense-bf16 transformer size of the base this run actually trains from.++ ``spec.dense_bf16_gb`` is one number per FAMILY, and flux.2-klein is a family with two+ transformer sizes under it: the 4B default (8.1 GB) and the 9B / base-9B pair (18.2 GB).+ Sizing a 9B run off the family number understates it by 2.3x, so base_precision="auto"+ (the mode /info recommends, and therefore the Train tab's default) resolves to bf16 on a+ 16-24 GB GPU and the dense load OOMs -- the run fails before the first step.++ The inference auto-policy already keeps per-base overrides for exactly this, so read them+ here instead of adding a second table that can drift. Reads the per-base OVERRIDES only,+ never the family table underneath them: this spec's own number is the family default, and+ the two are independently maintained, so falling through to the shared family entry would+ silently re-size every base that has no override (klein's 4B default from 8.1 to 7.8, which+ moves the bf16 band by half a GB). Never raises: a sizing lookup must not be able to fail a+ run that would otherwise train."""+ try:+ from core.inference.diffusion_auto_policy import base_repo_bf16_components_gb+ components = base_repo_bf16_components_gb(base_model)+ if components:+ return float(components[0])+ except Exception: # noqa: BLE001 -- table miss / import failure -> the family number+ pass+ return float(spec.dense_bf16_gb)++def _resolve_base_precision(cfg, spec, device) -> str:"""Resolve "auto" against the live GPU (free VRAM measured BEFORE anything loads);explicit modes pass through (normalized() already validated them against the repo and@@ -537,7 +565,13 @@ def _resolve_base_precision(cfg, spec, device) -> str:except Exception: # noqa: BLE001 -- probe failure -> the safe modepassreturn _pick_auto_precision(- prequant, device, free_gb, spec.dense_bf16_gb, capability, has_fp8, has_torchao+ prequant,+ device,+ free_gb,+ _dense_bf16_gb(spec, cfg.base_model),+ capability,+ has_fp8,+ has_torchao,)diff --git a/studio/backend/tests/test_diffusion_auto_policy.py b/studio/backend/tests/test_diffusion_auto_policy.pyindex 8eb9490adeb..2ac4acf9120 100644--- a/studio/backend/tests/test_diffusion_auto_policy.py+++ b/studio/backend/tests/test_diffusion_auto_policy.py@@ -58,6 +58,26 @@ def test_base_repo_override_wins_over_the_family_default():assert nine_b[0] > 2 * default[0]+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 is+ # the variant upstream points fine-tuning at, so it needs the same override as klein-9B.+ # Without it the base 9B is planned as a 4B and every size-driven decision under-reserves.+ default = family_bf16_components_gb(_fam("flux.2-klein"))+ nine_b = family_bf16_components_gb(+ _fam("flux.2-klein"), base_repo = "black-forest-labs/FLUX.2-klein-9B"+ )+ base_9b = family_bf16_components_gb(+ _fam("flux.2-klein"), base_repo = "black-forest-labs/FLUX.2-klein-base-9B"+ )+ assert base_9b == nine_b+ assert base_9b is not None and default is not None and base_9b[0] > 2 * default[0]+ # The unsloth mirror is what Studio actually loads, and canonical_base has to route it here too.+ assert (+ family_bf16_components_gb(_fam("flux.2-klein"), base_repo = "unsloth/FLUX.2-klein-base-9B")+ == base_9b+ )++# ── the estimator ─────────────────────────────────────────────────────────────def test_estimate_int8_steady_is_roughly_half_bf16():est = estimate_dense_quant(_fam("z-image"), "int8")diff --git a/studio/backend/tests/test_diffusion_base_precision.py b/studio/backend/tests/test_diffusion_base_precision.pyindex f24e0e3ad17..1704e1d1084 100644--- a/studio/backend/tests/test_diffusion_base_precision.py+++ b/studio/backend/tests/test_diffusion_base_precision.py@@ -387,6 +387,108 @@ def test_resolve_auto_int8_band_treats_stub_as_absent(monkeypatch):assert dit._resolve_base_precision(cfg, spec, "cuda") == "nf4"+def _fake_cuda_with_free_gb(monkeypatch, free_gb: float):+ """Point torch.cuda at a GPU reporting ``free_gb`` free, so the auto pick is deterministic."""+ import torch++ class _FakeCuda:+ @staticmethod+ def mem_get_info():+ return (int(free_gb * 1e9), int(80 * 1e9))++ @staticmethod+ def get_device_capability():+ return (10, 0)++ monkeypatch.setattr(torch, "cuda", _FakeCuda)+ monkeypatch.setattr(dit, "has_functional_torchao", lambda: True)+++ "base_model",+ [+ "black-forest-labs/FLUX.2-klein-9B",+ "black-forest-labs/FLUX.2-klein-base-9B",+ # The unsloth mirrors resolve to the same upstream ids, and they are what the Train tab sends.+ "unsloth/FLUX.2-klein-9B",+ "unsloth/FLUX.2-klein-base-9B",+ ],+)+def test_auto_sizes_flux2_klein_9b_off_its_own_weights(monkeypatch, base_model):+ # flux.2-klein covers a 4B and a 9B transformer under one family entry, so the family's+ # dense_bf16_gb (8.1, the 4B) must not size a 9B run: 20 GB free clears 8.1 * 1.5 but the+ # 9B dense weights are 18.2 GB, so "auto" would pick bf16 and the load would OOM before+ # step 1. Every 9B id has to land on nf4 here.+ spec = dit._SPECS["flux.2-klein"]+ _fake_cuda_with_free_gb(monkeypatch, 20.0)+ cfg = _cfg(base_model = base_model, base_precision = "auto", mixed_precision = "bf16")+ assert dit._resolve_base_precision(cfg, spec, "cuda") == "nf4"+ assert dit._dense_bf16_gb(spec, base_model) > 2 * spec.dense_bf16_gb+++def test_auto_still_picks_bf16_for_the_klein_4b_default(monkeypatch):+ # The same 20 GB against the family DEFAULT (4B, 8.1 GB dense) still clears the bf16 band:+ # the per-base lookup must narrow only the variant it has a size for.+ spec = dit._SPECS["flux.2-klein"]+ _fake_cuda_with_free_gb(monkeypatch, 20.0)+ cfg = _cfg(+ base_model = "black-forest-labs/FLUX.2-klein-4B",+ base_precision = "auto",+ mixed_precision = "bf16",+ )+ assert dit._resolve_base_precision(cfg, spec, "cuda") == "bf16"+++def test_the_klein_4b_bf16_band_edge_does_not_move(monkeypatch):+ # The band edge is dense_gb * 1.5, so a 12 GB card sits right on top of it for the 4B:+ # 8.1 -> 12.15 keeps int8, and the family table's 7.8 -> 11.70 would flip it to bf16 and+ # hand a 12 GB GPU a dense load with no room left. Pin the edge so the per-base lookup can+ # never widen it for a base it has no size for.+ spec = dit._SPECS["flux.2-klein"]+ _fake_cuda_with_free_gb(monkeypatch, 12.0)+ cfg = _cfg(+ base_model = "black-forest-labs/FLUX.2-klein-4B",+ base_precision = "auto",+ mixed_precision = "bf16",+ )+ assert dit._resolve_base_precision(cfg, spec, "cuda") == "int8"+++def test_dense_bf16_gb_keeps_every_base_without_an_override_exactly_where_it_was():+ # Only the klein 9B pair has a per-base override. EVERY other base -- including klein's own+ # 4B default -- must come back with the spec's own number untouched, bit for bit: the shared+ # family table is maintained separately (it records klein at 7.8 GB against this spec's 8.1),+ # so reading through to it would quietly move the auto bands of families this PR never+ # touched. An unknown base must fall back rather than raise, or the lookup could fail a run+ # that would otherwise train.+ for name in ("flux.1", "qwen-image", "z-image", "krea-2", "flux.2-dev", "flux.2-klein"):+ spec = dit._SPECS[name]+ for base in ("some/unknown-base", spec.family, ""):+ assert dit._dense_bf16_gb(spec, base) == spec.dense_bf16_gb+ klein = dit._SPECS["flux.2-klein"]+ for base in (+ "black-forest-labs/FLUX.2-klein-4B",+ "black-forest-labs/FLUX.2-klein-base-4B",+ "unsloth/FLUX.2-klein-4B",+ ):+ assert dit._dense_bf16_gb(klein, base) == klein.dense_bf16_gb+++def test_dense_bf16_gb_survives_a_broken_lookup(monkeypatch):+ # The sizing table is an optimisation, never a precondition: a lookup that blows up falls+ # back to the family number instead of failing the run.+ import core.inference.diffusion_auto_policy as ap++ def _boom(*_a, **_kw):+ raise RuntimeError("table unavailable")++ monkeypatch.setattr(ap, "base_repo_bf16_components_gb", _boom)+ spec = dit._SPECS["flux.2-klein"]+ assert dit._dense_bf16_gb(spec, "unsloth/FLUX.2-klein-base-9B") == pytest.approx(+ spec.dense_bf16_gb+ )++def test_has_functional_torchao_rejects_stub(monkeypatch):# has_functional_torchao must reject the import stub: the import succeeds against it, but the symbols are no-op stub types.import importlib