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
Merge branch 'main' into feat/fp8_compute_raw
Alexander Eichhorn863e96fa4ab0
diff --cc invokeai/backend/model_manager/load/load_default.pyindex 45abf0cf8b,e33d870263..76007dabeb--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@@ -523,16 -526,10 +544,16 @@@ class ModelLoader(ModelLoaderBase)Without the skip list, precision-sensitive tiny learned scalars (e.g. FLUX RMSNorm.scale)get crushed to FP8 and quality degrades noticeably.- `extra_skip_patterns` carries the model's own declared exclusions (diffusers'- `_skip_layerwise_casting_patterns`), which are model-specific and cannot be inferred from+ `extra_skip_patterns` carries the model's own declared exclusions (see+ `_model_declared_skip_patterns`), which are model-specific and cannot be inferred fromlayer types or generic name patterns.+ `skip` excludes further modules by (dotted name, module). Its one caller uses it to leave+ scaled-fp8 layers alone: those already hold fp8 weights plus a `weight_scale`, and the cast+ hooks installed here would upcast them *without* applying that scale — a silently wrong+ weight. Casting only the remainder lets a partly-quantized checkpoint (fp8 language model,+ bf16 visual tower) end up fully fp8-resident.+Modules holding already-quantized weights are skipped regardless of their class. This is abackstop behind the format check in `_should_use_fp8`, which cannot see quantization thatis not reflected in the model's format (e.g. a `diffusers`-format checkpoint whose weightsdiff --cc invokeai/backend/model_manager/load/model_loaders/anima.pyindex 4c38b41e6a,97782b07ff..5cb9e08ce7--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@@ -10,7 -10,7 +10,7 @@@ from invokeai.backend.model_manager.confrom 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.load_default import ModelLoader++from 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 (AnyModel,@@@ -203,19 -161,18 +203,19 @@@ class AnimaCheckpointModel(ModelLoader)with accelerate.init_empty_weights():model = AnimaTransformer(**ANIMA_TRANSFORMER_CONFIG)- skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())- # Determine safe dtype- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_anima_inference_dtype(target_device)-- # Handle memory management- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())- self._ram_cache.make_room(new_sd_size)++ skip_patterns = _model_declared_skip_patterns(model)+ # Layers the cast would dequantize anyway are folded here, scale applied, so the cast never+ # strips a scale that can no longer be put back.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. The prediction is unaffected by the split -- it applies the same+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ )- # Convert to target dtype (skip non-float tensors like embedding indices)- for k in sd.keys():- if sd[k].is_floating_point():- sd[k] = sd[k].to(model_dtype)+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ kept = cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)load_result = model.load_state_dict(sd, assign=True, strict=False)if load_result.unexpected_keys:diff --cc invokeai/backend/model_manager/load/model_loaders/flux.pyindex ed33a1582f,8ad9459735..6a51db4e7c--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@@ -62,7 -62,7 +62,11 @@@ from invokeai.backend.model_manager.conT5Encoder_T5Encoder_Config,)from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Config_Base, VAE_Checkpoint_Flux2_Config--from invokeai.backend.model_manager.load.load_default import ModelLoader, resolve_submodel_path++from invokeai.backend.model_manager.load.load_default import (++ ModelLoader,++ _model_declared_skip_patterns,++ resolve_submodel_path,++)from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders.flux2_state_dict_utils import (convert_flux2_bfl_to_diffusers,@@@ -734,71 -715,12 +738,71 @@@ class FluxCheckpointModel(ModelLoader)sd = load_file(model_path)if "model.diffusion_model.double_blocks.0.img_attn.norm.key_norm.scale" in sd:sd = convert_bundle_to_flux_transformer_checkpoint(sd)- new_sd_size = sum([ten.nelement() * torch.bfloat16.itemsize for ten in sd.values()])- self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- # We need to cast to bfloat16 due to it being the only currently supported dtype for inference- sd[k] = sd[k].to(torch.bfloat16)++ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight, optionally an input+ # scale). Read *after* the bundle conversion: the scale keys carry the same+ # `model.diffusion_model.` prefix as the weights and only line up with the module tree once+ # it has been stripped. Until now the loader had no idea these keys existed and+ # `load_state_dict` rejected the checkpoint outright as unexpected keys.+ #+ # Unlike FLUX.2 there is no key conversion here: the checkpoint is already in the BFL+ # layout this model implements, and `qkv` stays one fused Linear, so a per-tensor scale+ # attaches to exactly the module it was computed for.+ #+ # Hints ship either in the safetensors header or as per-layer `.comfy_quant` markers; the+ # header wins on the rare checkpoint carrying both.+ metadata = read_safetensors_metadata(model_path, self._logger)+ # Header names still carry the checkpoint prefix that was stripped off `sd`; strip it from+ # them too, or every per-layer flag matches nothing.+ layer_hints = {+ **extract_comfy_quant_hints(sd),+ **strip_layer_path_prefix(parse_quantization_metadata(metadata)),+ }+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)++ # A checkpoint that ships raw fp8 weights (fp8 tensors, no weight_scale) keeps them when the+ # fp8 matmul is available; casting them to bf16 here would throw away both the VRAM saving+ # and the tensor cores before the model is ever built.+ keep_fp8 = should_keep_fp8_weights(self._torch_device)+ if fp8_layers and not keep_fp8:+ # Without the matmul, keeping them quantized would halve VRAM but dequantize on every+ # forward. Fold the scale into the weight instead — the legacy result, except the scale+ # is now actually applied rather than dropped.+ dequantize_fp8_scaled(sd, fp8_layers, torch.bfloat16)+ fp8_layers = {}+- skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())++ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale that can no longer be put back.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. The prediction is unaffected by the split -- it applies the same+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(+ sd, torch.bfloat16, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns+ )+ )++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns)+ # Everything else is cast to bfloat16, the only dtype currently supported for inference.+ kept = cast_state_dict(sd, torch.bfloat16, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)model.load_state_dict(sd, assign=True)++ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ self._logger.info(f"FLUX: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")+ warn_on_unattached_scales(self._logger, "FLUX", attached, fp8_layers)+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)+ if marked and full_precision_hints_respected():+ self._logger.info(+ f"FLUX: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "+ "them on the fp8 tensor cores instead."+ )+ elif kept:+ self._logger.info(f"FLUX: kept {kept} raw fp8 weight(s) quantized for the fp8 tensor cores.")+return model@@@ -1170,24 -1063,9 +1174,24 @@@ class Flux2CheckpointModel(ModelLoader)out_features2, in_features2, dtype=torch.bfloat16)- # Convert to bfloat16 and load- for k in converted_sd.keys():- converted_sd[k] = converted_sd[k].to(torch.bfloat16)+ # Convert to bfloat16 and load, leaving raw fp8 weights quantized when the tensor cores can+ # take them (the scaled-fp8 path above has already folded any weight_scale it found). The+ # model's own precision-sensitive list is honored — see the Z-Image loader for why that is+ # a correctness requirement and not just a quality nicety.- skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())++ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale that can no longer be put back.+ fp8_layers = split_fp8_scaled_layers(+ converted_sd, fp8_layers, torch.bfloat16, model=model, skip_patterns=skip_patterns+ )++ kept = cast_state_dict(+ converted_sd,+ torch.bfloat16,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )# Load the state dict - guidance weights were already initialized above if missingmodel.load_state_dict(converted_sd, assign=True)diff --cc invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 34d9ee90f0,fbd681c802..c2e67acab0--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@@ -14,7 -14,7 +14,11 @@@ from invokeai.backend.model_manager.conQwen3VLEncoder_Checkpoint_Config,Qwen3VLEncoder_Qwen3VLEncoder_Config,)--from invokeai.backend.model_manager.load.load_default import ModelLoader, _device_supports_fp8_storage++from invokeai.backend.model_manager.load.load_default import (++ ModelLoader,++ _device_supports_fp8_storage,++ _model_declared_skip_patterns,++)from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoaderfrom invokeai.backend.model_manager.taxonomy import (@@@ -399,78 -363,17 +403,82 @@@ class Krea2CheckpointModel(ModelLoader)with accelerate.init_empty_weights():model = Krea2Transformer2DModel(**KREA2_TRANSFORMER_CONFIG)- skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())- new_sd_size = sum(ten.nelement() * model_dtype.itemsize for ten in sd.values())- self._ram_cache.make_room(new_sd_size)- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)++ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers the cast would dequantize anyway (skip patterns, non-Linear weights) are+ # folded here, with their scale applied. Left to `cast_state_dict` they would be cast+ # *without* it and `attach_fp8_scales` would then skip them for no longer being fp8 —+ # a weight silently off by 1/weight_scale. Krea-2's `time_embed.linear_1/linear_2` are+ # ordinary quantized Linears in a ComfyUI export and match the model's `time_embed` pattern.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. The prediction is unaffected by the split -- it applies the same+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ )++ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ # A checkpoint with raw fp8 weights (fp8 tensors and no weight_scale) yields no fp8_layers at+ # all, but its weights are still usable on the tensor cores, so the same `keep_fp8` covers+ # both kinds.+ kept = cast_state_dict(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )model.load_state_dict(sd, assign=True, strict=False)_reject_incomplete_load(model, what="Krea-2 single-file checkpoint")+ # `assign=True` aliases every param to its `sd` tensor. Drop the dict's references before+ # the FP8 cast, or each param's `model_dtype` original stays reachable while its fp8 copy is+ # allocated, overshooting the `make_room()` reservation above by ~50%.+ sd.clear()++ if kept and not fp8_layers:+ # Raw fp8: no scales to attach, but say so — otherwise the tensor-core path is invisible,+ # and the only other fp8 log line (the scaled one below) never fires for this checkpoint.+ self._logger.info(+ f"Krea-2: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint); "+ "they will run on the fp8 tensor cores with unit scaling."+ )++ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ self._logger.info(f"Krea-2: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")+ warn_on_unattached_scales(self._logger, "Krea-2", attached, fp8_layers)+ # Marked layers dequantize on every forward instead of using the tensor cores, which is+ # the single biggest lever on how much fp8_compute actually buys for a given checkpoint.+ # Surface it: otherwise "fp8_compute is on but barely faster" has no visible cause.+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)+ if marked:+ if full_precision_hints_respected():+ self._logger.info(+ f"Krea-2: {marked} of {len(fp8_layers)} layer(s) are marked "+ "full_precision_matrix_mult and will dequantize per forward. Set "+ "fp8_compute_full_precision_hints=false to run them on the fp8 tensor cores "+ "instead (faster, but overrides the checkpoint producer's instruction)."+ )+ else:+ self._logger.info(+ f"Krea-2: ignoring the full_precision_matrix_mult marker on {marked} layer(s) "+ "(fp8_compute_full_precision_hints=false)."+ )+ # fp8_storage exists to *create* fp8 weights from full-precision ones; here they already+ # are fp8, so it is bypassed entirely. Say so, otherwise a user who enabled it is left+ # wondering whether it took effect.+ default_settings = getattr(config, "default_settings", None)+ if default_settings is not None and getattr(default_settings, "fp8_storage", None):+ self._logger.info(+ "Krea-2: the model's fp8_storage setting is redundant here and was skipped - the "+ "checkpoint already ships fp8 weights."+ )+ # The layerwise-casting path exists to *produce* fp8 weights from full-precision ones. The+ # checkpoint already is fp8, and its hooks would cast back to the compute dtype without+ # applying weight_scale, so it must not run here.+ return model+# Honor the fp8-storage setting (re-quantizes the dequantized weights to fp8-resident on CUDA).model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)return modeldiff --cc invokeai/backend/model_manager/load/model_loaders/z_image.pyindex b460332ccc,ffda6eaf9c..95c3d663e8--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@@ -24,7 -24,7 +24,11 @@@ from invokeai.backend.model_manager.conQwen3Encoder_SDNQ_Config,Qwen3Encoder_SDNQ_Folder_Config,)--from invokeai.backend.model_manager.load.load_default import ModelLoader, resolve_submodel_path++from invokeai.backend.model_manager.load.load_default import (++ ModelLoader,++ _model_declared_skip_patterns,++ resolve_submodel_path,++)from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistryfrom invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoaderfrom invokeai.backend.model_manager.taxonomy import (@@@ -530,69 -473,29 +534,75 @@@ class ZImageCheckpointModel(ModelLoaderfor k in keys_to_remove:del sd[k]- # Handle memory management and dtype conversion- new_sd_size = sum([ten.nelement() * model_dtype.itemsize for ten in sd.values()])- self._ram_cache.make_room(new_sd_size)+ # ComfyUI 'scaled fp8' (fp8 weight + .weight_scale/.scale_weight). Until now the loader+ # deleted those scales and cast the weight — silently producing a weight off by+ # 1/weight_scale — and had no way to tell such a checkpoint from a raw fp8 one.+ layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}+ fp8_layers = extract_fp8_scaled_layers(sd, layer_hints=layer_hints)++ # Handle memory management and dtype conversion. A checkpoint that ships raw fp8 weights+ # (fp8 tensors, no weight_scale) keeps them when the fp8 matmul is available — casting them+ # here would discard both the VRAM saving and the tensor cores before the model is built.+ keep_fp8 = should_keep_fp8_weights(self._torch_device)+ if fp8_layers and not keep_fp8:+ # Legacy behavior, but now with the scale actually applied: fold it into the weight.+ dequantize_fp8_scaled(sd, fp8_layers, model_dtype)+ fp8_layers = {}++ # Honor the model's own precision-sensitive list. Z-Image declares+ # ["t_embedder", "cap_embedder"], and `TimestepEmbedder.forward` casts its activations to+ # `self.mlp[0].weight.dtype` — an fp8 weight there turns the activations fp8 and the forward+ # dies in `x.abs()`. Those layers must be dequantized even though the rest stays quantized.- skip_patterns = tuple(getattr(model, "_skip_layerwise_casting_patterns", None) or ())++ skip_patterns = _model_declared_skip_patterns(model)+ # Scaled layers that the cast would dequantize anyway are folded here, scale applied, so+ # `cast_state_dict` never strips a scale it cannot put back.+ # Reserve before the split, not after: `split_fp8_scaled_layers` dequantizes its unusable+ # subset through fp32, so reserving afterwards lets that transient peak land on an+ # unreserved cache. The prediction is unaffected by the split -- it applies the same+ # `can_stay_quantized` predicate, so those layers are already counted at `dtype.itemsize`.+ self._ram_cache.make_room(+ predict_cast_state_dict_size(sd, model_dtype, keep_fp8=keep_fp8, model=model, skip_patterns=skip_patterns)+ )- # Convert to target dtype- for k in sd.keys():- sd[k] = sd[k].to(model_dtype)+ fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)+ kept = cast_state_dict(+ sd,+ model_dtype,+ keep_fp8=keep_fp8,+ model=model,+ skip_patterns=skip_patterns,+ )model.load_state_dict(sd, assign=True)+ # `assign=True` aliases every param to its `sd` tensor, so the dict keeps the whole model+ # alive a second time. The FP8 cast below allocates the fp8 copy per param while the+ # `model_dtype` original is still reachable through `sd`, pushing peak RAM to ~1.5x what+ # `make_room()` reserved above (~17.4GB actual vs ~11.5GB reserved for Z-Image). Dropping+ # the dict's references lets each original free as soon as its param is cast.+ sd.clear()- # Every param is uniform `model_dtype` at this point, so the layerwise cast has a single- # unambiguous compute dtype to restore to.- #- # Caveat, pre-existing and not addressed here: for a ComfyUI *scaled*-fp8 checkpoint the- # filter above drops `.scale_weight` / `scaled_fp8` without folding them in, so the raw fp8- # codes are cast to `model_dtype` unscaled and the model loads with wrong weights. That is a- # separate bug in the key filtering, not something this cast makes safe.+ if fp8_layers:+ attached = attach_fp8_scales(model, fp8_layers)+ self._logger.info(f"Z-Image: kept {attached} layer(s) in fp8 (scaled fp8 checkpoint, fp8_compute enabled)")+ warn_on_unattached_scales(self._logger, "Z-Image", attached, fp8_layers)+ marked = sum(1 for layer in fp8_layers.values() if layer.full_precision_matmul)+ if marked and full_precision_hints_respected():+ self._logger.info(+ f"Z-Image: {marked} of {len(fp8_layers)} layer(s) are marked full_precision_matrix_mult "+ "and will dequantize per forward. Set fp8_compute_full_precision_hints=false to run "+ "them on the fp8 tensor cores instead."+ )+ elif kept:+ self._logger.info(+ f"Z-Image: kept {kept} raw fp8 weight(s) quantized (no weight_scale in the checkpoint); "+ "they will run on the fp8 tensor cores with unit scaling."+ )++ # FP8 *storage* on top. When nothing was kept quantized above, every param is uniform+ # `model_dtype` here, so the layerwise cast has one unambiguous compute dtype to restore to.+ # When weights *were* kept fp8, `_apply_fp8_layerwise_casting` bails out on its own (and+ # says so in the log): its hooks would restore the compute dtype before every forward and+ # silently disable the fp8 matmul, for no VRAM saving.model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)return modeldiff --cc tests/backend/model_manager/load/test_load_default_fp8.pyindex fe7aa3f6fb,cd87018aff..30957c4a3a--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@@ -695,87 -695,56 +696,142 @@@ def test_device_supports_fp8_storage_isassert _device_supports_fp8_storage(torch.device("xpu", 1)) is False+ def test_model_declared_skip_patterns_unions_both_diffusers_attributes():+ """`enable_layerwise_casting()` unions `_skip_layerwise_casting_patterns` with+ `_keep_in_fp32_modules`. We replaced that call with our own hook-based path, so we have to read+ both — otherwise a model that declares only the latter loses its exclusions silently.+ """++ class _Model(torch.nn.Module):+ _skip_layerwise_casting_patterns = ["t_embedder"]+ _keep_in_fp32_modules = ["time_embedder"]++ assert _model_declared_skip_patterns(_Model()) == ("t_embedder", "time_embedder")+++ def test_model_declared_skip_patterns_tolerates_missing_and_odd_declarations():+ """Most models declare neither attribute; diffusers sets them to `None` on some. A bare string+ is accepted too, so a subclass that writes one instead of a list isn't silently expanded into+ per-character patterns."""++ class _Bare(torch.nn.Module):+ pass++ class _Nulls(torch.nn.Module):+ _skip_layerwise_casting_patterns = None+ _keep_in_fp32_modules = None++ class _Strings(torch.nn.Module):+ _keep_in_fp32_modules = "time_embedder"++ assert _model_declared_skip_patterns(_Bare()) == ()+ assert _model_declared_skip_patterns(_Nulls()) == ()+ assert _model_declared_skip_patterns(_Strings()) == ("time_embedder",)+++ def test_keep_in_fp32_modules_are_not_cast():+ """End-to-end through the cast: a module named only by `_keep_in_fp32_modules` keeps its+ compute dtype."""++ class _Model(torch.nn.Module):+ _keep_in_fp32_modules = ["time_embedder"]++ def __init__(self):+ super().__init__()+ self.time_embedder = torch.nn.Linear(4, 4)+ self.attn = torch.nn.Linear(4, 4)++ loader = _make_loader(device="cuda")+ model = _Model().to(torch.bfloat16)++ with patch.object(ModelLoader, "_should_use_fp8", return_value=True):+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))++ assert model.time_embedder.weight.dtype == torch.bfloat16+ assert model.attn.weight.dtype == torch.float8_e4m3fn+++++class TestAlreadyFp8StorageGuard:+ """FP8 storage must not run over weights that are already fp8 and headed for the tensor cores.++ Layerwise casting installs a pre-hook that restores the compute dtype before every forward. On+ a scaled-fp8 checkpoint that hook does two things at once: `_can_use_fp8_matmul` no longer sees+ an fp8 weight, so the matmul silently falls back, and the hook upcasts the weight *without*+ applying its `weight_scale`, i.e. a weight off by `1/weight_scale`. Neither is visible in the+ output of a successful generation, so the guard is load-bearing and needs a test that fails if+ it is reverted.+ """++ def _model(self) -> torch.nn.Module:+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))+ model[0].weight = torch.nn.Parameter(+ torch.zeros(32, 16, dtype=torch.float32).to(torch.float8_e4m3fn), requires_grad=False+ )+ return model++ def test_a_model_whose_weights_are_already_fp8_is_left_alone(self) -> None:+ loader = _make_loader("cuda")+ model = self._model()++ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=True):+ result = loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))++ assert result is model+ # No compute-dtype marker means `_apply_fp8_to_nn_module` never ran over it.+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is None+ assert model[0].weight.dtype is torch.float8_e4m3fn++ def test_a_full_precision_model_is_still_cast(self) -> None:+ """The guard must key on the weights, not merely on fp8_compute being enabled."""+ loader = _make_loader("cuda")+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))++ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=True):+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))++ assert model[0].weight.dtype is torch.float8_e4m3fn+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR, None) is not None++ def test_ordinary_storage_casting_is_unaffected_when_the_matmul_is_unavailable(self) -> None:+ """The guard must not become a blanket "skip fp8 storage" once fp8_compute is off.++ Only the already-fp8 case is protected. A full-precision model still gets the storage cast,+ which is the entire point of the toggle on a card without the fp8 matmul.++ (The mirror case -- an already-fp8 model with the matmul *off* -- is unreachable: every+ loader either folds the scales or casts raw fp8 away when `should_keep_fp8_weights` is+ False, so nothing fp8 survives to reach this method. `set_fp8_compute_dtype` refuses it+ outright rather than recording float8 as a compute dtype.)+ """+ loader = _make_loader("cuda")+ model = torch.nn.Sequential(torch.nn.Linear(16, 32))++ with patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=False):+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))++ assert model[0].weight.dtype is torch.float8_e4m3fn+++class TestApplyFp8SkipCallback:+ """The `skip=` callback keeps scaled-fp8 layers out of the storage cast.++ Its one caller (the Qwen3-VL encoder) casts the *unquantized* remainder of a partly-quantized+ checkpoint to fp8 storage while leaving the scaled layers on the matmul path. Without the+ callback those layers would be cast without their scale.+ """++ def test_a_module_the_callback_rejects_is_not_cast(self) -> None:+ model = torch.nn.Sequential()+ model.add_module("keep", torch.nn.Linear(16, 32))+ model.add_module("cast", torch.nn.Linear(16, 32))+ model.keep.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.keep.weight.dtype is not torch.float8_e4m3fn+ assert model.cast.weight.dtype is torch.float8_e4m3fndiff --cc tests/backend/model_manager/load/test_z_image_fp8_wiring.pyindex 0000000000,631dc4a48f..baf2594d93mode 000000,100644..100644--- a/tests/backend/model_manager/load/test_z_image_fp8_wiring.py+++ b/tests/backend/model_manager/load/test_z_image_fp8_wiring.py@@@ -1,0 -1,106 +1,110 @@@+ """Guards for Z-Image's FP8-storage wiring in the single-file loader.++ `_load_from_singlefile` is the only place Z-Image checkpoints reach the layerwise cast, and nothing+ else in the suite observes it: deleting the `_apply_fp8_layerwise_casting` call leaves the whole+ `tests/backend/model_manager` suite green, so the toggle can go back to being rendered-and-inert+ with CI passing.+ """++ from types import SimpleNamespace+ from unittest.mock import MagicMock++ import diffusers+ import safetensors.torch+ import torch++ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_ZImage_Config+ from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageCheckpointModel+ from invokeai.backend.model_manager.taxonomy import SubModelType, ZImageVariantType+++ class _TinyZImageTransformer(torch.nn.Module):+ def __init__(self, **_kwargs) -> None:+ super().__init__()+ # `x_pad_token` is one of the loader's `valid_exact` keys, so it survives key filtering.+ self.x_pad_token = torch.nn.Parameter(torch.empty(2, 2))+++ def _prepare_loader(monkeypatch, tmp_path, state_dict: dict[str, torch.Tensor]):+ checkpoint_path = tmp_path / "z_image.safetensors"+ checkpoint_path.touch()+ config = Main_Checkpoint_ZImage_Config.model_construct(+ path=str(checkpoint_path), variant=ZImageVariantType.Turbo, fp8_storage=True+ )++ monkeypatch.setattr(diffusers, "ZImageTransformer2DModel", _TinyZImageTransformer, raising=False)+ monkeypatch.setattr(safetensors.torch, "load_file", lambda _path: state_dict)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.z_image.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.float32,+ )++ loader = object.__new__(ZImageCheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())++ # The scaled-fp8 path reads the safetensors header (logging if it cannot) and asks the device++ # whether the fp8 matmul is usable, so the stub needs both of those too.++ loader._logger = MagicMock()++ loader._torch_device = torch.device("cpu")+ return loader, config+++ def test_single_file_loader_applies_fp8_layerwise_casting(monkeypatch, tmp_path) -> None:+ """The `fp8_storage` toggle has to reach the cast for Z-Image checkpoints at all."""+ cast_calls: list[tuple[object, object]] = []++ loader, config = _prepare_loader(monkeypatch, tmp_path, {"x_pad_token": torch.ones(2, 2)})+ loader._apply_fp8_layerwise_casting = lambda model, cfg, submodel: (+ cast_calls.append((cfg, submodel)),+ model,+ )[1]++ model = loader._load_from_singlefile(config)++ assert isinstance(model, _TinyZImageTransformer)+ assert torch.equal(model.x_pad_token, torch.ones(2, 2))+ assert cast_calls == [(config, SubModelType.Transformer)]+++ def test_state_dict_is_released_before_the_fp8_cast(monkeypatch, tmp_path) -> None:+ """Peak RAM must not overshoot the `make_room()` reservation.++ `load_state_dict(..., assign=True)` aliases every param to its state-dict tensor. If the dict is+ still holding those references when the FP8 cast runs, `param.data.to(float8)` allocates the fp8+ copy while the original is still reachable, so the model is briefly resident ~1.5x over — about+ 17.4GB actual against an ~11.5GB reservation for Z-Image. Nothing in the loader reads `sd` after+ the load, so the dict must be empty by the time the cast starts.+ """+ state_dict = {"x_pad_token": torch.ones(2, 2)}+ observed_sd_len: list[int] = []++ loader, config = _prepare_loader(monkeypatch, tmp_path, state_dict)+ loader._apply_fp8_layerwise_casting = lambda model, _cfg, _submodel: (+ observed_sd_len.append(len(state_dict)),+ model,+ )[1]++ loader._load_from_singlefile(config)++ assert observed_sd_len == [0]+++ def test_assign_true_really_aliases_the_state_dict() -> None:+ """The premise of the test above: without clearing, the originals stay alive through `sd`.++ If a future torch release stopped aliasing under `assign=True`, `sd.clear()` would become dead+ weight rather than a fix, and this is the test that says so.+ """+ model = _TinyZImageTransformer()+ sd = {"x_pad_token": torch.ones(2, 2)}++ model.load_state_dict(sd, assign=True)++ assert model.x_pad_token.data_ptr() == sd["x_pad_token"].data_ptr()++ # And the cast leaves the state dict's copy behind at the original dtype.+ model.x_pad_token.data = model.x_pad_token.data.to(torch.float16)+ assert sd["x_pad_token"].dtype == torch.float32