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
fix(fp8): restore the loader registration the extracted helper stole
Alexander Eichhorn340aac9a2243
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex e09b74bf4b..276c67726d 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -30,7 +30,7 @@ from invokeai.backend.model_manager.taxonomy import ()from invokeai.backend.quantization.fp8_scaled import count_fp8_weights, should_keep_fp8_weightsfrom invokeai.backend.util.devices import TorchDevice-from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR, set_fp8_compute_dtype+from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR, FP8_STORAGE_DTYPES, set_fp8_compute_dtype# Probe results keyed by concrete device (e.g. "xpu:1"). float8 support is build/driver# dependent, so it is a per-device property: a discrete Arc may be paired with an integrated@@ -596,8 +596,20 @@ class ModelLoader(ModelLoaderBase):if not isinstance(module, _FP8_SUPPORTED_PYTORCH_LAYERS):continueif any(re.search(pattern, module_name) for pattern in skip_patterns):+ # A pattern skip means "this module computes in `compute_dtype`", so a weight that+ # arrived already float8 contradicts it: nothing casts it back and no pre-hook is+ # installed here, leaving the forward to run on raw fp8 codes. That is reachable+ # whenever a loader keeps checkpoint fp8 weights and then asks for fp8 storage on+ # the remainder (the Qwen3-VL encoder does exactly this), and it depends on a+ # coincidence — that the loader's own skip list and this one never name the same+ # Linear. Upcast instead of relying on that.+ ModelLoader._restore_compute_dtype(module, compute_dtype)continueif skip is not None and skip(module_name, module):+ # A caller-supplied skip is different: its one user excludes scaled-fp8 layers,+ # which are *meant* to stay quantized and go through `_scaled_mm` with their+ # `weight_scale`. Upcasting those would drop the scale. Leave them exactly as they+ # are.continueparams = list(module.parameters(recurse=False))if not params:@@ -610,6 +622,17 @@ class ModelLoader(ModelLoaderBase):ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)+ @staticmethod+ def _restore_compute_dtype(module: torch.nn.Module, compute_dtype: torch.dtype) -> None:+ """Cast a skipped module's float8 params back to the dtype it is expected to compute in.++ Only float8 params are touched, and only the storage dtypes — a quantized param (GGUF, NF4,+ bitsandbytes) is left to its own kernels.+ """+ for param in module.parameters(recurse=False):+ if param.data.dtype in FP8_STORAGE_DTYPES and not _is_quantized_param(param):+ param.data = param.data.to(compute_dtype)+@staticmethoddef _wrap_forward_with_fp8_cast(module: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtypediff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex b82e514a43..a2718758a7 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -760,6 +760,11 @@ class Qwen3VLEncoderCheckpointLoader(ModelLoader):predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, scaled_layers=fp8_layers))fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)+ # No `skip_patterns` here on purpose: this model declares none, and the storage pass below+ # applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect+ # on a 2-D Linear -- such a weight would arrive fp8 from the state dict, be skipped by the+ # cast pass, and forward on raw fp8 codes. `_apply_fp8_to_nn_module` now restores the compute+ # dtype on the modules it skips, so the two lists are independent again.cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)model.load_state_dict(sd, assign=True, strict=False)diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 62f175f0e5..a6e0255283 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -1025,7 +1025,6 @@ class ZImageControlCheckpointModel(ModelLoader):return model[email protected](base=BaseModelType.Any, type=ModelType.Qwen3Encoder, format=ModelFormat.Checkpoint)def _fold_comfy_scaled_weights(sd: dict[str, Any], dtype: torch.dtype) -> int:"""Fold every ComfyUI-style ``weight_scale`` into its weight, in place. Returns how many.@@ -1057,6 +1056,7 @@ def _fold_comfy_scaled_weights(sd: dict[str, Any], dtype: torch.dtype) -> int:return folded[email protected](base=BaseModelType.Any, type=ModelType.Qwen3Encoder, format=ModelFormat.Checkpoint)class Qwen3EncoderCheckpointLoader(ModelLoader):"""Class to load single-file Qwen3 Encoder models for Z-Image (safetensors format)."""diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex 30957c4a3a..9ed38273bf 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -835,3 +835,77 @@ class TestApplyFp8SkipCallback:assert model.keep.weight.dtype is not torch.float8_e4m3fnassert model.cast.weight.dtype is torch.float8_e4m3fn+++class TestSkippedModulesNeverKeepCheckpointFp8:+ """A pattern-skipped module must not be left holding float8 weights.++ The cast pass installs the upcast pre-hook only on modules it casts. A module it *skips* keeps+ whatever dtype it arrived with — fine when that is the compute dtype, silently fatal when the+ loader kept the checkpoint's fp8 weights: no hook, no cast back, and the forward runs on raw fp8+ codes. Reachable wherever a loader combines `keep_fp8` with fp8 storage on the remainder (the+ Qwen3-VL encoder), and otherwise dependent on the loader's skip list and+ `_FP8_DEFAULT_SKIP_PATTERNS` never naming the same Linear.+ """++ def _model(self) -> torch.nn.Module:+ model = torch.nn.Module()+ # `proj_out` is in `_FP8_DEFAULT_SKIP_PATTERNS`; `attn` is not.+ model.add_module("proj_out", torch.nn.Linear(16, 32))+ model.add_module("attn", torch.nn.Linear(16, 32))+ return model++ def test_a_pattern_skipped_module_is_restored_to_the_compute_dtype(self) -> None:+ model = self._model()+ # As a loader that kept checkpoint fp8 weights would hand it over.+ model.proj_out.weight = torch.nn.Parameter(+ torch.zeros(32, 16, dtype=torch.bfloat16).to(torch.float8_e4m3fn), requires_grad=False+ )++ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)++ assert model.proj_out.weight.dtype is torch.bfloat16, "skipped module left computing on fp8 codes"+ assert model.attn.weight.dtype is torch.float8_e4m3fn++ def test_an_extra_skip_pattern_gets_the_same_treatment(self) -> None:+ model = self._model()+ model.attn.weight = torch.nn.Parameter(+ torch.zeros(32, 16, dtype=torch.bfloat16).to(torch.float8_e4m3fn), requires_grad=False+ )++ ModelLoader._apply_fp8_to_nn_module(+ model,+ storage_dtype=torch.float8_e4m3fn,+ compute_dtype=torch.bfloat16,+ extra_skip_patterns=("attn",),+ )++ assert model.attn.weight.dtype is torch.bfloat16++ def test_a_full_precision_skipped_module_is_untouched(self) -> None:+ """The restore must not disturb the ordinary case it shares a branch with."""+ model = self._model()+ model.proj_out.weight = torch.nn.Parameter(torch.zeros(32, 16, dtype=torch.float32), requires_grad=False)++ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)++ assert model.proj_out.weight.dtype is torch.float32++ def test_a_caller_skipped_scaled_layer_keeps_its_fp8_weight(self) -> None:+ """The `skip=` callback means the opposite of a pattern skip: its one caller excludes+ scaled-fp8 layers, which stay quantized and go through `_scaled_mm` with their+ `weight_scale`. Upcasting those would drop the scale."""+ model = self._model()+ model.attn.weight = torch.nn.Parameter(+ torch.zeros(32, 16, dtype=torch.bfloat16).to(torch.float8_e4m3fn), requires_grad=False+ )+ model.attn.weight_scale = torch.tensor(2.0)++ ModelLoader._apply_fp8_to_nn_module(+ model,+ storage_dtype=torch.float8_e4m3fn,+ compute_dtype=torch.bfloat16,+ skip=lambda _name, module: getattr(module, "weight_scale", None) is not None,+ )++ assert model.attn.weight.dtype is torch.float8_e4m3fndiff --git a/tests/backend/model_manager/load/test_model_loader_registry_entries.py b/tests/backend/model_manager/load/test_model_loader_registry_entries.pynew file mode 100644index 0000000000..84fc6cb59c--- /dev/null+++ b/tests/backend/model_manager/load/test_model_loader_registry_entries.py@@ -0,0 +1,49 @@+"""Every registry entry must be an instantiable loader class.++`ModelLoaderRegistry.register` does no runtime type check and returns its argument unchanged, so it+happily decorates whatever follows it. Insert a helper function between the decorator and the class+it was meant to decorate — a plausible outcome of extracting a loop into a named function — and the+registry silently binds the helper instead. The helper keeps working everywhere it is called+directly, the module imports, ruff is clean and the whole suite passes; the only symptom is that+`ModelLoadService.load_model` calls `implementation(app_config=..., logger=..., ram_cache=...)` and+gets `TypeError: <helper>() got an unexpected keyword argument 'app_config'` — i.e. that model type+can no longer be loaded at all.++This happened to `Qwen3EncoderCheckpointLoader`. One assertion over the whole registry closes the+class, so it cannot happen again to a loader nobody has an end-to-end test for.+"""++import importlib+import inspect+import pkgutil++import invokeai.backend.model_manager.load.model_loaders as model_loaders_pkg+from invokeai.backend.model_manager.load.load_base import ModelLoaderBase+from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry+++def _import_every_loader_module() -> None:+ """Registration is an import side effect, so nothing is in the registry until this runs."""+ for module in pkgutil.iter_modules(model_loaders_pkg.__path__):+ importlib.import_module(f"{model_loaders_pkg.__name__}.{module.name}")+++def test_every_registered_implementation_is_a_loader_class() -> None:+ _import_every_loader_module()+ assert ModelLoaderRegistry._registry, "no loaders registered — the import sweep above is broken"++ not_classes = {key: impl for key, impl in ModelLoaderRegistry._registry.items() if not inspect.isclass(impl)}+ assert not not_classes, (+ "these registry keys are bound to something that is not a class, so instantiating them at "+ f"load time raises TypeError: {not_classes}"+ )+++def test_every_registered_implementation_subclasses_the_loader_base() -> None:+ """A class is not enough on its own — `load_model` also needs the base's constructor signature."""+ _import_every_loader_module()++ wrong_base = {+ key: impl for key, impl in ModelLoaderRegistry._registry.items() if not issubclass(impl, ModelLoaderBase)+ }+ assert not wrong_base, f"registered implementations that are not ModelLoaderBase subclasses: {wrong_base}"