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
Load the published Qwen-Image-2.1 INT8 checkpoint, and four more follow-ups (#11535)
Daniel Han67bc85754ead
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.pyindex 0e1e70c0014..6cdd8b2bfe5 100644--- a/studio/backend/core/inference/diffusion_cache.py+++ b/studio/backend/core/inference/diffusion_cache.py@@ -55,6 +55,64 @@ def normalize_transformer_cache(value: Optional[str]) -> Optional[str]:return normalized+# Block classes diffusers ships without first-block-cache metadata, and the metadata they want.+# The pair is (index of hidden_states in the block's return, index of encoder_hidden_states or None).+#+# Qwen-Image-2.1 is single stream: its block takes ``hidden_states, modulation, rotary_emb, ...``+# and returns the hidden states alone, so 0 / None. Without the entry ``enable_cache`` raises+# "Model class QwenImage21TransformerBlock not registered." and every load of the family renders+# uncached, which is the whole step-cache saving gone on a 20+ step model, silently.+_UNREGISTERED_BLOCK_METADATA: dict = {+ (+ "diffusers.models.transformers.transformer_qwenimage21",+ "QwenImage21TransformerBlock",+ ): (0, None),+}+++def register_unregistered_transformer_blocks(logger: Any = None) -> tuple:+ """Add our own first-block-cache metadata for block classes diffusers has not registered.++ Idempotent, best-effort, and never overwrites: a class diffusers registers later wins, since+ upstream's own metadata is authoritative and ours exists only to fill the gap until it lands.+ An import failure means that diffusers does not have the class at all, which is not an error+ here; the family simply is not installed.+ """+ added: list = []+ try:+ from diffusers.hooks._helpers import TransformerBlockMetadata, TransformerBlockRegistry+ except Exception: # noqa: BLE001 - an older diffusers has no registry to fill+ return ()+ for (module_name, class_name), (hidden_index, encoder_index) in (+ _UNREGISTERED_BLOCK_METADATA.items()+ ):+ try:+ import importlib+ block_cls = getattr(importlib.import_module(module_name), class_name, None)+ except Exception: # noqa: BLE001 - this diffusers does not ship the family+ continue+ if block_cls is None:+ continue+ try:+ TransformerBlockRegistry.get(block_cls)+ continue # already known, ours would be a downgrade+ except Exception: # noqa: BLE001 - "not registered" is the case we are here for+ pass+ try:+ TransformerBlockRegistry.register(+ model_class = block_cls,+ metadata = TransformerBlockMetadata(+ return_hidden_states_index = hidden_index,+ return_encoder_hidden_states_index = encoder_index,+ ),+ )+ added.append(class_name)+ except Exception as exc: # noqa: BLE001 - registration is an optimisation, never a gate+ if logger is not None:+ logger.debug("could not register %s for step caching: %s", class_name, exc)+ return tuple(added)++def _invalidate_child_registry_cache(transformer: Any) -> None:"""Drop the HookRegistry's cached child-registry list after (un)installing hooks.@@ -247,6 +305,8 @@ def apply_step_cache(transformer = getattr(pipe, "transformer", None)if transformer is None:return None+ # Before enable_cache, which is what raises on a block class the registry has never seen.+ register_unregistered_transformer_blocks(logger)thr = (thresholdif threshold is not Nonediff --git a/studio/backend/core/inference/prequant_safetensors.py b/studio/backend/core/inference/prequant_safetensors.pyindex 1cd5e613f6c..3eaeb79fc43 100644--- a/studio/backend/core/inference/prequant_safetensors.py+++ b/studio/backend/core/inference/prequant_safetensors.py@@ -47,6 +47,7 @@ a repo can host both and each build reads the one it understands.from __future__ import annotationsimport json+import refrom typing import Any, OptionalSAFETENSORS_SUFFIX = ".safetensors"@@ -55,6 +56,11 @@ SAFETENSORS_SUFFIX = ".safetensors"# with torchao's, which are ``tensor_names`` plus one key per tensor FQN.UNSLOTH_FORMAT_KEY = "unsloth_format"UNSLOTH_METADATA_KEY = "unsloth_metadata"+# Root-level PLAIN tensors, carried beside torchao's flat set rather than through it. Written under+# this prefix and listed under this header key, so the reader restores their bare names and torchao+# never sees a key it would try to rsplit on ".".+UNSLOTH_ROOT_PREFIX = "unsloth_root::"+UNSLOTH_ROOT_KEYS_KEY = "unsloth_root_tensors"# The torchao release that first shipped the flatten/unflatten pair under this import path. Below it# the helpers are absent and a safetensors artifact simply cannot be read, so the loader says so and@@ -128,16 +134,8 @@ def _first(value: Any) -> Any:return value[0] if isinstance(value, tuple) else value-def unsupported_state_dict_keys(state_dict: Any) -> list:- """Keys torchao's unflatten cannot round-trip: the ones with no ``.`` in them.-- ``unflatten_tensor_state_dict`` does ``tensor_name.rsplit(".", 1)`` to split a key into module- fqn and weight name, so a ROOT-level parameter or buffer (``pos_embed`` rather than- ``embed.weight``) raises ``ValueError: not enough values to unpack`` when the file is read back.- Saving one would produce an artifact that writes cleanly and can never be loaded, so the builder- refuses up front and says which keys are the problem. Every DiT Unsloth ships today is dotted- throughout; this exists so a future one fails at build time rather than in a user's loader.- """+def _root_level_keys(state_dict: Any) -> list:+ """Keys with no ``.`` in them, in the order the state dict gives them."""try:keys = list(state_dict.keys())except Exception: # noqa: BLE001 - not a mapping is the caller's problem, not this check's@@ -145,6 +143,29 @@ def unsupported_state_dict_keys(state_dict: Any) -> list:return [k for k in keys if "." not in str(k)]+def unsupported_state_dict_keys(state_dict: Any) -> list:+ """Root-level keys this container cannot round-trip: the QUANTIZED ones.++ ``unflatten_tensor_state_dict`` does ``tensor_name.rsplit(".", 1)`` to split a key into module+ fqn and weight name, so a root-level entry (``x_pad_token`` rather than ``embed.weight``) cannot+ go through torchao at all. Plain tensors do not need to: they are written beside the flat set+ under ``UNSLOTH_ROOT_PREFIX`` and restored on read, which is what z-image needs, since+ ``ZImageTransformer2DModel`` holds ``x_pad_token`` and ``cap_pad_token`` at the root and every+ safetensors build of it was refused after the download and the GPU quantization had finished.++ A root-level TENSOR SUBCLASS is still refused: reconstructing one is exactly the job of the+ flatten pair that cannot address it, so there is nothing to carry it in.+ """+ roots = _root_level_keys(state_dict)+ if not roots:+ return []+ try:+ import torch+ except Exception: # noqa: BLE001 - no torch means no way to tell the two apart; refuse as before+ return roots+ return [k for k in roots if type(state_dict[k]) is not torch.Tensor]++def save_prequant_safetensors(path: str, *, fmt: str, state_dict: Any, metadata: Any) -> None:"""Write ``state_dict`` (quantized, tensor subclasses and plain tensors alike) to ``path``.@@ -165,15 +186,20 @@ def save_prequant_safetensors(path: str, *, fmt: str, state_dict: Any, metadata:undotted = unsupported_state_dict_keys(state_dict)if undotted:raise ValueError(- "these state dict keys have no '.' and cannot be read back by torchao's unflatten, "- f"so a safetensors checkpoint carrying them would never load: {undotted[:8]}"+ "these state dict keys have no '.' and are not plain tensors, so torchao's unflatten "+ f"cannot address them and this checkpoint would never load: {undotted[:8]}"+ (f" (+{len(undotted) - 8} more)" if len(undotted) > 8 else "")+ ". Write this build as a .pt checkpoint instead.")+ # Root-level plain tensors go beside the flat set, not through it. Split BEFORE flatten so+ # torchao only ever sees dotted keys, and the pair stays exactly the one it supports.+ roots = _root_level_keys(state_dict)+ quantizable = {k: v for k, v in state_dict.items() if k not in set(roots)} if roots else state_dict+flatten, _ = helperstry:- flat, torchao_metadata = flatten(state_dict)+ flat, torchao_metadata = flatten(quantizable)except ValueError as exc:# Only the NEW torchao tensor subclasses can be flattened. The one that bites in practice is# int8: through torchao 0.17 ``Int8DynamicActivationInt8WeightConfig`` still produces the@@ -198,6 +224,13 @@ def save_prequant_safetensors(path: str, *, fmt: str, state_dict: Any, metadata:header = dict(torchao_metadata or {})header[UNSLOTH_FORMAT_KEY] = str(fmt)header[UNSLOTH_METADATA_KEY] = json.dumps(metadata or {}, default = str)+ if roots:+ flat = dict(flat)+ for key in roots:+ # ``contiguous`` because safetensors refuses a view, and a root buffer sliced out of a+ # larger allocation is exactly the shape that arrives as one.+ flat[f"{UNSLOTH_ROOT_PREFIX}{key}"] = state_dict[key].contiguous()+ header[UNSLOTH_ROOT_KEYS_KEY] = json.dumps([str(k) for k in roots])save_file(flat, path, metadata = header)@@ -226,6 +259,95 @@ def read_prequant_header(path: str) -> Optional[dict]:return {"format": str(fmt), "metadata": metadata}+# torchao reports a field its constructor will not take through this exact phrasing, wrapped in its+# own "Failed to create instance of <Class>" message.+_UNEXPECTED_KWARG = re.compile(r"unexpected keyword argument '([^']+)'")++# Values that mean "this field is not doing anything", so an older torchao that has never heard of+# the field behaves identically without it. Anything else is a real setting and must not be dropped.+_INERT_FIELD_VALUES = (False, None, 0)+++def _drop_field(value: Any, name: str, removed: list) -> Any:+ """``value`` with every nested occurrence of key ``name`` removed, recording what was dropped."""+ if isinstance(value, dict):+ out = {}+ for key, inner in value.items():+ if key == name:+ removed.append(inner)+ continue+ out[key] = _drop_field(inner, name, removed)+ return out+ if isinstance(value, list):+ return [_drop_field(v, name, removed) for v in value]+ return value+++def _header_without_unconstructible_fields(+ unflatten: Any, tensors: Any, raw: dict, *, path: str, attempts: int = 8+) -> dict:+ """``raw``, minus fields THIS torchao cannot construct, when dropping them changes nothing.++ torchao's tensor subclasses are reconstructed from their serialized dataclass kwargs, so a+ checkpoint written by a newer release carries fields an older constructor rejects outright:+ 0.18 added ``reduce_range`` to ``QuantizeTensorToInt8Kwargs``, and a 0.17 install answers the+ published Qwen-Image-2.1 int8 artifact with ``Failed to create instance of+ QuantizeTensorToInt8Kwargs: ... unexpected keyword argument 'reduce_range'``. The loader then+ reports no usable checkpoint and the dense bf16 denoiser is downloaded and quantized at runtime,+ which is the whole saving gone, for a field the file records as ``false``.++ Driven by the error rather than by a version table: the failure names the field, so only the+ field that actually blocks this install is touched, and a release that adds a different one is+ handled with no code change. A dropped field carrying a NON-default value is refused instead,+ since silently loading weights under settings the file did not ask for is worse than falling+ back. A dry run against ``unflatten`` is the only way to learn the name, and it is cheap: the+ constructor raises on the first tensor.+ """+ header = dict(raw)+ dropped: list = []+ for _ in range(attempts):+ try:+ unflatten(tensors, header)+ break+ except Exception as exc: # noqa: BLE001 - only the one shape below is acted on+ match = _UNEXPECTED_KWARG.search(str(exc))+ if match is None:+ break+ name = match.group(1)+ removed: list = []+ pruned = {}+ for key, value in header.items():+ if key in (UNSLOTH_FORMAT_KEY, UNSLOTH_METADATA_KEY, UNSLOTH_ROOT_KEYS_KEY):+ pruned[key] = value+ continue+ try:+ parsed = json.loads(value)+ except Exception: # noqa: BLE001 - not every header entry is JSON+ pruned[key] = value+ continue+ pruned[key] = json.dumps(_drop_field(parsed, name, removed))+ if not removed:+ break+ live = [v for v in removed if v not in _INERT_FIELD_VALUES]+ if live:+ raise ValueError(+ f"{path} records {name!r}={live[0]!r}, which this torchao "+ f"({_torchao_version() or 'unknown'}) cannot construct. Upgrade torchao to read "+ "this checkpoint; dropping the field would load the weights under settings the "+ "file did not ask for."+ ) from exc+ dropped.append(name)+ header = pruned+ if dropped:+ # Worth saying out loud: the artifact was built by a newer torchao than this one.+ print(+ f"note: {path} carries {', '.join(sorted(set(dropped)))} from a newer torchao; "+ f"the field is inert here and was ignored",+ flush = True,+ )+ return header++def load_prequant_safetensors(path: str, *, device: str = "cpu") -> dict:"""Read ``path`` into the SAME dict shape the pickle path returns.@@ -257,6 +379,18 @@ def load_prequant_safetensors(path: str, *, device: str = "cpu") -> dict:)metadata = json.loads(raw.get(UNSLOTH_METADATA_KEY) or "{}")+ # Lifted out BEFORE unflatten: torchao would rsplit these on "." and fail, and they are plain+ # tensors that never needed it. Keyed off the prefix rather than the header list, so a file+ # written by a build that recorded one and not the other still reads; the list is the order.+ roots = {+ key[len(UNSLOTH_ROOT_PREFIX):]: tensors.pop(key)+ for key in [k for k in tensors if k.startswith(UNSLOTH_ROOT_PREFIX)]+ }++ # A newer torchao can record a field an older one's constructor does not take, which is how a+ # published int8 checkpoint stopped loading. Dropped here when it is inert; see the helper.+ raw = _header_without_unconstructible_fields(unflatten, tensors, raw, path = path)+# torchao reads its OWN keys out of the same header; ours are namespaced and simply ignored. The second element# is what it could NOT account for: a subclass missing one of its parts (a truncated or hand-edited file) is# skipped there rather than raised, which would reach load_state_dict as a bare missing-key error saying nothing@@ -269,6 +403,10 @@ def load_prequant_safetensors(path: str, *, device: str = "cpu") -> dict:f"{path} has {len(leftover)} tensor(s) its header does not account for "f"(e.g. {sorted(leftover)[0]!r}); the checkpoint is incomplete or was edited")+ if roots:+ # Back under their bare names, so the caller's load_state_dict sees the shape the model+ # declares. A dotted key can never collide with one of these.+ state_dict.update(roots)return {"format": str(fmt), "state_dict": state_dict, "metadata": metadata}diff --git a/studio/backend/core/inference/sd_cpp_backend.py b/studio/backend/core/inference/sd_cpp_backend.pyindex e43418a884a..68e93214f53 100644--- a/studio/backend/core/inference/sd_cpp_backend.py+++ b/studio/backend/core/inference/sd_cpp_backend.py@@ -2050,6 +2050,17 @@ class SdCppDiffusionBackend:# Class-level defaults so an instance built with ``__new__`` answers before any load ran._loading_cards = None_committed_loading_card: Optional[str] = None+ # The family this backend is loading, kept so the executable checks below can ask whether the+ # build they just resolved implements it. The router's answer does not travel: it clears its own+ # local variables, and this class resolves sd-server and sd-cli again, independently, and can+ # end up on the OTHER one when a server fails to start.+ #+ # Thread-local for the same reason as _loading_card: begin_load sets it BEFORE taking _lock to+ # reject a concurrent load, so on shared state a request that is refused a line later would+ # still have replaced the family the running worker validates its binaries against, and refuse+ # a good build or accept an incapable one. Class-level default answers before any load ran.+ _loading_families = None+ _loading_family_default: Any = Nonedef __init__(self, engine: Optional[SdCppEngine] = None) -> None:self._lock = threading.Lock()@@ -2115,6 +2126,27 @@ class SdCppDiffusionBackend:except AttributeError:pass+ def _loading_family_store(self) -> threading.local:+ """Lazily, so an instance built with ``__new__`` (the unit-test seam) still answers."""+ store = getattr(self, "_loading_families", None)+ if store is None:+ store = threading.local()+ self._loading_families = store+ return store++ @property+ def _loading_family(self) -> Any:+ """The family THIS worker is loading. Off a load thread, the last one begun."""+ return getattr(self._loading_family_store(), "family", self._loading_family_default)++ @_loading_family.setter+ def _loading_family(self, value: Any) -> None:+ self._loading_family_store().family = value+ # Per-INSTANCE (shadows the class default), for an off-thread reader that never ran+ # begin_load. A rejected concurrent load can still move this one, which is why the worker+ # reads its thread-local first and never this.+ self._loading_family_default = value+def _reserve_stop(self, count: int = 1) -> None:"""Claim ``count`` pending stops. MUST be called under ``_lock`` in the same block thatunpublishes the servers: incrementing afterwards leaves a gap in which _state,@@ -2154,6 +2186,15 @@ class SdCppDiffusionBackend:def _resolve_engine(self) -> SdCppEngine:"""The SdCppEngine, installing the binary on first use. Raises if unusable."""if self._engine is not None and self._engine.is_available():+ # Checked on the CACHED engine too. It outlives the load that resolved it (nothing ever+ # clears _engine), so an sd-cli cached by an older family's one-shot load would other-+ # wise be committed for a family it cannot run and die on the first generation, which+ # is the failure this gate exists to prevent. Only when it names a path: an engine with+ # no binary is the injected test seam, and a None there reads as "carries no marker"+ # and would refuse every marked family.+ cached_binary = getattr(self._engine, "binary", None)+ if cached_binary:+ self._refuse_incapable_build(cached_binary, "sd-cli")return self._engine# The accelerator this host resolves to, never the "cpu" default: this is also the one-shot FALLBACK path (a# GPU sd-server that would not start lands here), and asking for the CPU build there would reinstall the plain@@ -2164,9 +2205,29 @@ class SdCppDiffusionBackend:)if not binary:raise RuntimeError("sd-cli (stable-diffusion.cpp) binary is unavailable.")+ self._refuse_incapable_build(binary, "sd-cli")self._engine = SdCppEngine(binary = binary)return self._engine+ def _refuse_incapable_build(self, binary: Optional[str], name: str) -> None:+ """Raise when ``binary`` does not implement the family being loaded.++ The router drops an incapable build before choosing native, but its verdict is local to that+ call: this class resolves both executables again, and the two can be DIFFERENT builds+ (separate SD_SERVER_PATH / SD_CLI_PATH, or a partially upgraded tree). A current server that+ fails to start then falls through to a pre-Qwen-2.1 sd-cli, which the router never approved.+ Failing the load here is the point: the alternative is a one-shot backend that reports ready+ and dies on the first generation.+ """+ fam = self._loading_family+ if fam is None or sd_cpp_binary_runs_family(binary, fam):+ return+ raise RuntimeError(+ f"the {name} build at {binary} predates {getattr(fam, 'name', 'this model')} support. "+ "Reinstall the native engine (delete the managed stable-diffusion.cpp install, or point "+ "SD_CLI_PATH / SD_SERVER_PATH at a build from after upstream added it)."+ )+def _resolve_backend(self) -> tuple[str, Optional[str], Optional[SdCppEngine]]:"""Pick the native execution mode: ("server", binary, None) or ("oneshot", None, engine).The persistent ``sd-server`` is preferred (load once, serve many); the one-shot@@ -2189,6 +2250,17 @@ class SdCppDiffusionBackend:server_binary = ensure_sd_server_binary(allow_install = _install_allowed() and not upgrade_pending, accelerator = accelerator)+ if server_binary is not None and not sd_cpp_binary_runs_family(+ server_binary, self._loading_family+ ) and self._loading_family is not None:+ # Not fatal on its own: the one-shot path resolves its own binary, which may well be a+ # newer build, and _resolve_engine refuses it if it is not.+ logger.warning(+ "sd-server at %s predates %s support; trying the one-shot sd-cli instead",+ server_binary,+ getattr(self._loading_family, "name", "this model"),+ )+ server_binary = Noneif server_binary is not None:return "server", server_binary, Nonelogger.warning(@@ -2303,6 +2375,7 @@ class SdCppDiffusionBackend:)if not family_sd_cpp_supported(fam):raise ValueError(f"Family '{fam.name}' has no native sd.cpp asset mapping.")+ self._loading_family = fambase = resolve_base_repo(fam, base_repo)# Offline-only here, deliberately: begin_load returns at once by contractdiff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex d2c9daafb1e..c553e08e3ba 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -2979,7 +2979,37 @@ class VideoBackend:return Trueif isinstance(exc, LocalEntryNotFoundError):return bool(local_files_only)- return isinstance(exc, EntryNotFoundError)+ if isinstance(exc, EntryNotFoundError):+ return True+ return VideoBackend._te_fetch_miss_by_name(exc, local_files_only = local_files_only)++ # Class names the xet fallback can only hand back as TEXT. Matched on the whole leading token,+ # so "LocalEntryNotFoundError" is never read as the remote one by a substring test.+ _REMOTE_MISS_NAMES = frozenset({"EntryNotFoundError", "RemoteEntryNotFoundError"})+ _LOCAL_MISS_NAMES = frozenset({"LocalEntryNotFoundError"})++ @staticmethod+ def _te_fetch_miss_by_name(exc: BaseException, *, local_files_only: bool) -> bool:+ """The same verdict for an exception whose TYPE did not survive the download.++ ``hf_hub_download_with_xet_fallback`` runs the fetch in a child process and re-raises by+ class name, and ``unsloth_zoo`` only preserves the names it knows: huggingface_hub 1.x+ raises ``RemoteEntryNotFoundError`` for a 404, which is not on that list, so the parent sees+ a bare ``RuntimeError`` reading ``"RemoteEntryNotFoundError: 404 ..."``. Without this a+ 404 on the preferred safetensors name stops the walk, every ``.pt``-only repo keeps its+ dense encoder in the base download and then fetches the ``.pt`` on top of it, which is the+ double download the candidate list exists to avoid.++ Deliberately narrow: only a RuntimeError whose message BEGINS with one of those class names,+ which is the exact shape ``_raise_child_error`` produces.+ """+ if not isinstance(exc, RuntimeError):+ return False+ message = str(exc)+ name = message.split(":", 1)[0].strip() if ":" in message else ""+ if name in VideoBackend._LOCAL_MISS_NAMES:+ return bool(local_files_only)+ return name in VideoBackend._REMOTE_MISS_NAMES@staticmethoddef _base_download_files(diff --git a/studio/backend/tests/test_diffusion_cache_block_registry.py b/studio/backend/tests/test_diffusion_cache_block_registry.pynew file mode 100644index 00000000000..96aabf1cd06--- /dev/null+++ b/studio/backend/tests/test_diffusion_cache_block_registry.py@@ -0,0 +1,60 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""First-block-cache metadata Unsloth registers for blocks diffusers has not.++Separate from ``test_diffusion_cache.py``, which stubs ``diffusers`` through ``sys.modules``: this+one needs the REAL registry, since the thing under test is whether a class the installed diffusers+ships is known to it.+"""++from __future__ import annotations++import pytest++from core.inference import diffusion_cache as dc+++def _registry_and_block():+ """The real registry plus the 2.1 block, or a skip.++ ``importorskip`` is not enough: importing diffusers drags in optional integrations, and a host+ whose bitsandbytes cannot find CUDA raises RuntimeError rather than ImportError. That is an+ environment fact, not a result.+ """+ try:+ from diffusers.hooks._helpers import TransformerBlockRegistry+ from diffusers.models.transformers.transformer_qwenimage21 import (+ QwenImage21TransformerBlock,+ )+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"diffusers is not importable here: {type(exc).__name__}")+ return TransformerBlockRegistry, QwenImage21TransformerBlock+++def test_the_qwen_image_21_block_is_registered_for_step_caching():+ """diffusers ships no metadata for ``QwenImage21TransformerBlock``, so ``enable_cache`` raised+ "Model class ... not registered." and every load of the family rendered uncached, which is the+ whole step-cache saving gone on a 20+ step model and only visible in a log line.++ The block is single stream: it takes ``hidden_states, modulation, rotary_emb, ...`` and returns+ the hidden states alone, hence 0 and None.+ """+ registry, block = _registry_and_block()++ dc.register_unregistered_transformer_blocks()+ meta = registry.get(block)+ assert meta.return_hidden_states_index == 0+ assert meta.return_encoder_hidden_states_index is None+++def test_registration_is_idempotent_and_never_overwrites_diffusers_own():+ """Upstream's metadata is authoritative; ours fills a gap until it lands, so a class diffusers+ registers itself must be left exactly as it is, however many times this runs."""+ registry, _ = _registry_and_block()+ from diffusers.models.transformers.transformer_qwenimage import QwenImageTransformerBlock++ dc.register_unregistered_transformer_blocks()+ before = registry.get(QwenImageTransformerBlock)+ dc.register_unregistered_transformer_blocks()+ assert registry.get(QwenImageTransformerBlock) is beforediff --git a/studio/backend/tests/test_prequant_safetensors.py b/studio/backend/tests/test_prequant_safetensors.pyindex 1a0f0a0d2a2..a0582baa823 100644--- a/studio/backend/tests/test_prequant_safetensors.py+++ b/studio/backend/tests/test_prequant_safetensors.py@@ -417,3 +417,100 @@ def test_the_real_installed_torchao_answers_the_int8_question(monkeypatch):assert answer is False, f"torchao {torchao.__version__} should refuse int8 flatten"else:assert answer is not False, f"torchao {torchao.__version__} should flatten int8"+++# ── root-level plain tensors ─────────────────────────────────────────────────+++def test_a_root_level_plain_tensor_round_trips_instead_of_failing_the_build(tmp_path):+ """z-image is not hypothetical: ``ZImageTransformer2DModel`` holds ``x_pad_token`` and+ ``cap_pad_token`` at the root, so refusing every undotted key refused the only safetensors build+ of a family this repo ships, and it did so AFTER the download and the GPU quantization.++ torchao still never sees them: they are split out before flatten and restored after unflatten.+ """+ torch = pytest.importorskip("torch")+ if not ps.safetensors_prequant_supported():+ pytest.skip("this install cannot write safetensors pre-quant checkpoints")++ state = {+ "blocks.0.linear.weight": torch.arange(16, dtype = torch.float32).reshape(4, 4),+ "x_pad_token": torch.tensor([1.0, 2.0, 3.0]),+ "cap_pad_token": torch.tensor([[4.0, 5.0]]),+ }+ assert ps.unsupported_state_dict_keys(state) == []++ path = str(tmp_path / "roots.safetensors")+ ps.save_prequant_safetensors(path, fmt = "fp8", state_dict = state, metadata = {"scheme": "fp8"})+ back = ps.load_prequant_safetensors(path)["state_dict"]++ assert set(back) == set(state)+ for key, value in state.items():+ assert torch.equal(back[key], value), key+++def test_a_root_level_tensor_subclass_is_still_refused_up_front(monkeypatch):+ """The carry-alongside trick only works for PLAIN tensors: reconstructing a subclass is exactly+ the job of the flatten pair that cannot address a root key, so there is nothing to put it in."""+ torch = pytest.importorskip("torch")++ class _Subclass(torch.Tensor):+ pass++ state = {+ "blocks.0.linear.weight": torch.zeros(2, 2),+ "quantized_root": _Subclass(torch.zeros(2)),+ }+ assert ps.unsupported_state_dict_keys(state) == ["quantized_root"]+++# ── a checkpoint written by a NEWER torchao ──────────────────────────────────+++def test_a_field_a_newer_torchao_added_is_dropped_when_it_is_inert(monkeypatch):+ """The live regression: torchao 0.18 records ``reduce_range`` in+ ``QuantizeTensorToInt8Kwargs``, 0.17's constructor refuses it, and the published+ Qwen-Image-2.1 int8 checkpoint therefore failed to load on a stock install with+ ``Failed to create instance of QuantizeTensorToInt8Kwargs: ... unexpected keyword argument+ 'reduce_range'``. The loader reported no usable checkpoint, and the dense bf16 denoiser was+ downloaded and quantized at runtime instead, which is the entire saving gone for a field the+ file records as false.+ """+ calls: list = []++ def _unflatten(tensors, header):+ calls.append(header)+ if "reduce_range" in header["w.weight"]:+ raise ValueError(+ "Failed to create instance of QuantizeTensorToInt8Kwargs: "+ "QuantizeTensorToInt8Kwargs.__init__() got an unexpected keyword argument "+ "'reduce_range'"+ )+ return {"w.weight": object()}, {}++ header = {+ "w.weight": json.dumps({"_type": "Int8Tensor", "_data": {"reduce_range": False,+ "block_size": [1, 4]}}),+ ps.UNSLOTH_FORMAT_KEY: "fp8_v1",+ }+ pruned = ps._header_without_unconstructible_fields(+ _unflatten, {}, header, path = "artifact.safetensors"+ )+ assert "reduce_range" not in pruned["w.weight"]+ # The rest of the description survives, and our own header keys are never parsed as torchao's.+ assert json.loads(pruned["w.weight"])["_data"]["block_size"] == [1, 4]+ assert pruned[ps.UNSLOTH_FORMAT_KEY] == "fp8_v1"+ assert len(calls) == 2 # the failing probe, then the retry that succeeded+++def test_a_field_carrying_a_real_setting_is_refused_rather_than_dropped():+ """Dropping a field that is doing something would load the weights under settings the file did+ not ask for. A refusal keeps the dense fallback, which is merely slower."""+ def _unflatten(tensors, header):+ raise ValueError("unexpected keyword argument 'reduce_range'")++ header = {"w.weight": json.dumps({"_data": {"reduce_range": True}})}+ with pytest.raises(ValueError, match = "reduce_range"):+ ps._header_without_unconstructible_fields(+ _unflatten, {}, header, path = "artifact.safetensors"+ )diff --git a/studio/backend/tests/test_sd_cpp_backend.py b/studio/backend/tests/test_sd_cpp_backend.pyindex 0f485745692..b84d3dcdc1d 100644--- a/studio/backend/tests/test_sd_cpp_backend.py+++ b/studio/backend/tests/test_sd_cpp_backend.py@@ -2467,3 +2467,45 @@ def test_the_scan_is_redone_when_the_binary_on_that_path_changes(tmp_path):assert bk.binary_carries_marker(str(path), "qwen_image_2_1") is Falsepath.write_bytes(b"a new build with qwen_image_2_1 in it")assert bk.binary_carries_marker(str(path), "qwen_image_2_1") is True+++def test_a_cached_engine_is_re_checked_against_the_family_now_loading(tmp_path):+ # _engine is resolved lazily and never cleared, so it outlives the load that created it. An+ # sd-cli cached by an older family's one-shot load would otherwise be handed straight back for+ # a family it cannot run, and the load would report ready and die on the first generation,+ # which is the failure the gate exists to prevent.+ old = tmp_path / "sd-cli-old"+ old.write_bytes(b"a build from before the family landed")+ backend = SdCppDiffusionBackend.__new__(SdCppDiffusionBackend)+ backend._engine = types.SimpleNamespace(binary = str(old), is_available = lambda: True)+ backend._engine_injected = False++ # A family the cached build does carry is still served from the cache, unchanged.+ backend._loading_family = detect_family("z-image")+ assert backend._resolve_engine() is backend._engine++ backend._loading_family = detect_family("qwen-image-2.1")+ with pytest.raises(RuntimeError, match = "predates qwen-image-2.1 support"):+ backend._resolve_engine()+++def test_a_rejected_concurrent_load_cannot_move_the_family_the_worker_validates_against():+ # begin_load assigns the family BEFORE taking _lock to refuse a second load, so on shared state+ # a request refused a line later would still have replaced the family the running worker checks+ # its binaries against, and could refuse a good build or accept an incapable one.+ backend = SdCppDiffusionBackend.__new__(SdCppDiffusionBackend)+ worker_family = detect_family("qwen-image-2.1")+ backend._loading_family = worker_family+ seen = {}+ started = threading.Event()++ def _other_request():+ backend._loading_family = detect_family("z-image")+ started.set()++ other = threading.Thread(target = _other_request)+ other.start()+ started.wait(timeout = 5)+ other.join(timeout = 5)+ seen["worker"] = backend._loading_family+ assert seen["worker"] is worker_family, "another thread's family reached this worker"