Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(models): decide FP8 Storage support in one place, on the loader's own key
Alexander Eichhorna73d191ff2ec
diff --git a/invokeai/backend/model_manager/load/fp8_capability.py b/invokeai/backend/model_manager/load/fp8_capability.pynew file mode 100644index 0000000000..4e36a5aa31--- /dev/null+++ b/invokeai/backend/model_manager/load/fp8_capability.py@@ -0,0 +1,248 @@+"""Whether FP8 Storage does anything for a given kind of model, decided in one place.++The toggle was offered for every `main`, `controlnet` and `t2i_adapter` record, and honoured by+whichever loader happened to call the cast. Those are two different questions, and collapsing them+produced a control that changes nothing for 19 of the 52 loader keys it is shown for -- no crash, no+log line, just the same memory as before. Worse, identification *enables* it on its own for any+checkpoint whose denoiser stores float8 (`configs/factory.py`), so a Wan fp8 install used to record+`fp8_storage: true` and then load at bf16 size anyway.++Three things have to be true, and each is owned by a different piece of the system:++- **the model kind** -- only a model run as its own forward pass has anywhere to put the hooks, and+ only three types carry the setting at all (`FP8_STORAGE_MODEL_TYPES`);+- **the format** -- an already-quantized payload must never be re-encoded (`QUANTIZED_MODEL_FORMATS`);+- **the loader** -- it has to implement the cast, which it declares at registration.++The first two are policy and stay here. The third is a capability, so it is keyed the way loaders are+keyed -- `(base, type, format)`, `ModelLoaderRegistry`'s own key. That key is what a per-architecture+field cannot express: FLUX main casts and FLUX ControlNet does not, and both are `flux`.++`fp8_storage_verdict` composes all three, and everything that needs the answer calls it: the loader+gate (`ModelLoader._should_use_fp8`), identification (so it stops enabling what will not run), and+the API row a client reads. Shipping the three inputs separately would invite the next client to+rebuild the composition, differently.++**Not here: whether the device can do it.** `_device_supports_fp8_storage` probes the torch device+and is deliberately the last thing `_should_use_fp8` asks, so the probe never runs on an API or+install thread. It is an environment fact rather than a fact about the model, and folding it in would+put a device probe behind an HTTP handler.++**Not here: `fp8_compute`.** Keeping a checkpoint's weights packed for `_scaled_mm` is a second axis,+and nothing offers it as a control -- `should_keep_fp8_weights` reads the device. A served field+nobody reads is a contract nobody checks, so it is left until something asks.+"""++from collections.abc import Mapping+from dataclasses import dataclass+from types import MappingProxyType+from typing import TypeAlias++from pydantic import BaseModel, Field++from invokeai.backend.model_manager.taxonomy import (+ QUANTIZED_MODEL_FORMATS,+ BaseModelType,+ ModelFormat,+ ModelType,+)+++@dataclass(frozen=True)+class NotApplicable:+ """This loader will never implement the cast, and that is the right answer.++ An adapter too small for the saving to matter, or weights that are already one byte each.+ """++ reason: str+++@dataclass(frozen=True)+class Unimplemented:+ """This loader could implement the cast and does not yet. A backlog entry, not a decision.++ Kept apart from `NotApplicable` so the gap is queryable -- filter `declared_fp8_storage()` for+ this class and you have the list, which shrinks in the code rather than ageing inside a planning+ document. Both markers hide the control identically; the distinction is for us, not the client.+ """++ reason: str+++Fp8StorageDeclaration: TypeAlias = NotApplicable | Unimplemented | None+"""What a loader says about FP8 Storage at registration. `None` means "implemented"."""+++FP8_STORAGE_MODEL_TYPES: frozenset[ModelType] = frozenset(+ {+ ModelType.Main,+ ModelType.ControlNet,+ ModelType.T2IAdapter,+ }+)+"""The model types FP8 Storage can reach, which is also the set whose settings carry the field.++Everything else is excluded for one of two reasons, and `test_fp8_capability.py` checks that the set+still matches the config schemas rather than trusting this comment:++- it has no `fp8_storage` in its default settings, so nothing can ask (VAE, LoRA, IP-Adapter, the+ encoders, ...). A VAE would be excluded anyway: fp8 storage degrades its decode visibly, which is+ why `_FP8_EXCLUDED_SUBMODEL_TYPES` also keeps it out of a pipeline's cast;+- it carries the field but is never run as its own forward pass. `ControlLoRa` shares+ `ControlAdapterDefaultSettings` with the control adapters, and is patched into a base model, so+ layerwise-casting hooks on it would never fire.+"""+++@dataclass(frozen=True)+class Fp8StorageVerdict:+ """Whether the setting can do anything here, and what to say when it cannot."""++ supported: bool+ reason: str | None = None+ """Why not. `None` exactly when `supported`."""+++class Fp8StorageSupport(BaseModel):+ """One row of the served table: a loader key and the finished answer.++ The reason is not served. Both markers hide the control identically, so a client has nothing to+ do with the difference; it stays in the declaration, where the backlog lives.+ """++ base: BaseModelType+ type: ModelType+ format: ModelFormat+ supported: bool = Field(description="Whether FP8 Storage changes anything for a model of this kind.")+++_declared: dict[tuple[BaseModelType, ModelType, ModelFormat], Fp8StorageDeclaration] = {}+"""Every registered loader key, with what it declared. Written by `ModelLoaderRegistry.register`.++Holding *every* key, including the implemented ones whose value is `None`, is what lets this module+serve the table without importing the registry back -- and the registry is the one thing that knows+which keys exist.+"""+++def declare_fp8_storage(+ base: BaseModelType,+ type: ModelType,+ format: ModelFormat,+ declaration: Fp8StorageDeclaration,+) -> None:+ """Record what a loader declared. Called once per registration, including for `None`."""+ _declared[(base, type, format)] = declaration+++def _ensure_loaders_registered() -> None:+ """Import the loader modules, and refuse to answer from an empty table.++ The import is function-local because `model_loader_registry` imports this module and the reverse+ edge at module scope would close a cycle. It is also nearly always a no-op: this module lives+ *inside* the package it imports, so anything that can call this has already run+ `load/__init__.py`, which globs `model_loaders/*.py`. It is kept for the one caller that reaches+ here through `configs.factory` rather than through the package, and because it states the+ dependency.++ The check is the part that earns its place. There is exactly one window where `_declared` is+ incomplete -- a re-entrant read from inside `load/__init__.py`, where the import above is a+ `sys.modules` hit on the half-built package -- and in that window every lookup would answer "no+ loader is registered", which is indistinguishable from the truthful answer for an unregistered+ key. Failing loudly is the only way that stays visible.+ """+ import invokeai.backend.model_manager.load # noqa: F401 (its __init__ globs model_loaders/*.py)++ if not _declared:+ raise RuntimeError(+ "No model loaders have registered, so FP8 Storage support cannot be decided. This means "+ "`fp8_capability` was read while `invokeai.backend.model_manager.load` was still importing."+ )+++def fp8_storage_verdict(base: BaseModelType, type: ModelType, format: ModelFormat) -> Fp8StorageVerdict:+ """Whether FP8 Storage would change anything for a model of this kind.++ Ordered so the reported reason is the most fundamental one: a GGUF ControlLoRa is refused for+ being patched in, not for being packed. An unregistered key answers no -- nothing can load it.+ """+ if type not in FP8_STORAGE_MODEL_TYPES:+ # Deliberately one sentence for the whole set rather than a per-type explanation: the grounds+ # differ (a VAE is excluded because fp8 visibly degrades decode, a LoRA because it is patched+ # into a base model and the hooks would never fire, everything else because it carries no such+ # setting), and a single invented reason would be wrong about most of them. The grounds are in+ # `FP8_STORAGE_MODEL_TYPES`, where they can be read next to the set they justify.+ return Fp8StorageVerdict(+ supported=False,+ reason=f"FP8 Storage is not offered for {type.value} models.",+ )++ # Their weights are packed integer payloads, not values anything may re-encode, and casting them+ # is not a no-op: GGUF raises `Operation changed the dtype of GGMLTensor unexpectedly`, while bnb+ # NF4 corrupts *silently* -- `bnb.nn.LinearNF4` subclasses `nn.Linear`, so the packed uint8+ # payload is cast to float8, inference still returns finite numbers, and the model produces+ # garbage. No quantized-format loader implements the cast, so this stays a rule rather than a+ # per-loader declaration: it holds for the next one too.+ if format in QUANTIZED_MODEL_FORMATS:+ return Fp8StorageVerdict(+ supported=False,+ reason=(+ f"{format.value} weights are already a packed quantized payload, which FP8 Storage must not re-encode."+ ),+ )++ _ensure_loaders_registered()+ # Exact key first, then the `Any`-base one, exactly as `ModelLoaderRegistry.get_implementation`+ # resolves a loader. Without the fallback every T2I adapter answers "no loader registered": they are+ # served by `GenericDiffusersLoader` under `any/t2i_adapter/diffusers`, and no record carries `any`+ # as its own base.+ for key in ((base, type, format), (BaseModelType.Any, type, format)):+ if key in _declared:+ declaration = _declared[key]+ if declaration is None:+ return Fp8StorageVerdict(supported=True)+ return Fp8StorageVerdict(supported=False, reason=declaration.reason)++ return Fp8StorageVerdict(+ supported=False,+ reason=f"No loader is registered for {base.value}/{type.value}/{format.value}.",+ )+++def fp8_storage_support() -> list[Fp8StorageSupport]:+ """The table a client joins against its model records, sorted so the response is diffable.++ Only the three types that can carry the setting get a row; for anything else the answer is no+ without a loader having to say so, and a row would be a field nobody reads.++ A row whose base is `any` is a wildcard registration, and a client has to resolve it the way the+ registry does: exact `(base, type, format)` first, then `(any, type, format)`. It is served as the+ wildcard rather than expanded over every base because most bases have no such model, and a row per+ base would invent twenty answers to hold one. A key that matches neither is not supported -- which is+ also what `fp8_storage_verdict` concludes for it.+ """+ _ensure_loaders_registered()+ rows = [+ Fp8StorageSupport(+ base=base,+ type=type,+ format=format,+ supported=fp8_storage_verdict(base, type, format).supported,+ )+ for (base, type, format) in _declared+ if type in FP8_STORAGE_MODEL_TYPES+ ]+ return sorted(rows, key=lambda row: (row.type.value, row.base.value, row.format.value))+++def declared_fp8_storage() -> Mapping[tuple[BaseModelType, ModelType, ModelFormat], Fp8StorageDeclaration]:+ """Every registered loader key and what it declared, read-only.++ This is where §6's "5 of 20" lives now: filtering for `Unimplemented` is the backlog, as a query+ rather than a number in a document. Exposed rather than left private because the count is meant+ to be asked for -- by the test that keeps the declarations honest, and by anyone wondering what+ is left.+ """+ _ensure_loaders_registered()+ return MappingProxyType(_declared)diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex 3d1f9e45dc..533283be11 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -13,6 +13,7 @@ import torchfrom invokeai.app.services.config import InvokeAIAppConfigfrom invokeai.backend.model_manager.configs.base import Diffusers_Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfig+from invokeai.backend.model_manager.load.fp8_capability import fp8_storage_verdictfrom invokeai.backend.model_manager.load.load_base import LoadedModel, ModelLoaderBasefrom invokeai.backend.model_manager.load.memory_snapshot import GB, MemorySnapshotfrom invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecord@@ -25,7 +26,6 @@ from invokeai.backend.model_manager.load.model_cache.model_cache import (from invokeai.backend.model_manager.load.model_util import calc_model_size_by_fsfrom invokeai.backend.model_manager.load.optimizations import skip_torch_weight_initfrom invokeai.backend.model_manager.taxonomy import (- QUANTIZED_MODEL_FORMATS,AnyModel,SubModelType,)@@ -44,6 +44,33 @@ _FP8_STORAGE_SUPPORTED: set[str] = set()# the warning on every model load would bury the log._FP8_PROBE_FAILURE_REPORTED: set[str] = set()+# Components FP8 storage is never applied to, whatever the model asks for.+#+# The prompt enhancer is a causal LM run autoregressively (one full forward per generated token), so+# layerwise casting would pay the bf16<->fp8 round trip on every token — and its entire job is text+# quality, which fp8 rounding degrades. Its tokenizer is listed for symmetry (it is not an nn.Module,+# so casting is a no-op today only by accident).+#+# Unlike the model-kind rules in `fp8_capability.py`, these are about which *component* of a model is+# being loaded, which no client can see and nothing outside this file asks about.+_FP8_EXCLUDED_SUBMODEL_TYPES: frozenset[SubModelType] = frozenset(+ {+ SubModelType.TextEncoder,+ SubModelType.TextEncoder2,+ SubModelType.TextEncoder3,+ SubModelType.Tokenizer,+ SubModelType.Tokenizer2,+ SubModelType.Tokenizer3,+ SubModelType.PromptEnhancer,+ SubModelType.PromptEnhancerTokenizer,+ SubModelType.Scheduler,+ SubModelType.SafetyChecker,+ SubModelType.VAE,+ SubModelType.VAEDecoder,+ SubModelType.VAEEncoder,+ }+)+def put_in_eval_mode(model: AnyModel) -> AnyModel:"""Put a freshly constructed model into inference mode.@@ -332,6 +359,7 @@ class ModelLoader(ModelLoaderBase):passconfig.path = str(self._get_model_path(config))+ self._report_inert_fp8_request(config, submodel_type)# Fast path (multi-GPU): if another device already loaded this exact model, its canonical# CPU weights are still resident in the shared store along with an empty (meta-weight)@@ -425,66 +453,57 @@ class ModelLoader(ModelLoaderBase):variant=config.repo_variant if isinstance(config, Diffusers_Config_Base) else None,)+ @staticmethod+ def _fp8_storage_asked_for(config: AnyModelConfig, submodel_type: Optional[SubModelType]) -> bool:+ """Whether this record asks for FP8 Storage on a component that could take it.++ The half of the gate that is about the *request* rather than about the model kind or the+ device. Shared with `_report_inert_fp8_request`, which has to ask the same question from the+ other side: restating it there is how two answers drift apart, which is the defect this whole+ change is about.++ `getattr`, because `AnyModelConfig` is a union and only some members carry default settings.+ Text encoders, tokenizers, schedulers and VAEs never take the cast whatever the record says.+ """+ if submodel_type in _FP8_EXCLUDED_SUBMODEL_TYPES:+ return False+ return getattr(getattr(config, "default_settings", None), "fp8_storage", None) is True+def _should_use_fp8(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> bool:"""Check if FP8 layerwise casting should be applied to a model."""- from invokeai.backend.model_manager.taxonomy import ModelType-- # Already-quantized models are excluded. Their weights are packed integer payloads, not- # values we may re-encode, and casting them is not a no-op:- # - GGUF raises `Operation changed the dtype of GGMLTensor unexpectedly`.- # - bnb NF4 corrupts *silently* — `bnb.nn.LinearNF4` subclasses `nn.Linear`, so the packed- # uint8 payload is cast to float8, inference still returns finite numbers, and the model- # just produces garbage.- # No quantized-format loader calls `_apply_fp8_layerwise_casting` today, so this is a guard- # against the next loader that gets wired up (they are being added one model at a time)- # rather than a fix for a live crash.- # The payload is packed integers, not values FP8 storage may re-encode.- if hasattr(config, "format") and config.format in QUANTIZED_MODEL_FORMATS:+ if not self._fp8_storage_asked_for(config, submodel_type):return False- # VAEs are excluded — fp8 storage causes noticeable quality degradation in decode.- if hasattr(config, "type") and config.type == ModelType.VAE:+ # Whether the setting can reach a model of this kind at all -- its type, its format, and+ # whether this loader implements the cast -- is decided in `fp8_capability.py`, because the UI+ # that offers the control and the identification that enables it have to give the same answer+ # as this gate. Deciding it here as well is how they came to disagree.+ if not fp8_storage_verdict(config.base, config.type, config.format).supported:return False- # LoRAs (including ControlLoRA) are excluded — they are not run as a standalone forward pass,- # they are patched into a base model, so the layerwise-casting hooks would never fire. The- # toggle is also hidden in the UI for ControlLoRA; this guard handles legacy persisted values.- if hasattr(config, "type") and config.type in (ModelType.LoRA, ModelType.ControlLoRa):- return False+ # Device support is probed last, so it runs only for a model that actually wants FP8 -- not on+ # the first load of any tokenizer/VAE/scheduler, and not on API or install threads, where it+ # would force XPU lazy SYCL init on a thread that never generates.+ return _device_supports_fp8_storage(self._torch_device, self._logger)- # Don't apply FP8 to text encoders, tokenizers, schedulers, VAEs, etc.- # The prompt enhancer is a causal LM run autoregressively (one full forward per generated- # token), so layerwise casting would pay the bf16<->fp8 round trip on every token — and its- # entire job is text quality, which fp8 rounding degrades. Its tokenizer is listed for- # symmetry (it is not an nn.Module, so casting is a no-op today only by accident).- _excluded_submodel_types = {- SubModelType.TextEncoder,- SubModelType.TextEncoder2,- SubModelType.TextEncoder3,- SubModelType.Tokenizer,- SubModelType.Tokenizer2,- SubModelType.Tokenizer3,- SubModelType.PromptEnhancer,- SubModelType.PromptEnhancerTokenizer,- SubModelType.Scheduler,- SubModelType.SafetyChecker,- SubModelType.VAE,- SubModelType.VAEDecoder,- SubModelType.VAEEncoder,- }- if submodel_type in _excluded_submodel_types:- return False+ def _report_inert_fp8_request(self, config: AnyModelConfig, submodel_type: Optional[SubModelType]) -> None:+ """Say so when a record asks for FP8 Storage that this kind of model cannot take.- # Check default_settings.fp8_storage (Main models, ControlNet)- if hasattr(config, "default_settings") and config.default_settings is not None:- if hasattr(config.default_settings, "fp8_storage") and config.default_settings.fp8_storage is True:- # Device support is probed last, so it runs only for a model that actually wants- # FP8 -- not on the first load of any tokenizer/VAE/scheduler, and not on API or- # install threads, where it would force XPU lazy SYCL init on a thread that never- # generates.- return _device_supports_fp8_storage(self._torch_device, self._logger)+ Nothing else would. A loader that does not implement the cast never calls `_should_use_fp8`+ either, so until now the setting was ignored without a word -- the failure mode this whole+ change is about. The control is no longer offered for such models, and identification no longer+ writes one, but records from before this change still carry the value. Those are left alone: the+ setting is inert, and if such a loader later implements the cast the stored request starts being+ honoured, which is what its owner asked for.- return False+ Once per cold load, and only for the submodel that would have been cast, so a Main model does+ not repeat it for its tokenizer and its VAE.+ """+ if not self._fp8_storage_asked_for(config, submodel_type):+ return+ verdict = fp8_storage_verdict(config.base, config.type, config.format)+ if not verdict.supported:+ self._logger.info(f"FP8 Storage is set for '{config.name}' but does nothing here: {verdict.reason}")def _keep_fp8_weights(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> bool:"""Whether a checkpoint's fp8 weights should stay packed rather than be folded into bf16.diff --git a/invokeai/backend/model_manager/load/model_loader_registry.py b/invokeai/backend/model_manager/load/model_loader_registry.pyindex ca9ea56edb..6c411701ab 100644--- a/invokeai/backend/model_manager/load/model_loader_registry.py+++ b/invokeai/backend/model_manager/load/model_loader_registry.py@@ -21,6 +21,7 @@ from typing import Callable, Dict, Optional, Tuple, Type, TypeVarfrom invokeai.backend.model_manager.configs.base import Config_Basefrom invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.load import ModelLoaderBase+from invokeai.backend.model_manager.load.fp8_capability import Fp8StorageDeclaration, declare_fp8_storagefrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType@@ -30,7 +31,11 @@ class ModelLoaderRegistryBase(ABC):@classmethod@abstractmethoddef register(- cls, type: ModelType, format: ModelFormat, base: BaseModelType = BaseModelType.Any+ cls,+ type: ModelType,+ format: ModelFormat,+ base: BaseModelType = BaseModelType.Any,+ fp8_storage: Fp8StorageDeclaration = None,) -> Callable[[Type[ModelLoaderBase]], Type[ModelLoaderBase]]:"""Define a decorator which registers the subclass of loader."""@@ -64,9 +69,19 @@ class ModelLoaderRegistry(ModelLoaderRegistryBase):@classmethoddef register(- cls, type: ModelType, format: ModelFormat, base: BaseModelType = BaseModelType.Any+ cls,+ type: ModelType,+ format: ModelFormat,+ base: BaseModelType = BaseModelType.Any,+ fp8_storage: Fp8StorageDeclaration = None,) -> Callable[[Type[TModelLoader]], Type[TModelLoader]]:- """Define a decorator which registers the subclass of loader."""+ """Define a decorator which registers the subclass of loader.++ `fp8_storage` is where a loader says it does *not* implement FP8 Storage, as+ `NotApplicable(reason)` or `Unimplemented(reason)`; the default means it does. The UI derived+ that from the model type alone, and so offered a control that 19 of its 52 keys ignore --+ see `fp8_capability.py` for why the answer belongs on this key and nowhere coarser.+ """def decorator(subclass: Type[TModelLoader]) -> Type[TModelLoader]:key = cls._to_registry_key(base, type, format)@@ -75,6 +90,7 @@ class ModelLoaderRegistry(ModelLoaderRegistryBase):f"{subclass.__name__} is trying to register as a loader for {base}/{type}/{format}, but this type of model has already been registered by {cls._registry[key].__name__}")cls._registry[key] = subclass+ declare_fp8_storage(base, type, format, fp8_storage)return subclassreturn decoratordiff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.pyindex 62bce3ad5a..4894b5197e 100644--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@ -11,6 +11,7 @@ from invokeai.backend.model_manager.configs.base import Checkpoint_Config_Basefrom invokeai.backend.model_manager.configs.controlnet import ControlNet_Checkpoint_Anima_Configfrom invokeai.backend.model_manager.configs.factory import AnyModelConfigfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Anima_Config+from invokeai.backend.model_manager.load.fp8_capability import NotApplicablefrom invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patternsfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.taxonomy import (@@ -258,7 +259,15 @@ class AnimaCheckpointModel(ModelLoader):return model[email protected](base=BaseModelType.Anima, type=ModelType.ControlNet, format=ModelFormat.Checkpoint)+ base=BaseModelType.Anima,+ type=ModelType.ControlNet,+ format=ModelFormat.Checkpoint,+ fp8_storage=NotApplicable(+ "an LLLite adapter is 8-66 MB (every one in the starter catalog), so the saving is tens of "+ "megabytes bought with an upcast on each of its per-Linear modules, every forward"+ ),+)class AnimaControlNetLLLiteModel(ModelLoader):"""Class to load Anima ControlNet-LLLite adapter models from safetensors checkpoints.diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 4ca5f23ea5..415b2b675f 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -63,6 +63,7 @@ from invokeai.backend.model_manager.configs.t5_encoder import (T5Encoder_T5Encoder_Config,)from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Config_Base, VAE_Checkpoint_Flux2_Config+from invokeai.backend.model_manager.load.fp8_capability import Unimplementedfrom invokeai.backend.model_manager.load.load_default import (ModelLoader,_model_declared_skip_patterns,@@ -1809,8 +1810,25 @@ class Flux2GGUFCheckpointModel(ModelLoader):return model[email protected](base=BaseModelType.Flux, type=ModelType.ControlNet, format=ModelFormat.Checkpoint)[email protected](base=BaseModelType.Flux, type=ModelType.ControlNet, format=ModelFormat.Diffusers)+_FLUX_CONTROLNET_FP8_STORAGE = Unimplemented(+ "neither the XLabs nor the InstantX path casts -- they do not even move the adapter to a compute dtype -- "+ "and the InstantX union build is a full FLUX transformer, so the gap is worth closing"+)+"""Both registrations below say this; naming it once keeps the two from drifting apart."""+++ base=BaseModelType.Flux,+ type=ModelType.ControlNet,+ format=ModelFormat.Checkpoint,+ fp8_storage=_FLUX_CONTROLNET_FP8_STORAGE,+)+ base=BaseModelType.Flux,+ type=ModelType.ControlNet,+ format=ModelFormat.Diffusers,+ fp8_storage=_FLUX_CONTROLNET_FP8_STORAGE,+)class FluxControlnetModel(ModelLoader):"""Class to load FLUX ControlNet models."""diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.pyindex db69005978..39df20d8da 100644--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py@@ -25,6 +25,7 @@ from invokeai.backend.model_manager.configs.main import (Main_Checkpoint_Ideogram4_Config,Main_Diffusers_Ideogram4_Config,)+from invokeai.backend.model_manager.load.fp8_capability import NotApplicablefrom invokeai.backend.model_manager.load.load_default import ModelLoader, _model_declared_skip_patternsfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.taxonomy import (@@ -101,7 +102,15 @@ def _verify_encoder_fully_materialized(model: torch.nn.Module, *, context: str))[email protected](base=BaseModelType.Ideogram4, type=ModelType.Main, format=ModelFormat.Diffusers)+ base=BaseModelType.Ideogram4,+ type=ModelType.Main,+ format=ModelFormat.Diffusers,+ fp8_storage=NotApplicable(+ "every published build is nf4 or fp8 already: `Fp8Linear` keeps the fp8 one at a byte per weight, "+ "and casting the nf4 payload would corrupt it silently"+ ),+)class Ideogram4DiffusersModel(ModelLoader):"""Loads Ideogram 4 main models (nf4 / fp8) bundled in diffusers layout."""diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.pyindex 5402f25b01..36557178bb 100644--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py@@ -32,6 +32,7 @@ from invokeai.backend.model_manager.configs.main import (Main_Checkpoint_MiniMaxH3_Config,Main_Diffusers_MiniMaxH3_Config,)+from invokeai.backend.model_manager.load.fp8_capability import Unimplementedfrom invokeai.backend.model_manager.load.load_default import ModelLoaderfrom invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders._single_file_guards import (@@ -79,7 +80,15 @@ def _raise_if_no_weight_shards(submodel_path: Path, submodel_label: str) -> None)[email protected](base=BaseModelType.MiniMaxH3, type=ModelType.Main, format=ModelFormat.Diffusers)+ base=BaseModelType.MiniMaxH3,+ type=ModelType.Main,+ format=ModelFormat.Diffusers,+ fp8_storage=Unimplemented(+ "the transformer keeps fp32 patch projections and output heads beside bf16 blocks, and the cast "+ "derives one compute dtype from the first float parameter; that has to be checked here first"+ ),+)class MiniMaxH3DiffusersModel(ModelLoader):"""Loader for MiniMax H3 diffusers-format models (FL2VA)."""@@ -165,7 +174,15 @@ class MiniMaxH3DiffusersModel(ModelLoader):raise ValueError(f"Unsupported submodel type {submodel_type} for MiniMax H3 models.")[email protected](base=BaseModelType.MiniMaxH3, type=ModelType.Main, format=ModelFormat.Checkpoint)+ base=BaseModelType.MiniMaxH3,+ type=ModelType.Main,+ format=ModelFormat.Checkpoint,+ fp8_storage=Unimplemented(+ "the same mixed-precision islands as the diffusers path, and the int8-convrot build additionally "+ "keeps packed int8 linears resident"+ ),+)class MiniMaxH3CheckpointModel(ModelLoader):"""Loader for MiniMax H3 single-file transformer checkpoints (bf16 or Comfy int8-convrot,full or AdaLN-pruned).diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 679750cec0..c5cd36e51b 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -25,6 +25,7 @@ from invokeai.backend.model_manager.configs.qwen3_encoder import (Qwen3Encoder_SDNQ_Config,Qwen3Encoder_SDNQ_Folder_Config,)+from invokeai.backend.model_manager.load.fp8_capability import Unimplementedfrom invokeai.backend.model_manager.load.load_default import (ModelLoader,_model_declared_skip_patterns,@@ -1004,7 +1005,15 @@ class Qwen3EncoderLoader(ModelLoader):)[email protected](base=BaseModelType.ZImage, type=ModelType.ControlNet, format=ModelFormat.Checkpoint)+ base=BaseModelType.ZImage,+ type=ModelType.ControlNet,+ format=ModelFormat.Checkpoint,+ fp8_storage=Unimplemented(+ "the adapter is loaded straight from the file and never cast at all; the Tile build is ~6.7 GB, "+ "so this one is worth closing"+ ),+)class ZImageControlCheckpointModel(ModelLoader):"""Class to load Z-Image Control adapter models from safetensors checkpoint.diff --git a/tests/backend/model_manager/load/test_fp8_capability.py b/tests/backend/model_manager/load/test_fp8_capability.pynew file mode 100644index 0000000000..08be63e067--- /dev/null+++ b/tests/backend/model_manager/load/test_fp8_capability.py@@ -0,0 +1,381 @@+"""Every loader that could be offered FP8 Storage either implements it or says why not.++The control was derived from the model type alone, and honoured by whichever loader happened to call+the cast. Nothing connected the two, so 19 of the 52 offered loader keys did nothing with it -- and+identification switched it on by itself for a float8 denoiser, which wrote `fp8_storage: true` onto+records whose loader ignores it.++The walk below is the part that cannot rot: a loader added tomorrow with neither the cast nor a+declaration fails here, named. It reads the loaders' source to decide whether they implement the cast,+which is only sound while every call is `self._apply_fp8_layerwise_casting(...)` inside a loader+class -- so that assumption is a cell of its own rather than a comment.+"""++import ast+import inspect+import textwrap+from pathlib import Path++import pytest++import invokeai.backend.model_manager.load # noqa: F401 (registers every loader)+from invokeai.backend.model_manager.configs.base import Config_Base+from invokeai.backend.model_manager.configs.factory import AnyModelConfig # noqa: F401 (builds every config class)+from invokeai.backend.model_manager.load import fp8_capability+from invokeai.backend.model_manager.load.fp8_capability import (+ FP8_STORAGE_MODEL_TYPES,+ NotApplicable,+ Unimplemented,+ declare_fp8_storage,+ declared_fp8_storage,+ fp8_storage_support,+ fp8_storage_verdict,+)+from invokeai.backend.model_manager.load.load_base import ModelLoaderBase+from invokeai.backend.model_manager.load.load_default import ModelLoader+from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry+from invokeai.backend.model_manager.taxonomy import (+ QUANTIZED_MODEL_FORMATS,+ BaseModelType,+ ModelFormat,+ ModelType,+)++_CAST = "_apply_fp8_layerwise_casting"+_KEEP = "_keep_fp8_weights"+_HELPERS = (_CAST, _KEEP)+# `_should_use_fp8` is deliberately *not* one of these, although `qwen_image.py` does consult it to+# decide whether to keep its packed weights. Consulting the gate is not honouring the setting: `wan.py`+# asks it only to decide whether to explain a decline, so counting it made this walk pass a Wan+# checkpoint whose cast had been deleted -- measured, by mutation. A loader that honoured the setting+# only that way would instead be asked for a declaration it does not need, which fails loudly and in+# the safe direction; a false positive is how `WanDiffusersModel` stayed hidden for as long as it did.+_LOADERS_DIR = Path(inspect.getfile(invokeai.backend.model_manager.load)).parent / "model_loaders"++# The two classes that *define* the fp8 helpers. Their source is excluded from the scan below, or+# every loader would look like it implements the cast by inheriting the method that performs it.+_GENERIC = (ModelLoader, ModelLoaderBase, object)+++def _undeclare_for_test(key: tuple[BaseModelType, ModelType, ModelFormat]) -> None:+ """Remove a declaration this file added. The module has no remover, because production never needs one."""+ fp8_capability._declared.pop(key)+++def _self_calls(source: str) -> set[str]:+ """The names a piece of source calls as `self.<name>(...)`.++ Parsed rather than grepped: `qwen_image.py` and `z_image.py` both discuss+ `_apply_fp8_layerwise_casting` in comments, and a substring scan reads those as implementations --+ the exact kind of false pass this file exists to prevent.+ """+ return {+ node.func.attr+ for node in ast.walk(ast.parse(textwrap.dedent(source)))+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "self"+ }+++def _super_calls(source: str) -> set[str]:+ """The names a piece of source calls as `super().<name>(...)`."""+ return {+ node.func.attr+ for node in ast.walk(ast.parse(textwrap.dedent(source)))+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and isinstance(node.func.value, ast.Call)+ and isinstance(node.func.value.func, ast.Name)+ and node.func.value.func.id == "super"+ }+++def _method_source(klass: type, name: str) -> str:+ """The source of the method `klass` itself defines, unwrapped from any descriptor."""+ attribute = vars(klass)[name]+ return inspect.getsource(getattr(attribute, "__func__", attribute))+++def _implements_the_cast(loader_cls: type) -> bool:+ """Whether the `_load_model` that would actually run reaches FP8 Storage.++ Either by calling the cast, or by asking `_keep_fp8_weights` -- a checkpoint loader that keeps+ scaled fp8 weights packed when the setting is on has honoured it just as much, without ever casting+ anything.++ Neither of the two obvious rules works, and both failed against real loaders in this tree:++ - scanning every class in the MRO credits an inherited call that an override replaced.+ `WanDiffusersModel` overrides `_load_model` outright and never delegates, so+ `GenericDiffusersLoader`'s cast never runs -- yet a flat scan called it implemented, and that+ false pass hid a live dead toggle;+ - scanning only the class that defines `_load_model` misses work handed to a helper elsewhere in+ the MRO. LTX-2 puts `_load_transformer_from_file` (and the cast) on the `_LTX2ComponentLoading`+ mixin, so that rule demanded a declaration from a loader that does implement it.++ So this follows the dispatch: start at the `_load_model` that would run, walk the `self.<helper>()`+ calls each method makes into whichever class in this loader's own MRO defines them, and follow+ `super().<name>()` past the definition it overrides. Per method, not per class, so an unrelated+ method on the same mixin cannot vouch for this one.+ """+ own = [klass for klass in loader_cls.__mro__ if klass not in _GENERIC]+ pending: list[tuple[str, int]] = [("_load_model", 0)]+ seen: set[tuple[str, int]] = set()++ while pending:+ name, start = pending.pop()+ if (name, start) in seen:+ continue+ seen.add((name, start))++ index = next((i for i in range(start, len(own)) if name in vars(own[i])), None)+ if index is None:+ continue # defined by the generic loader, or not a method of this loader at all++ source = _method_source(own[index], name)+ calls = _self_calls(source)+ if set(_HELPERS) & calls:+ return True+ pending.extend((called, 0) for called in calls)+ pending.extend((called, index + 1) for called in _super_calls(source))++ return False+++def _offered_keys() -> dict[tuple[BaseModelType, ModelType, ModelFormat], type]:+ """The registrations a client could offer the control for, by loader key.++ Quantized formats are left out: they are refused by a rule that holds for every loader, present+ and future, so asking each one to declare it would be asking them to repeat the rule.+ """+ return {+ (base, type_, format_): ModelLoaderRegistry._registry[+ ModelLoaderRegistry._to_registry_key(base, type_, format_)+ ]+ for (base, type_, format_) in declared_fp8_storage()+ if type_ in FP8_STORAGE_MODEL_TYPES and format_ not in QUANTIZED_MODEL_FORMATS+ }+++class TestEveryLoaderAnswersForItself:+ def test_each_offered_loader_either_implements_the_cast_or_says_why_not(self) -> None:+ """The cell that keeps this from rotting, in both directions.++ A loader with neither is the original defect: a control that changes nothing. A loader with+ both is a stale marker -- it implemented the cast and the declaration was left behind, so the+ UI goes on hiding a control that now works. Neither is allowed to pass quietly.+ """+ undeclared: list[str] = []+ stale: list[str] = []+ for (base, type_, format_), loader_cls in sorted(_offered_keys().items()):+ declaration = declared_fp8_storage()[(base, type_, format_)]+ key = f"{base.value}/{type_.value}/{format_.value} ({loader_cls.__name__})"+ if _implements_the_cast(loader_cls):+ if declaration is not None:+ stale.append(f"{key}: declares {type(declaration).__name__} but does reach the cast")+ elif declaration is None:+ undeclared.append(f"{key}: never reaches the cast and declares nothing")++ assert undeclared == [], (+ "These loaders would be offered FP8 Storage and silently ignore it. Either implement the "+ "cast or declare NotApplicable/Unimplemented at the registration:\n " + "\n ".join(undeclared)+ )+ assert stale == [], (+ "These declarations are out of date -- the loader implements the cast now, so the "+ "declaration only hides a control that works:\n " + "\n ".join(stale)+ )++ def test_the_scan_above_can_see_every_way_a_loader_reaches_the_helpers(self) -> None:+ """The scan looks for `self.<helper>(...)` inside a loader class, so any other route is invisible.++ A module-level function taking the loader as an argument would break it silently: the loader+ would read as inert, and this file would then demand a declaration for a loader that works --+ or, if one were added, hide a working control. Pinning the shape the scan assumes is cheaper+ and more honest than making the scan cleverer.+ """+ stray: list[str] = []+ for path in sorted(_LOADERS_DIR.glob("*.py")):+ for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):+ if isinstance(node, ast.Name) and node.id in _HELPERS:+ stray.append(f"{path.name}:{node.lineno}: bare reference to {node.id}")+ elif isinstance(node, ast.Attribute) and node.attr in _HELPERS:+ through_self = isinstance(node.value, ast.Name) and node.value.id == "self"+ if not through_self:+ stray.append(f"{path.name}:{node.lineno}: {node.attr} reached other than through `self`")+ assert stray == [], (+ "An fp8 helper is reached other than as `self.<helper>(...)`, which the scan above cannot "+ "attribute to a loader class:\n " + "\n ".join(stray)+ )++ def test_the_declarations_are_the_backlog_and_nothing_else(self) -> None:+ """`Unimplemented` is work and `NotApplicable` is a decision, so the split has to stay real.++ Asserted as the current lists rather than as counts: a count going down says nothing about+ which one moved, and the useful failure here is "you implemented one, update this line".+ """+ by_marker: dict[type, list[str]] = {NotApplicable: [], Unimplemented: []}+ for (base, type_, format_), declaration in sorted(declared_fp8_storage().items()):+ if declaration is not None:+ by_marker[type(declaration)].append(f"{base.value}/{type_.value}/{format_.value}")++ assert by_marker[NotApplicable] == [+ "anima/controlnet/checkpoint", # 8-66 MB adapters+ "ideogram-4/main/diffusers", # published only as nf4 or fp8+ ]+ assert by_marker[Unimplemented] == [+ "flux/controlnet/checkpoint",+ "flux/controlnet/diffusers",+ "minimax-h3/main/checkpoint",+ "minimax-h3/main/diffusers",+ "z-image/controlnet/checkpoint",+ ]++ def test_every_declaration_gives_a_reason(self) -> None:+ """A marker without a reason is a dead control with better manners."""+ for key, declaration in declared_fp8_storage().items():+ if declaration is not None:+ assert declaration.reason.strip(), key+ assert len(declaration.reason) > 30, f"{key}: {declaration.reason!r} explains nothing"+++class TestThePolicyMatchesTheSchemas:+ def test_the_types_that_can_ask_are_exactly_the_types_that_carry_the_setting(self) -> None:+ """`FP8_STORAGE_MODEL_TYPES` is derived from the config schemas, so it has to keep matching them.++ Walking every concrete config class and reading the `default_settings` annotation is the only+ way to notice a new type whose settings carry `fp8_storage` -- it would then offer the control+ with nothing behind it, which is where this whole class of bug came from.++ ControlLoRa is the one type that carries the field and is still excluded: it shares+ `ControlAdapterDefaultSettings` with the control adapters but is patched into a base model, so+ the casting hooks would never fire.+ """+ carries_the_field: set[ModelType] = set()+ for config_cls in Config_Base.CONFIG_CLASSES:+ field = config_cls.model_fields.get("default_settings")+ if field is None:+ continue+ settings_types = [+ annotation+ for annotation in getattr(field.annotation, "__args__", (field.annotation,))+ if isinstance(annotation, type) and hasattr(annotation, "model_fields")+ ]+ if any("fp8_storage" in settings.model_fields for settings in settings_types):+ carries_the_field.add(config_cls.model_fields["type"].default)++ assert carries_the_field - FP8_STORAGE_MODEL_TYPES == {ModelType.ControlLoRa}+ assert FP8_STORAGE_MODEL_TYPES - carries_the_field == set()+++class TestTheVerdict:+ def test_a_loader_that_implements_the_cast_is_supported(self) -> None:+ """The positive control. Without it every cell below passes on a verdict that always says no."""+ verdict = fp8_storage_verdict(BaseModelType.Flux, ModelType.Main, ModelFormat.Checkpoint)+ assert verdict.supported is True+ assert verdict.reason is None++ def test_a_declared_loader_is_refused_with_its_own_reason(self) -> None:+ verdict = fp8_storage_verdict(BaseModelType.ZImage, ModelType.ControlNet, ModelFormat.Checkpoint)+ assert verdict.supported is False+ assert verdict.reason is not None and "never cast" in verdict.reason++ def test_a_quantized_format_is_refused_although_its_loader_declares_nothing(self) -> None:+ """The rule the loaders do not have to repeat. `WanGGUFCheckpointModel` declares nothing and+ must still come out unsupported, or every quantized loader would need a marker saying the same+ sentence."""+ assert declared_fp8_storage()[(BaseModelType.Wan, ModelType.Main, ModelFormat.GGUFQuantized)] is None+ verdict = fp8_storage_verdict(BaseModelType.Wan, ModelType.Main, ModelFormat.GGUFQuantized)+ assert verdict.supported is False+ assert verdict.reason is not None and "packed quantized payload" in verdict.reason++ @pytest.mark.parametrize(+ "type_",+ [ModelType.VAE, ModelType.LoRA, ModelType.ControlLoRa, ModelType.IPAdapter],+ ids=lambda t: t.value,+ )+ def test_a_type_the_setting_cannot_reach_is_refused_before_anything_else_is_asked(self, type_: ModelType) -> None:+ verdict = fp8_storage_verdict(BaseModelType.Flux, type_, ModelFormat.Diffusers)+ assert verdict.supported is False+ # The reason names the type and stops there. Each of these is excluded on different grounds --+ # decode quality for a VAE, patched-in weights for the LoRAs, no such setting for the rest --+ # and one sentence covering all four would have to be untrue of most of them.+ assert verdict.reason == f"FP8 Storage is not offered for {type_.value} models."++ def test_a_wildcard_registration_answers_for_every_base_it_serves(self) -> None:+ """`get_implementation` falls back to the `Any` base, so this has to as well.++ Every T2I adapter is loaded by `GenericDiffusersLoader` under `any/t2i_adapter/diffusers`, and no+ record carries `any` as its own base. Looking up the exact key alone answers "no loader+ registered" for all of them, which would quietly withdraw a control that works.+ """+ assert (BaseModelType.StableDiffusion1, ModelType.T2IAdapter, ModelFormat.Diffusers) not in (+ declared_fp8_storage()+ )+ assert (BaseModelType.Any, ModelType.T2IAdapter, ModelFormat.Diffusers) in declared_fp8_storage()++ for base in (BaseModelType.StableDiffusion1, BaseModelType.StableDiffusionXL):+ assert fp8_storage_verdict(base, ModelType.T2IAdapter, ModelFormat.Diffusers).supported is True++ def test_an_exact_registration_wins_over_the_wildcard(self) -> None:+ """Same precedence as the registry's own lookup, including when the exact one is the stricter.++ No architecture registers its own T2I adapter loader today, so this is asserted against the+ resolution rather than against a live pair: a declared key must not be overruled by a permissive+ wildcard sitting behind it.+ """+ key = (BaseModelType.Flux, ModelType.T2IAdapter, ModelFormat.Diffusers)+ # Asserted before writing: the day a FLUX-specific T2I adapter loader registers, this cell must+ # fail rather than delete that loader's real declaration on its way out.+ assert key not in declared_fp8_storage(), "this key is registered now; pin the precedence against it instead"++ declare_fp8_storage(*key, Unimplemented("registered by this test only, to pin the precedence"))+ try:+ assert fp8_storage_verdict(*key).supported is False+ assert (+ fp8_storage_verdict(+ BaseModelType.StableDiffusion1, ModelType.T2IAdapter, ModelFormat.Diffusers+ ).supported+ is True+ )+ finally:+ _undeclare_for_test(key)++ def test_a_key_with_no_loader_is_refused(self) -> None:+ """Nothing can load it, so nothing can honour the setting either -- and the client's lookup+ misses for exactly these, which is why absence has to mean no rather than yes."""+ key = (BaseModelType.StableDiffusion1, ModelType.Main, ModelFormat.BnbQuantizednf4b)+ assert key not in declared_fp8_storage()+ verdict = fp8_storage_verdict(*key)+ assert verdict.supported is False+++class TestTheServedTable:+ def test_flux_main_and_flux_controlnet_disagree(self) -> None:+ """The reason the table is keyed `(base, type, format)` and not by architecture.++ Both rows are `flux`. A per-architecture field -- the shape this was first designed as -- can+ hold only one answer for the two, and would have to be wrong about one of them.+ """+ rows = {(row.base, row.type, row.format): row.supported for row in fp8_storage_support()}+ assert rows[(BaseModelType.Flux, ModelType.Main, ModelFormat.Checkpoint)] is True+ assert rows[(BaseModelType.Flux, ModelType.ControlNet, ModelFormat.Checkpoint)] is False++ def test_the_format_changes_the_answer_for_one_architecture(self) -> None:+ """The other axis a coarser key loses: same base, same type, two formats, two answers."""+ rows = {(row.base, row.type, row.format): row.supported for row in fp8_storage_support()}+ assert rows[(BaseModelType.Wan, ModelType.Main, ModelFormat.Checkpoint)] is True+ assert rows[(BaseModelType.Wan, ModelType.Main, ModelFormat.GGUFQuantized)] is False++ def test_every_loader_of_those_types_gets_exactly_one_row(self) -> None:+ """Counted against the registry rather than rebuilt from the table's own comprehension, which+ would only restate it. A client builds a map from this, so a duplicate would pick a winner in+ silence and a missing row would read as unsupported."""+ rows = fp8_storage_support()+ keys = [(row.base, row.type, row.format) for row in rows]++ assert len(set(keys)) == len(keys)+ assert len(keys) == sum(+ 1 for _base, type_, _format in declared_fp8_storage() if type_ in FP8_STORAGE_MODEL_TYPES+ )diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex c5db052bb0..0ac15ed4ca 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -52,20 +52,31 @@ def _make_loader(device: str = "cuda") -> ModelLoader:return loader-def _make_config(model_type: ModelType, fp8: bool, base: BaseModelType = BaseModelType.Flux):+def _make_config(+ model_type: ModelType,+ fp8: bool,+ base: BaseModelType = BaseModelType.Flux,+ fmt: ModelFormat = ModelFormat.Diffusers,+):+ """A stand-in for a model record.++ `format` is not optional here, as it is not optional on a real config: `Config_Base` refuses a+ concrete class that does not declare base, type and format, and the gate now asks all three --+ whether the loader for that key implements the cast is part of the answer+ (`load/fp8_capability.py`). A double without a format would be a shape production never sees.+ """return SimpleNamespace(type=model_type,base=base,+ format=fmt,name="test",default_settings=SimpleNamespace(fp8_storage=fp8),)def _make_quantized_config(fmt: ModelFormat = ModelFormat.GGUFQuantized):- """A config carrying a quantized `format`, which `_make_config` deliberately omits."""- config = _make_config(ModelType.Main, fp8=True)- config.format = fmt- return config+ """A config whose `format` is one of the already-quantized ones."""+ return _make_config(ModelType.Main, fp8=True, fmt=fmt)_STORAGE_PROBE = "invokeai.backend.model_manager.load.load_default._device_supports_fp8_storage"@@ -576,6 +587,45 @@ def test_should_use_fp8_allows_z_image():assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=True, base=BaseModelType.ZImage)) is True+def test_should_use_fp8_refuses_a_loader_that_declared_it_does_not_implement_the_cast():+ """A Z-Image ControlNet asks for fp8 and its loader never casts, so the gate must say no.++ Not the same question as the one above: Z-Image *main* implements the cast. Both are+ `base=z-image`, which is why the answer cannot live on the architecture -- it lives on the+ loader key, and `ZImageControlCheckpointModel` declares `Unimplemented` there.++ The device probe must not run for it either: an inert request is no reason to touch the GPU.+ """+ loader = _make_loader(device="cuda")+ config = _make_config(ModelType.ControlNet, fp8=True, base=BaseModelType.ZImage, fmt=ModelFormat.Checkpoint)+ with patch(_STORAGE_PROBE) as mock_probe:+ assert loader._should_use_fp8(config) is False+ mock_probe.assert_not_called()+++def test_an_inert_fp8_request_is_reported_rather_than_ignored(caplog):+ """The setting survives on records that predate the declarations -- identification used to set it+ itself for any float8 denoiser -- and such a loader never reaches `_should_use_fp8` at all. So the+ load says once why nothing happened, which is the one thing the silent version never did.+ """+ loader = _make_loader(device="cuda")+ config = _make_config(ModelType.Main, fp8=True, base=BaseModelType.MiniMaxH3, fmt=ModelFormat.Checkpoint)++ with caplog.at_level("INFO", logger="test"):+ loader._report_inert_fp8_request(config, SubModelType.Transformer)+ assert "does nothing here" in caplog.text+ assert "mixed-precision islands" in caplog.text++ caplog.clear()+ # Not for the components that were never going to be cast, or a Main model would repeat itself+ # once per submodel, nor for a model that asked for nothing.+ with caplog.at_level("INFO", logger="test"):+ loader._report_inert_fp8_request(config, SubModelType.Tokenizer)+ loader._report_inert_fp8_request(_make_config(ModelType.Main, fp8=False), SubModelType.Transformer)+ loader._report_inert_fp8_request(_make_config(ModelType.Main, fp8=True), SubModelType.Transformer)+ assert caplog.text == ""++def test_wrap_forward_reaches_custom_linear_after_apply_custom_layers():"""Production order: `_load_model` applies FP8 wrapping, THEN `ModelCache.put()` calls`apply_custom_layers_to_model` which constructs a NEW `CustomLinear` object viadiff --git a/tests/backend/util/test_fp8.py b/tests/backend/util/test_fp8.pyindex f6895181d4..62ea51c45e 100644--- a/tests/backend/util/test_fp8.py+++ b/tests/backend/util/test_fp8.py@@ -19,7 +19,7 @@ import pytestimport torchfrom invokeai.backend.model_manager.load.load_default import ModelLoader-from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelTypefrom invokeai.backend.util.fp8 import (FP8_COMPUTE_DTYPE_ATTR,get_model_compute_dtype,@@ -81,6 +81,9 @@ def test_returns_compute_dtype_after_real_fp8_cast():config = SimpleNamespace(type=ModelType.Main,base=BaseModelType.StableDiffusionXL,+ # A real config always declares a format, and the gate reads it: whether the loader for this+ # `(base, type, format)` implements the cast is part of the answer (`load/fp8_capability.py`).+ format=ModelFormat.Diffusers,name="test",default_settings=SimpleNamespace(fp8_storage=True),)@@ -143,6 +146,9 @@ def test_double_cast_is_a_noop():config = SimpleNamespace(type=ModelType.Main,base=BaseModelType.StableDiffusionXL,+ # A real config always declares a format, and the gate reads it: whether the loader for this+ # `(base, type, format)` implements the cast is part of the answer (`load/fp8_capability.py`).+ format=ModelFormat.Diffusers,name="test",default_settings=SimpleNamespace(fp8_storage=True),)