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
Pin the training precision, video preset and image metadata contracts (#8162)
Daniel Han5d461d7458a8
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 6fa96823aca..aad36820d40 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -20879,6 +20879,13 @@ async def openai_image_generations(# The batch shares one base seed, so restoring a batch_index>0 sibling needs the original batch_size."batch_size": body.n,"model": result.get("repo_id"),+ # The BUILD, exactly as /images/generate records it. This route is a supported way to+ # produce an image, and without these the gallery entry cannot say which GGUF quant or+ # which dense precision made the pixels -- the whole point of recording them.+ "model_kind": result.get("model_kind"),+ "gguf_filename": result.get("gguf_filename"),+ "transformer_quant": result.get("transformer_quant"),+ "baked_loras": list(result.get("baked_loras") or []),"created_at": float(created),}# The diffusers batch shares one seed; the native batch uses a distinct seed per image, so record each image's own seed.diff --git a/studio/backend/tests/test_saved_image_metadata_precision_contract.py b/studio/backend/tests/test_saved_image_metadata_precision_contract.pynew file mode 100644index 00000000000..09b18366aa7--- /dev/null+++ b/studio/backend/tests/test_saved_image_metadata_precision_contract.py@@ -0,0 +1,647 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Contract: a saved image's recipe records the build that ENGAGED, not the one requested.++``transformer_quant`` is a *request*: the loader may decline it (no dense source, not+enough VRAM, torchao missing) and run the GGUF as-is, or resolve "auto" to a concrete+scheme. Only ``_LoadState`` knows what actually ran, so the whole chain reads from it:++ load_pipeline(transformer_quant=...) -> _LoadState.transformer_quant (ENGAGED)+ |+ diffusion.generate() returns state.kind / .gguf_filename / .transformer_quant+ |+ routes/inference.py persists result[...] into the PNG recipe+ |+ images-page.tsx RecipePopover "Quant" row++If any hop starts echoing the request instead, a Recipe popover claims an image was made+with a quant that never loaded. These tests pin the divergent case at both ends.++They also pin ``image_gallery._REQUIRED_META``: the build keys are additive, so a PNG+written before they existed must still list rather than be dropped as foreign.++Hermetic: torch / diffusers are stubbed via ``sys.modules`` (same approach as+``test_diffusion_backend.py``, stubbed as packages so the loader's submodule imports resolve+without a real install), and the route half runs against a fake backend.+"""++from __future__ import annotations++import contextlib+import importlib.machinery+import io+import json+import sys+import types+from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import core.inference.diffusion as diffusion_module+import core.inference.gpu_arbiter as gpu_arbiter+import core.inference.image_gallery as gallery+from auth.authentication import get_current_subject+from core.inference.diffusion import DiffusionBackend+from routes.inference import router as openai_router, studio_router++_FRONTEND = Path(__file__).resolve().parents[2] / "frontend" / "src"++# The build fields the recipe carries beyond the plain generation settings. All sourced from+# the committed load state, all optional on an older PNG.+# Load-time build identity the route persists and GalleryImage defaults for older records.+# baked_loras belongs here for the same reason the other three do: promoting any of them into+# image_gallery._REQUIRED_META would stop every PNG written before it existed from listing.+_BUILD_KEYS = ("model_kind", "gguf_filename", "transformer_quant", "baked_loras")+++# ── stub runtime (pared-down twin of test_diffusion_backend's) ────────────────+++class _FakeDtype:+ def __init__(self, name: str) -> None:+ self._name = name++ def __repr__(self) -> str:+ return f"torch.{self._name}"++ __str__ = __repr__+++class _FakeGenerator:+ def __init__(self, device = None) -> None:+ self.device = device++ def seed(self) -> int:+ return 4242++ def manual_seed(self, value: int):+ return self+++class _FakeImage:+ """Stand-in for a generated PIL image."""+++class _FakePipe:+ def __init__(self) -> None:+ self.moved_to = None++ def to(self, device):+ self.moved_to = device+ return self++ def enable_model_cpu_offload(self, device = None) -> None:+ pass++ def enable_sequential_cpu_offload(self, device = None) -> None:+ pass++ def enable_vae_tiling(self) -> None:+ pass++ def enable_vae_slicing(self) -> None:+ pass++ # Explicit signature (not just **kwargs) so generate()'s signature-gated guards fire.+ def __call__(+ self,+ *,+ prompt = None,+ negative_prompt = None,+ callback_on_step_end = None,+ guidance_scale = None,+ true_cfg_scale = None,+ **kwargs,+ ):+ n = kwargs.get("num_images_per_prompt", 1)+ return types.SimpleNamespace(images = [_FakeImage() for _ in range(n)])+++class _FakePipeline:+ @classmethod+ def from_pretrained(cls, base, **kwargs):+ return _FakePipe()+++class _FakeTransformer:+ last: dict = {}++ @classmethod+ def from_single_file(cls, path, **kwargs):+ _FakeTransformer.last = {"path": path, **kwargs}+ return object()+++def _stub_package(name: str) -> types.ModuleType:+ """A stub module the import machinery will treat as a PACKAGE.++ ``types.ModuleType`` alone has no ``__path__``, so ``import torch.nn.functional`` cannot+ resolve a submodule through it -- see ``stub_runtime`` for why that matters.+ """+ module = types.ModuleType(name)+ module.__path__ = [] # empty: submodules are registered by hand, never found on disk+ module.__spec__ = importlib.machinery.ModuleSpec(name, loader = None, is_package = True)+ return module+++def stub_runtime(monkeypatch):+ """Enough torch / diffusers for a z-image GGUF load + one txt2img generate.++ ``load_pipeline`` lazily imports ``diffusion_eager_patches``, whose module body runs+ ``import torch.nn.functional as F``, and the GGUF prefix-strip shim imports+ ``diffusers.loaders.single_file_model``. Neither resolves through a bare ``ModuleType``.+ A dev box hides that -- something (``tests/conftest.py`` -> ``unsloth_zoo`` -> ``import+ torch``) has usually already seeded ``sys.modules["torch.nn.functional"]``, so the import+ short-circuits on the cached entry and never looks at the stub's missing ``__path__``. On a+ clean CPU-only CI interpreter nothing seeds it and the load dies with "'torch' is not a+ package". So register the submodules explicitly and make the stubs real packages: same+ hermetic runtime in both environments, whatever ran before.+ """+ torch = _stub_package("torch")+ torch.bfloat16 = _FakeDtype("bfloat16")+ torch.float16 = _FakeDtype("float16")+ torch.float32 = _FakeDtype("float32")+ torch.Generator = _FakeGenerator+ torch.cuda = types.SimpleNamespace(is_available = lambda: False)+ torch.backends = types.SimpleNamespace(mps = None)+ torch.inference_mode = lambda: contextlib.nullcontext()+ # torch.nn.functional: imported by diffusion_eager_patches. Empty -- the patch installers+ # only probe it (hasattr F, "rms_norm") and no patched forward runs under the fake pipe.+ torch_nn = _stub_package("torch.nn")+ torch_nn_functional = types.ModuleType("torch.nn.functional")+ torch_nn.functional = torch_nn_functional+ torch.nn = torch_nn++ diffusers = _stub_package("diffusers")+ diffusers.GGUFQuantizationConfig = lambda compute_dtype = None: ("quant", compute_dtype)+ diffusers.ZImagePipeline = _FakePipeline+ diffusers.ZImageTransformer2DModel = _FakeTransformer+ # diffusers.loaders.single_file_model: the GGUF prefix-strip shim looks the transformer class+ # up in this registry. Empty -> the shim finds no entry and returns, the same no-op it+ # performs against a real diffusers that has no converter for the class.+ diffusers_loaders = _stub_package("diffusers.loaders")+ single_file_model = types.ModuleType("diffusers.loaders.single_file_model")+ single_file_model.SINGLE_FILE_LOADABLE_CLASSES = {}+ diffusers_loaders.single_file_model = single_file_model+ diffusers.loaders = diffusers_loaders++ for name, module in (+ ("torch", torch),+ ("torch.nn", torch_nn),+ ("torch.nn.functional", torch_nn_functional),+ ("diffusers", diffusers),+ ("diffusers.loaders", diffusers_loaders),+ ("diffusers.loaders.single_file_model", single_file_model),+ ):+ # setitem restores the previous entry (or deletes it, if there was none) on teardown,+ # so a real torch/diffusers imported by another test is left untouched.+ monkeypatch.setitem(sys.modules, name, module)+ monkeypatch.setattr("core.inference.diffusion.clear_gpu_cache", lambda: None)+ _FakeTransformer.last = {}+ yield torch+ # A load that COMMITS deliberately keeps its process-wide eager/arch patches installed --+ # only unload() reverts them (diffusion.py's finally covers the pre-commit failure path+ # alone), and the GGUF default speed profile is "default", not "off", so the install runs.+ # Today nothing survives here because diffusers 0.39's bodies do not match the drift guards,+ # but that is a version accident, so revert unconditionally rather than rely on it. Both+ # calls are idempotent, and this runs before monkeypatch restores the stub modules.+ try:+ from core.inference.diffusion_arch_patches import uninstall_arch_patches+ from core.inference.diffusion_eager_patches import uninstall_patches++ uninstall_patches()+ uninstall_arch_patches()+ except Exception: # noqa: BLE001 - teardown must not mask the test's own failure+ pass+ # ...and evict the patch modules themselves. They were imported (lazily, by load_pipeline)+ # WHILE the fakes were installed, so their module-level `torch`, `F` and diffusers class+ # globals are bound to the stubs. monkeypatch puts sys.modules["torch"] back but not these,+ # so every later test in the process -- and any real load -- would go on running against+ # module bodies that closed over the fakes. Dropping the cache entries makes the next import+ # rebind them under whatever runtime is installed then.+ for cached in (+ "core.inference.diffusion_eager_patches",+ "core.inference.diffusion_arch_patches",+ ):+ sys.modules.pop(cached, None)+++def backend(stub_runtime):+ """A backend that is unloaded afterwards, so a committed load's process-wide state does not+ outlive the test that created it."""+ instance = DiffusionBackend()+ try:+ yield instance+ finally:+ try:+ instance.unload()+ except Exception: # noqa: BLE001 - a stub teardown failure is not this test's verdict+ pass+++def _load(backend, tmp_path, monkeypatch, torch, **kwargs):+ (tmp_path / "m.gguf").write_bytes(b"x")+ # Drive the loader down the CUDA (dense-quant capable) path under the stub.+ monkeypatch.setattr(backend, "_pick_device_and_dtype", lambda: ("cuda", torch.bfloat16))+ return backend.load_pipeline(+ str(tmp_path), gguf_filename = "m.gguf", family_override = "z-image", **kwargs+ )+++def _generate(backend):+ return backend.generate(prompt = "a sloth", width = 512, height = 512, steps = 2, guidance = 1.0, seed = 7)+++# ── backend: generate() reports the committed load state ──────────────────────+++def test_a_declined_quant_request_is_not_reported_as_engaged(+ backend, stub_runtime, tmp_path, monkeypatch+):+ """The user asked for fp8; the host has no dense source, so the GGUF loaded as-is.+ The recipe must say "GGUF, no quant", not "fp8"."""+ monkeypatch.setattr(diffusion_module, "dense_transformer_supported", lambda target: False)+ status = _load(backend, tmp_path, monkeypatch, stub_runtime, transformer_quant = "fp8")++ assert status["transformer_quant"] is None+ assert backend._state.transformer_quant is None+ # The provenance record keeps BOTH sides, so the UI can explain the difference: the+ # request was explicit, the engaged value is "off".+ resolved = status["resolved"]["transformer_quant"]+ assert resolved["value"] == "off" and resolved["source"] == "explicit"+ assert "GGUF transformer loaded" in resolved["reason"]++ result = _generate(backend)+ assert result["transformer_quant"] is None, (+ "generate() echoed the declined request; the saved recipe would claim a quant "+ "that never loaded"+ )+ assert result["model_kind"] == "gguf"+ assert result["gguf_filename"] == "m.gguf"+++def test_generate_reports_the_engaged_scheme_when_it_differs_from_the_request(+ backend, stub_runtime, tmp_path, monkeypatch+):+ """The request said fp8; the resolver picked int8 for this GPU. int8 is what ran, so+ int8 is what the recipe has to record."""+ requested, engaged = "fp8", "int8"++ @classmethod+ def _from_pretrained(cls, base, **kwargs):+ return object()++ monkeypatch.setattr(_FakeTransformer, "from_pretrained", _from_pretrained, raising = False)+ monkeypatch.setattr(diffusion_module, "dense_transformer_supported", lambda target: True)+ monkeypatch.setattr(+ diffusion_module,+ "select_transformer_quant_scheme",+ lambda target, mode, family = None: engaged,+ )+ monkeypatch.setattr(diffusion_module, "resolve_prequant_source", lambda fam, scheme, **kw: None)+ monkeypatch.setattr(+ diffusion_module, "quantize_transformer", lambda pipe, target, *, mode, **kw: engaged+ )++ status = _load(backend, tmp_path, monkeypatch, stub_runtime, transformer_quant = requested)++ assert status["transformer_quant"] == engaged+ assert backend._state.transformer_quant == engaged++ result = _generate(backend)+ assert result["transformer_quant"] == engaged, (+ f"generate() reported {result['transformer_quant']!r}; the ENGAGED scheme was "+ f"{engaged!r} and the request was {requested!r}"+ )+ assert result["transformer_quant"] != requested+ # The dense build is no longer a GGUF transformer, and that is part of the build identity too.+ assert result["model_kind"] == "gguf" and result["gguf_filename"] == "m.gguf"+++# ── route: the persisted recipe carries what generate() reported ──────────────+++class _EngagedBackend:+ """A backend that accepts one precision and engages another, so the route cannot+ satisfy the assertions by reading the load request."""++ requested = "fp8"+ engaged = "int8"++ def __init__(self) -> None:+ self.loaded = False+ self.loading: tuple = ()+ self.last_load_kwargs: dict = {}++ @property+ def is_loaded(self) -> bool:+ return self.loaded++ def loading_repo_ids(self) -> tuple:+ return tuple(self.loading)++ def validate_load_request(self, model_path, **kwargs):+ from core.inference.diffusion_families import detect_family+ return detect_family(model_path, kwargs.get("family_override"))++ def preflight_base_access(self, model_path, fam, **kwargs):+ return None++ def begin_load(self, model_path, **kwargs):+ self.loaded = True+ self.last_load_kwargs = dict(kwargs)+ return {+ "loaded": True,+ "repo_id": model_path,+ "family": "z-image",+ "base_repo": "base/repo",+ "device": "cuda",+ "dtype": "bfloat16",+ "cpu_offload": False,+ "offload_policy": "none",+ "vae_tiling": False,+ "memory_mode": "auto",+ # The loader declined fp8 and engaged int8 instead.+ "transformer_quant": self.engaged,+ }++ def load_progress(self):+ return {+ "phase": "ready" if self.loaded else None,+ "bytes_downloaded": 0,+ "bytes_total": 0,+ "fraction": 1.0,+ "error": None,+ }++ def generate(+ self,+ *,+ seed = None,+ batch_size = 1,+ prompts = None,+ seeds = None,+ **kwargs,+ ):+ if not self.loaded:+ raise RuntimeError("No diffusion model is loaded.")+ return {+ "images": [object() for _ in range(batch_size)],+ "seed": seed if seed is not None else 4242,+ "repo_id": "x/z-image",+ # Straight off the committed load state, as the real backend does.+ "model_kind": "gguf",+ "gguf_filename": "z-image-Q4_K_M.gguf",+ "transformer_quant": self.engaged,+ "workflow": "txt2img",+ }++ def generate_progress(self):+ return {"active": False, "step": 0, "total_steps": 0, "fraction": 0.0, "eta_seconds": None}++ def unload(self):+ self.loaded = False+ return {"loaded": False}++ def status(self):+ return {"loaded": self.loaded, "repo_id": None, "family": None, "cpu_offload": False}+++def engaged_client(monkeypatch, tmp_path):+ backend = _EngagedBackend()+ monkeypatch.setattr(diffusion_module, "get_diffusion_backend", lambda: backend)+ import core.inference.diffusion_engine_router as engine_router++ monkeypatch.setattr(engine_router, "select_and_activate_engine", lambda fam, **kw: backend)+ monkeypatch.setattr(engine_router, "get_active_diffusion_engine", lambda: backend)+ monkeypatch.setattr(engine_router, "predict_engine", lambda fam, **kw: "diffusers")+ monkeypatch.setattr(engine_router, "_active_engine_name", "diffusers")+ monkeypatch.setattr(engine_router, "_fallback_reason", None)+ monkeypatch.setattr(gpu_arbiter, "_owner", None)+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.CHAT, lambda: None)+ monkeypatch.setitem(gpu_arbiter._EVICTORS, gpu_arbiter.DIFFUSION, lambda: None)++ # Record exactly the metadata dict the route hands the gallery.+ saved: list[dict] = []++ def _save(image, meta):+ saved.append(meta)+ image_id = f"img{len(saved)}"+ (tmp_path / f"{image_id}.png").write_bytes(b"PNG")+ return {**meta, "id": image_id, "url": f"/api/inference/images/gallery/{image_id}/file"}++ monkeypatch.setattr(gallery, "save", _save)++ app = FastAPI()+ app.include_router(studio_router, prefix = "/api/inference")+ # The OpenAI-compatible images route lives on the other router, mounted at /v1 in+ # production. Both persistence paths reach the same gallery, so both are exercised here.+ app.include_router(openai_router, prefix = "/v1")+ app.dependency_overrides[get_current_subject] = lambda: "test-user"+ return TestClient(app), backend, saved+++def test_the_persisted_recipe_records_the_engaged_build_not_the_load_request(engaged_client):+ client, backend, saved = engaged_client+ load = client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-Q4_K_M.gguf",+ "transformer_quant": _EngagedBackend.requested,+ },+ )+ assert load.status_code == 200, load.text+ # The request really did ask for the other scheme.+ assert backend.last_load_kwargs["transformer_quant"] == _EngagedBackend.requested++ gen = client.post("/api/inference/images/generate", json = {"prompt": "a sloth", "seed": 7})+ assert gen.status_code == 200, gen.text++ assert len(saved) == 1+ meta = saved[0]+ assert meta["transformer_quant"] == _EngagedBackend.engaged, (+ f"the recipe recorded {meta['transformer_quant']!r}; the load REQUESTED "+ f"{_EngagedBackend.requested!r} and the backend ENGAGED {_EngagedBackend.engaged!r}"+ )+ assert meta["transformer_quant"] != _EngagedBackend.requested+ assert meta["model_kind"] == "gguf"+ assert meta["gguf_filename"] == "z-image-Q4_K_M.gguf"++ # ...and again through the response model, because that is what the Recipe popover reads.+ # The dict above is pre-serialization: a GalleryImage that stops declaring these fields has+ # FastAPI silently strip them from the wire while every assertion above still passes.+ body = gen.json()["images"][0]+ for field, expected in (+ ("transformer_quant", _EngagedBackend.engaged),+ ("model_kind", "gguf"),+ ("gguf_filename", "z-image-Q4_K_M.gguf"),+ ):+ assert body.get(field) == expected, (+ f"the generate response dropped {field!r}: the route recorded {meta[field]!r} and "+ f"the serialized body says {body.get(field)!r}"+ )+++def test_the_openai_route_persists_the_same_build(engaged_client):+ """The other supported way to make an image.++ /v1/images/generations goes through the same backend and the same gallery, and its recipe+ was missing every build key -- so an image made through an OpenAI client listed with no+ quant, no kind and no filename while the contract above stayed green.+ """+ client, backend, saved = engaged_client+ load = client.post(+ "/api/inference/images/load",+ json = {+ "model_path": "unsloth/Z-Image-Turbo-GGUF",+ "gguf_filename": "z-image-Q4_K_M.gguf",+ "transformer_quant": _EngagedBackend.requested,+ },+ )+ assert load.status_code == 200, load.text++ generated = client.post(+ "/v1/images/generations",+ json = {"prompt": "a sloth", "n": 1, "response_format": "url"},+ )+ assert generated.status_code == 200, generated.text++ assert len(saved) == 1+ meta = saved[0]+ assert meta["transformer_quant"] == _EngagedBackend.engaged+ assert meta["model_kind"] == "gguf"+ assert meta["gguf_filename"] == "z-image-Q4_K_M.gguf"+ assert meta["baked_loras"] == []+++def test_the_stub_runtime_does_not_outlive_its_own_test(stub_runtime):+ """The patch modules are imported lazily by load_pipeline, i.e. WHILE the fakes are+ installed, so their module globals close over them. monkeypatch restores sys.modules["torch"]+ but not those, and every later test in the process would then run against module bodies+ bound to a fake torch. The fixture has to evict them."""+ import core.inference.diffusion_eager_patches # noqa: F401 — imported under the stubs+ assert sys.modules["torch"] is stub_runtime+ # The eviction itself is asserted by the sibling test below, which runs after teardown.+++def test_the_patch_modules_are_not_left_cached_against_the_fakes():+ """Runs outside the stub fixture: whatever the test above imported must be gone."""+ for cached in (+ "core.inference.diffusion_eager_patches",+ "core.inference.diffusion_arch_patches",+ ):+ module = sys.modules.get(cached)+ if module is None:+ continue+ # Present only because something imported it under the REAL runtime.+ torch_global = getattr(module, "torch", None)+ assert torch_global is None or torch_global is sys.modules.get(+ "torch"+ ), f"{cached} is cached with a torch that is not the live one"+++# ── gallery: the build keys stay additive ─────────────────────────────────────+++def tmp_gallery(monkeypatch, tmp_path):+ monkeypatch.setattr(gallery, "studio_root", lambda: tmp_path)+ return tmp_path+++def _old_schema_meta() -> dict:+ """A recipe as written before the build fields existed."""+ return {+ "prompt": "a sloth",+ "negative_prompt": None,+ "width": 1024,+ "height": 1024,+ "steps": 9,+ "guidance": 0.0,+ "seed": 7,+ "model": "unsloth/Z-Image-Turbo-GGUF",+ "created_at": 100.0,+ }+++def test_the_build_keys_are_never_required_to_list_a_png(tmp_gallery):+ """``_REQUIRED_META`` is the "is this PNG ours" gate. Promoting a build key into it+ would silently hide every image generated before that key existed."""+ for key in _BUILD_KEYS:+ assert key not in gallery._REQUIRED_META, (+ f"{key!r} became a required recipe key; every PNG written before it existed would "+ "stop listing"+ )+++def test_a_png_without_the_build_keys_still_lists(tmp_gallery):+ pytest.importorskip("PIL")+ from PIL import Image++ meta = _old_schema_meta()+ for key in _BUILD_KEYS:+ assert key not in meta+ record = gallery.save(Image.new("RGB", (16, 16), (10, 20, 30)), meta)++ listed = gallery.list_images()+ assert [r["id"] for r in listed] == [record["id"]]+ assert listed[0]["prompt"] == "a sloth"+ # Absent, not null-filled: the popover keys off truthiness and hides the rows.+ for key in _BUILD_KEYS:+ assert key not in listed[0]+ assert gallery.owned_image_path(record["id"]) is not None+++def test_a_png_with_the_build_keys_round_trips_them(tmp_gallery):+ pytest.importorskip("PIL")+ from PIL import Image++ meta = {+ **_old_schema_meta(),+ "model_kind": "gguf",+ "gguf_filename": "z-image-Q4_K_M.gguf",+ "transformer_quant": "int8",+ }+ record = gallery.save(Image.new("RGB", (16, 16), (10, 20, 30)), meta)+ listed = gallery.list_images()+ assert listed[0]["transformer_quant"] == "int8"++ # Through the listing's response model too. Pydantic drops anything the model does not+ # declare, so a GalleryImage that stops carrying a build key leaves the raw assertion above+ # green and the wire silently short -- which is the popover going blank.+ from models.inference import GalleryListResponse++ wire = GalleryListResponse(images = listed).model_dump()["images"][0]+ for key in ("model_kind", "gguf_filename", "transformer_quant"):+ assert wire.get(key) == meta[key], (+ f"GalleryImage no longer serializes {key!r}: the record has {meta[key]!r}, the wire "+ f"has {wire.get(key)!r}"+ )++ # The PNG itself carries the recipe, so a downloaded file keeps the build identity.+ raw = (gallery.gallery_dir() / f"{record['id']}.png").read_bytes()+ with Image.open(io.BytesIO(raw)) as im:+ embedded = json.loads(im.text["unsloth"])+ assert embedded["transformer_quant"] == "int8"+ assert embedded["gguf_filename"] == "z-image-Q4_K_M.gguf"+++# ── frontend: the recipe popover still shows the engaged build ────────────────+++def test_the_recipe_popover_renders_the_build_fields():+ src = (_FRONTEND / "features" / "images" / "images-page.tsx").read_text(encoding = "utf-8")+ popover = src[src.index("function RecipePopover(") :]+ popover = popover[: popover.index("\ntype Busy")]+ assert '<RecipeRow label="Quant" value={image.transformer_quant} />' in popover+ assert '<RecipeRow label="File" value={image.gguf_filename} mono />' in popover+ # Rendered conditionally, so an older PNG without them shows the rest of the recipe.+ for key in ("transformer_quant", "gguf_filename"):+ assert f"image.{key} ?" in popoverdiff --git a/studio/backend/tests/test_train_precision_scheme_contract.py b/studio/backend/tests/test_train_precision_scheme_contract.pynew file mode 100644index 00000000000..e000051d11f--- /dev/null+++ b/studio/backend/tests/test_train_precision_scheme_contract.py@@ -0,0 +1,366 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Contract: the diffusion TRAINING precision menu never gains an INFERENCE-only scheme.++Inference and training share a vocabulary of quantisation names, but not the same set.+Inference offers ``nvfp4`` (torchao 4-bit weight-only, Blackwell) and ``fp8_dynamic``;+the DiT trainer offers neither -- there is no training path for them, so a UI that+advertised one would evict every resident model, start a run, and then fail. The chain+that has to stay honest is:++ train_precision_modes() -> family_train_infos() -> GET /diffusion/info+ |+ diffusion-train-panel.tsx `precisionModes`+ |+ DiffusionTrainingStartRequest.base_precision (422 gate)++These assertions read BOTH ends -- the live Python probe over a simulated GPU matrix, and+the frontend source -- so adding ``nvfp4`` to either one reddens. They are deliberately+paired with a positive check that ``nvfp4`` really is a supported INFERENCE scheme, so the+suite cannot pass by the name having quietly disappeared everywhere.+"""++from __future__ import annotations++import re+from pathlib import Path+from typing import get_args++import pytest++import core.training.diffusion_train_common as common+from core.inference.diffusion_lora import _DIFFUSERS_LORA_BLOCKED_QUANT+from core.inference.diffusion_precision import TE_QUANT_MODES, TE_QUANT_NVFP4+from core.training.diffusion_train_common import DiffusionLoraConfig, train_precision_modes+from models.inference import DiffusionLoadRequest, VideoLoadRequest+from models.training import DiffusionTrainingStartRequest++_BACKEND = Path(__file__).resolve().parent.parent+_FRONTEND = _BACKEND.parent / "frontend" / "src"++# The base_precision wire contract: anything outside this is a 422 before a GPU is touched.+_TRAIN_PRECISIONS: frozenset[str] = frozenset(+ get_args(DiffusionTrainingStartRequest.model_fields["base_precision"].annotation)+)++# "off"/"none"/"auto" are request sentinels, not schemes; strip them before diffing the two vocabularies.+_SENTINELS: frozenset[str] = frozenset({"auto", "none", "off"})+++def _literal_names(model, field: str) -> frozenset[str]:+ """The Literal member names of an ``Optional[Literal[...]]`` field."""+ annotation = model.model_fields[field].annotation+ names = {a for a in get_args(annotation) if isinstance(a, str)}+ for arg in get_args(annotation):+ names |= {a for a in get_args(arg) if isinstance(a, str)}+ return frozenset(names)+++# Every quantisation name inference can be asked for, across the transformer and the text encoders.+_INFERENCE_SCHEMES: frozenset[str] = (+ _literal_names(DiffusionLoadRequest, "transformer_quant")+ | _literal_names(DiffusionLoadRequest, "text_encoder_quant")+ | frozenset(TE_QUANT_MODES)+) - _SENTINELS++# Schemes inference supports that training has no path for. Derived, not hardcoded, so a new+# inference-only scheme is covered the day it lands; the guard below pins nvfp4 into it so the+# derivation cannot silently empty out (which would make every assertion here vacuous).+_INFERENCE_ONLY: frozenset[str] = _INFERENCE_SCHEMES - _TRAIN_PRECISIONS++# (major, minor) capabilities spanning every branch of the probe: pre-Ampere, Ampere, Ada, Hopper, Blackwell, and newer.+_CAPABILITIES = ((7, 5), (8, 0), (8, 6), (8, 9), (9, 0), (10, 0), (12, 0))+++def _probe(+ monkeypatch,+ capability,+ *,+ cuda = True,+ torchao = True,+) -> tuple[list[str], str]:+ """(modes, recommended) as train_precision_modes() would answer on the given machine.++ The recommendation is returned, not discarded: the Train panel seeds basePrecision from it,+ so a recommendation outside the reported list is an option the user starts on and the select+ never offered."""+ import torch++ monkeypatch.setattr(torch.cuda, "is_available", lambda: cuda)+ monkeypatch.setattr(torch.cuda, "is_bf16_supported", lambda *a, **k: True)+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a, **k: capability)+ monkeypatch.setattr(common, "has_functional_torchao", lambda: torchao)+ return train_precision_modes()+++def _every_advertisable_mode(monkeypatch) -> frozenset[str]:+ """The union of everything the probe can EVER put in front of a user, over the whole+ GPU x torchao matrix. The UI can only ever render a subset of this."""+ seen: set[str] = set()+ for capability in _CAPABILITIES:+ for torchao in (True, False):+ seen.update(_probe(monkeypatch, capability, torchao = torchao)[0])+ seen.update(_probe(monkeypatch, (10, 0), cuda = False)[0])+ return frozenset(seen)+++# ── the vocabularies really do differ ─────────────────────────────────────────+++def test_nvfp4_is_a_real_inference_scheme_and_not_a_training_one():+ """Anchors the rest of the file: nvfp4 must exist on the inference side, or every+ "nvfp4 is absent" assertion below would pass for the wrong reason."""+ assert TE_QUANT_NVFP4 == "nvfp4"+ assert TE_QUANT_NVFP4 in TE_QUANT_MODES+ assert "nvfp4" in _literal_names(DiffusionLoadRequest, "transformer_quant")+ assert "nvfp4" in _literal_names(DiffusionLoadRequest, "text_encoder_quant")+ # It is also the scheme the diffusers LoRA path refuses to attach to, so it is genuinely live.+ assert "nvfp4" in _DIFFUSERS_LORA_BLOCKED_QUANT+ # ...and it is inference-only.+ assert "nvfp4" in _INFERENCE_ONLY+ assert "nvfp4" not in _TRAIN_PRECISIONS+++# ── backend: the probe ────────────────────────────────────────────────────────++[email protected]("capability", _CAPABILITIES)[email protected]("torchao", (True, False))+def test_train_precision_modes_never_offers_an_inference_only_scheme(+ monkeypatch, capability, torchao+):+ modes, recommended = _probe(monkeypatch, capability, torchao = torchao)+ leaked = sorted(_INFERENCE_ONLY.intersection(modes))+ assert not leaked, (+ f"train_precision_modes() on sm{capability[0]}{capability[1]} (torchao={torchao}) "+ f"advertises inference-only scheme(s) {leaked}; the DiT trainer has no path for them, "+ "so /diffusion/info would offer a start that evicts resident models and then fails"+ )+ # Anything advertised must also clear the request schema, or the UI offers a guaranteed 422.+ assert set(modes) <= _TRAIN_PRECISIONS, sorted(set(modes) - _TRAIN_PRECISIONS)+ assert "nf4" in modes # the floor is always available+ # The recommendation is what the panel seeds basePrecision with, so one outside the reported+ # list is an option the user starts on and the select never offered -- and one outside the+ # schema is a guaranteed 422 on the first start.+ assert recommended in modes, (+ f"the recommendation {recommended!r} is not in the modes reported for "+ f"sm{capability[0]}{capability[1]} (torchao={torchao}): {sorted(modes)}"+ )+ assert recommended in _TRAIN_PRECISIONS+++def test_the_advertisable_vocabulary_is_exactly_the_schema_vocabulary(monkeypatch):+ """Across every GPU the probe can meet, the modes it emits are exactly the request+ Literal -- no more (a 422 the UI could hit) and no fewer (a dead schema member)."""+ assert _every_advertisable_mode(monkeypatch) == _TRAIN_PRECISIONS+++def test_family_train_infos_never_advertises_an_inference_only_scheme(monkeypatch, dit_train_host):+ """The /diffusion/info payload itself, on a Blackwell host where every scheme is live."""+ _probe(monkeypatch, (10, 0))+ for info in common.family_train_infos():+ modes = info["precision_modes"]+ assert not _INFERENCE_ONLY.intersection(+ modes+ ), f"family {info['name']!r} advertises {sorted(_INFERENCE_ONLY.intersection(modes))}"+ assert set(modes) <= _TRAIN_PRECISIONS+ assert info["recommended_precision"] in _TRAIN_PRECISIONS+++# ── schema: the 422 gate ──────────────────────────────────────────────────────++[email protected]("scheme", sorted(_INFERENCE_ONLY))+def test_the_start_request_rejects_an_inference_only_precision(scheme):+ with pytest.raises(Exception) as excinfo:+ DiffusionTrainingStartRequest(+ base_model = "black-forest-labs/FLUX.1-dev",+ data_dir = "d",+ output_dir = "o",+ base_precision = scheme,+ )+ assert "base_precision" in str(excinfo.value)+++def test_the_trainer_accepts_exactly_what_the_schema_advertises():+ """The one link the rest of this file cannot supply. Every set above is derived from the+ request schema and the probe, so a mode added to BOTH of those disappears from+ ``_INFERENCE_ONLY`` and every assertion here passes -- while+ ``DiffusionLoraConfig.normalized()`` keeps its own hardcoded tuple and rejects the run after+ it has already evicted the resident model. Asked of the trainer directly rather than parsed+ out of it, so a refactor of that tuple cannot fool the check.+ """+ accepted, refused = set(), {}+ for mode in sorted(_TRAIN_PRECISIONS):+ config = DiffusionLoraConfig(+ base_model = "black-forest-labs/FLUX.1-dev",+ data_dir = "d",+ output_dir = "o",+ base_precision = mode,+ )+ try:+ config.normalized()+ except Exception as exc: # noqa: BLE001 - anything that stops a start counts as a refusal+ # The mode-name message is the expected shape, but it is not the only way a start+ # dies: a dense-base check, a mixed-precision check or a new dataset-path check would+ # block the same advertised mode just as completely. Swallowing those would keep this+ # green for a precision the UI offers and the trainer refuses.+ refused[mode] = f"{type(exc).__name__}: {exc}"+ continue+ accepted.add(mode)++ assert not refused, (+ f"the request schema advertises {sorted(refused)}, which DiffusionLoraConfig.normalized() "+ "rejects; a start would evict the resident model and then fail"+ )+ assert accepted == set(_TRAIN_PRECISIONS)++ # ...and the tuple is not simply permissive: an inference-only scheme still has to bounce,+ # or the assertion above would hold for a trainer that accepts everything.+ for scheme in sorted(_INFERENCE_ONLY):+ bogus = DiffusionLoraConfig(+ base_model = "black-forest-labs/FLUX.1-dev",+ data_dir = "d",+ output_dir = "o",+ base_precision = scheme,+ )+ with pytest.raises(ValueError, match = "base_precision must be one of"):+ bogus.normalized()+++def test_every_training_precision_is_accepted_by_the_start_request():+ for mode in sorted(_TRAIN_PRECISIONS):+ req = DiffusionTrainingStartRequest(+ base_model = "black-forest-labs/FLUX.1-dev",+ data_dir = "d",+ output_dir = "o",+ base_precision = mode,+ )+ assert req.base_precision == mode+++# ── frontend: the Train panel's precision selector ────────────────────────────+++def _precision_memo_block() -> str:+ """The body of ``diffusion-train-panel.tsx``'s ``precisionModes`` useMemo: the type+ annotation, the reported-mode filter, and the no-backend fallback array."""+ src = (_FRONTEND / "features" / "images" / "train" / "diffusion-train-panel.tsx").read_text(+ encoding = "utf-8"+ )+ start = src.index("const precisionModes = useMemo<")+ close = src.index("\n }, [", start)+ block = src[start : src.index(");", close) + 2]+ # Guard the extraction itself: a refactor that moves the memo must not silently shrink this to nothing.+ assert "familyUntrainable" in block and "return [" in block, block+ return block+++# A TS/TSX string literal in any of the three quotings. Prettier normalizes this file to+# double quotes, but the guard must not depend on that: a hand-edit or a merge that spelled a+# scheme 'nvfp4' or `nvfp4` would otherwise slip past every assertion below while rendering+# exactly the same option. Verified by mutation -- a single-quoted arm used to pass clean.+_STRING_LITERAL = re.compile(r"""["'`]([^"'`\\\n]*)["'`]""")+_M_EQUALS = re.compile(r"""m === ["'`]([^"'`]+)["'`]""")+++def _strip_comments(block: str) -> str:+ """Line and block comments removed, so a scheme merely NAMED in prose is not read as an+ offered option (and, the other way round, so a commented-out arm cannot mask a real one)."""+ return re.sub(r"//[^\n]*", "", re.sub(r"/\*.*?\*/", "", block, flags = re.S))+++def _memo_string_literals(block: str) -> list[str]:+ return _STRING_LITERAL.findall(_strip_comments(block))+++def test_the_precision_selector_names_only_training_precisions():+ """Every string literal inside the memo -- the TS union, the runtime filter whitelist and+ the fallback array -- must be a real training precision. This is the assertion that+ reddens if someone drops "nvfp4" anywhere into the Train panel's precision list."""+ literals = set(_memo_string_literals(_precision_memo_block()))+ assert literals, "parsed no string literals out of the precisionModes memo"+ assert literals <= _TRAIN_PRECISIONS, (+ f"the Train precision selector names {sorted(literals - _TRAIN_PRECISIONS)}, which "+ f"{'is' if len(literals - _TRAIN_PRECISIONS) == 1 else 'are'} not accepted by "+ "DiffusionTrainingStartRequest.base_precision"+ )+ assert not _INFERENCE_ONLY.intersection(literals)+++def test_the_precision_selector_fallback_is_a_subset_of_what_the_backend_can_report(monkeypatch):+ """With no /diffusion/info report the panel falls back to a hardcoded array. It must stay+ inside what the backend could actually have said, or the first paint offers a dead option."""+ returns = re.findall(r"return\s*\[([^\]]*)\]", _strip_comments(_precision_memo_block()))+ fallback = _STRING_LITERAL.findall(returns[-1])+ assert len(fallback) >= 2, f"failed to parse the fallback array: {returns[-1]!r}"+ advertisable = _every_advertisable_mode(monkeypatch)+ assert set(fallback) <= advertisable, (+ f"the Train panel's offline fallback offers {sorted(set(fallback) - advertisable)}, "+ "which train_precision_modes() never reports on any GPU"+ )+ assert not _INFERENCE_ONLY.intersection(fallback)+++def test_the_reported_mode_filter_is_a_subset_of_what_the_backend_can_report(monkeypatch):+ """The panel narrows the backend's list through an explicit ``m === "..."`` whitelist.+ Every arm of it must be a mode the backend can actually emit."""+ block = _strip_comments(_precision_memo_block())+ predicate = block[block.index(".filter(") : block.index("return [", block.index(".filter("))]+ whitelist = set(_M_EQUALS.findall(predicate))+ assert whitelist, f"parsed no whitelist arms out of {predicate!r}"+ advertisable = _every_advertisable_mode(monkeypatch)+ # Equality, not containment. A subset check passes just as happily when an arm is DELETED,+ # and the effect of deleting one is that the backend keeps reporting the mode while the panel+ # silently drops it from the select -- a mode the user can never pick and no error anywhere.+ assert whitelist == advertisable - _SENTINELS, (+ f"the panel filters to {sorted(whitelist)} but the backend can report "+ f'{sorted(advertisable - _SENTINELS)}; "auto" is prepended separately, so the filter '+ "has to name every other advertisable mode exactly"+ )+ assert not _INFERENCE_ONLY.intersection(whitelist)+ # ...and Auto has to survive the memo. Subtracting it above is only sound while the memo+ # prepends it: change `return ["auto", ...reported]` to `return reported` and this file+ # would still pass while the user loses the backend-recommended option the moment a report+ # arrives. Both return paths, since the fallback is what a backendless first paint renders.+ # `return []` for an untrainable family offers nothing at all, deliberately; every return+ # that offers anything has to lead with Auto.+ returns = [+ line+ for line in block.splitlines()+ if "return [" in line+ and line.strip() not in ("return [];", "if (familyUntrainable) return [];")+ ]+ assert returns, f"parsed no return arrays out of the memo: {block!r}"+ for line in returns:+ assert '"auto"' in line, f"the memo returns a list with no Auto option: {line.strip()!r}"+++# ── inference keeps NVFP4 ─────────────────────────────────────────────────────+++def test_inference_still_offers_nvfp4_end_to_end():+ """The training guard must not be "fixed" by deleting NVFP4 from inference, where it is a+ legitimate Blackwell option on both the image and the video load forms."""+ req = DiffusionLoadRequest(+ model_path = "unsloth/Z-Image-Turbo-GGUF",+ transformer_quant = "nvfp4",+ text_encoder_quant = "nvfp4",+ )+ assert req.transformer_quant == "nvfp4" and req.text_encoder_quant == "nvfp4"++ # The video load form too, through the schema rather than its source: video-page.tsx can+ # keep offering NVFP4 long after VideoLoadRequest stopped accepting it, and the only symptom+ # is a 422 from /video/load.+ video = VideoLoadRequest(model_path = "unsloth/Wan2.2-TI2V-5B", transformer_quant = "nvfp4")+ assert video.transformer_quant == "nvfp4"++ for rel in (+ ("features", "images", "images-page.tsx"),+ ("features", "video", "video-page.tsx"),+ ):+ src = (_FRONTEND.joinpath(*rel)).read_text(encoding = "utf-8")+ assert '["nvfp4", "NVFP4 (Blackwell)"]' in src, f"{rel[-1]} no longer offers NVFP4"+ exports = (_FRONTEND / "features" / "export" / "constants.ts").read_text(encoding = "utf-8")+ assert 'value: "nvfp4"' in exportsdiff --git a/studio/backend/tests/test_video_resolution_preset_contract.py b/studio/backend/tests/test_video_resolution_preset_contract.pynew file mode 100644index 00000000000..3aac0a44ce8--- /dev/null+++ b/studio/backend/tests/test_video_resolution_preset_contract.py@@ -0,0 +1,179 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Contract: every video resolution the UI offers is a real family preset, and vice versa.++The Video tab's Resolution select is populated from ``status.defaults.resolution_presets``,+which is ``VideoFamily.resolution_presets`` copied straight through+``video.py::status()`` -> ``VideoGenerationDefaults``. Before a model is loaded it falls back+to ``FALLBACK_RESOLUTION_PRESETS`` in ``video-page.tsx``. Two things have to hold:++ * the offline fallback names only sizes some family actually declares, so the first paint+ cannot offer a shape no checkpoint was trained at;+ * every family declares at least one preset, because ``video.py``'s generate path indexes+ ``fam.resolution_presets[0]`` unguarded when width/height are omitted -- an empty tuple+ there is an IndexError on the very first generate of that family.++Pure-module: no torch, no network, no browser. The frontend half reads the TSX source, the+same way the other cross-language contract checks in this suite do.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from core.inference.video_families import (+ detect_video_family,+ snap_video_size,+ supported_video_family_names,+)+from models.inference import VideoGenerationDefaults, VideoStatusResponse++_BACKEND = Path(__file__).resolve().parent.parent+_VIDEO_PAGE = _BACKEND.parent / "frontend" / "src" / "features" / "video" / "video-page.tsx"++_FAMILY_NAMES = supported_video_family_names()+++def _family(name: str):+ fam = detect_video_family("", override = name)+ assert fam is not None, f"{name} is listed but does not resolve"+ return fam+++def _all_presets() -> set[tuple[int, int]]:+ """Every (width, height) any family offers -- the domain the UI may draw from."""+ return {tuple(p) for name in _FAMILY_NAMES for p in _family(name).resolution_presets}+++# ── the family registry ───────────────────────────────────────────────────────+++def test_the_registry_is_not_empty():+ # Guards the parametrised cases below from silently covering nothing.+ assert len(_FAMILY_NAMES) >= 5++[email protected]("name", _FAMILY_NAMES)+def test_every_family_declares_at_least_one_resolution_preset(name):+ """``video.py`` resolves an omitted size with ``width or fam.resolution_presets[0][0]``.+ A family with an empty tuple would IndexError there instead of generating."""+ fam = _family(name)+ assert len(fam.resolution_presets) >= 1, (+ f"{name} declares no resolution presets; generate() indexes resolution_presets[0] "+ "unguarded when the request omits width/height, so this is an IndexError, and the "+ "UI's Resolution select would render empty"+ )+ # The unguarded index itself, exactly as the generate path performs it.+ assert fam.resolution_presets[0][0] > 0 and fam.resolution_presets[0][1] > 0++[email protected]("name", _FAMILY_NAMES)+def test_every_preset_survives_the_family_snap_unchanged(name):+ """A preset is what the UI sends verbatim, so it must already sit on the family's+ grid -- otherwise the clip comes back a different size than the one selected."""+ fam = _family(name)+ for width, height in fam.resolution_presets:+ assert isinstance(width, int) and isinstance(height, int)+ assert snap_video_size(fam, width, height) == (width, height), (+ f"{name} preset {width}x{height} is not a multiple of "+ f"resolution_multiple={fam.resolution_multiple}, so the pipeline floors it and the "+ "recorded size disagrees with the rendered clip"+ )++[email protected]("name", _FAMILY_NAMES)+def test_presets_are_unique_and_land_in_the_status_payload(name):+ """Through the real ``VideoBackend.status()``, not a hand-built VideoGenerationDefaults.++ Constructing the model here would assert only that Pydantic round-trips a list, and would+ stay green if status() ever hardcoded a preset list or stopped emitting the key at all --+ which is the loaded UI offering shapes the checkpoint was never trained at.+ """+ import core.inference.video as video_module++ fam = _family(name)+ presets = [tuple(p) for p in fam.resolution_presets]+ assert len(set(presets)) == len(presets), f"{name} repeats a preset: {presets}"++ backend = video_module.VideoBackend()+ backend._state = video_module._VideoLoadState(+ pipe = object(),+ family = fam,+ repo_id = f"unsloth/{name}",+ base_repo = fam.base_repo,+ device = "cpu",+ dtype = "bfloat16",+ kind = "pipeline",+ )+ # Through VideoStatusResponse, the model GET /video/status actually declares, not just the+ # inner VideoGenerationDefaults: the outer model dropping or renaming `defaults` leaves the+ # inner assertion perfectly happy while the browser receives no presets at all.+ wire = VideoStatusResponse(**backend.status()).model_dump()+ defaults_payload = wire.get("defaults")+ assert defaults_payload is not None, "the status response model no longer carries defaults"++ defaults = VideoGenerationDefaults(**defaults_payload)+ assert (+ [tuple(p) for p in defaults.resolution_presets] == presets+ ), f"{name}: status() serves {defaults.resolution_presets} but the family declares {presets}"+ assert defaults.frame_step == fam.frame_step+ assert defaults.resolution_multiple == fam.resolution_multiple+++# ── the frontend fallback ─────────────────────────────────────────────────────+++def _fallback_presets() -> list[tuple[int, int]]:+ """``FALLBACK_RESOLUTION_PRESETS`` from video-page.tsx."""+ src = _VIDEO_PAGE.read_text(encoding = "utf-8")+ start = src.index("const FALLBACK_RESOLUTION_PRESETS")+ body = src[start : src.index("];", start)]+ pairs = [(int(w), int(h)) for w, h in re.findall(r"\[\s*(\d+)\s*,\s*(\d+)\s*\]", body)]+ assert pairs, f"failed to parse FALLBACK_RESOLUTION_PRESETS out of {body!r}"+ return pairs+++def test_the_frontend_fallback_offers_only_real_family_presets():+ fallback = _fallback_presets()+ real = _all_presets()+ unknown = [p for p in fallback if p not in real]+ assert not unknown, (+ f"video-page.tsx offers {unknown} before a model is loaded, but no VideoFamily "+ "declares those sizes; a user who picks one gets a shape no checkpoint was trained at"+ )+++def test_the_frontend_fallback_is_a_usable_default_for_the_family_it_mirrors():+ """The fallback exists to populate the select on first paint, so it must be non-empty+ and its first entry must be some family's DEFAULT (presets[0]) -- the size the loader+ plans against -- not an arbitrary member of the union."""+ fallback = _fallback_presets()+ assert len(fallback) >= 1+ # An empty tuple is its own test above; skip it here so that failure is not double-reported.+ firsts = {+ tuple(fam.resolution_presets[0])+ for fam in (_family(name) for name in _FAMILY_NAMES)+ if fam.resolution_presets+ }+ assert (+ fallback[0] in firsts+ ), f"the fallback leads with {fallback[0]}, which is not the default preset of any family"+++def test_the_resolution_select_renders_the_backend_presets_not_a_hardcoded_list():+ """The select must map over the memo fed by ``status.defaults.resolution_presets``;+ if it were rebound to the fallback the backend's per-family list would never show."""+ src = _VIDEO_PAGE.read_text(encoding = "utf-8")+ memo = src[src.index("const resolutionPresets = useMemo<") :]+ memo = memo[: memo.index("\n }, [")]+ assert "status?.defaults?.resolution_presets" in memo+ assert "FALLBACK_RESOLUTION_PRESETS" in memo+ # Only the empty/absent case falls back.+ assert "presets && presets.length > 0" in memo+ assert "{resolutionPresets.map(([w, h], i) => (" in src+ # And the generate call sends the SELECTED preset, so the offered pair is the one rendered.+ assert "const preset = resolutionPresets[resolutionIdx] ?? resolutionPresets[0];" in src