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(model-manager): isolate shared weights by FP8 storage policy (#10171)
Nianze Wuf879d201a505
diff --git a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdxindex 0d0899f4a5..5c7bb2f264 100644--- a/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx+++ b/docs/src/content/docs/configuration/Optimization/fp8-storage.mdx@@ -76,7 +76,7 @@ The rows describe full-precision files, unless a row says otherwise. Quantized s| Wan (checkpoint and Diffusers) | Yes || ControlNet (SD1, SD2, SDXL), T2I-Adapter | Yes || VAE | No: visible decode-quality regression |-| Text encoders, tokenizers | No: small models, and FP8 rounding costs text quality. Scaled fp8 single-file encoders (T5-XXL, Qwen3, Qwen3-VL, Qwen2.5-VL, and the FLUX.2 Mistral encoder) keep their fp8 Linear weights packed, with their scales, on any GPU that passes the FP8 test, with no setting. |+| Text encoders, tokenizers | No: small models, and FP8 rounding costs text quality. Scaled fp8 single-file encoders (T5-XXL, Qwen3, Qwen3-VL, Qwen2.5-VL, and the FLUX.2 Mistral encoder) keep their fp8 Linear weights packed, with their scales, on a GPU that passes the FP8 test, with no setting. CPU-only loads unpack them using the CPU's dtype policy (see [Sharing across devices and CPU encoders](#sharing-across-devices-and-cpu-encoders)). || Anima ControlNet-LLLite | No: the adapter is only tens of MB || FLUX.1, FLUX.2, Z-Image and Qwen-Image ControlNets | No: not implemented yet || MiniMax H3 | No: not implemented yet |@@ -142,10 +142,21 @@ without FP8 and the log warns once: `FP8 storage probe failed on <device> (…);<TabItem label="CPU and Apple silicon">Not used. PyTorch can hold FP8 on the CPU, but casting is emulated in software and costs more than the memory saves.With the setting on, the loader returns the model unchanged, without a log line (FLUX.1 and FLUX.2 still log their skip line-for int8 builds, FLUX.3 for int8 and nvfp4 builds). Checkpoints that store FP8 weights are unpacked to BF16 here.+for int8 builds, FLUX.3 for int8 and nvfp4 builds). Checkpoints that store FP8 weights are unpacked using the device's dtype policy: BF16 where supported, otherwise FP32. See+[Sharing across devices and CPU encoders](#sharing-across-devices-and-cpu-encoders).</TabItem></Tabs>+## Sharing across devices and CPU encoders++For the FP8-aware checkpoint and encoder loaders, device caches distinguish policies that retain FP8 weights from those that unpack them, and distinguish their compute dtypes. The ERNIE-Image and SD3 GGUF transformer loaders also distinguish compute dtypes. When PyTorch rejects BF16, loaders using the BF16-safe policy fall back to FP16 on CUDA and FP32 on other devices. Matching policies can reuse the same CPU allocation without another checkpoint read.++For int8 and int4 builds that decline FP8 Storage, mixed-capability devices can also retain separate CPU copies even though the resulting weights are identical.++This choice is made before reading the checkpoint. With `fp8_compute` enabled (off by default), a mixed-capability setup can therefore retain two CPU copies and read a checkpoint twice even when that file contains only BF16 weights. FP8 Storage can likewise separate device caches when its device support differs. This conservative policy avoids reading large files just to decide whether their cached weights can be shared. A transient FP8 probe failure uses the unpacked policy for that load; a later successful probe can leave both copies resident until normal eviction.++**CPU-only Mistral and Qwen3-VL encoders unpack FP8 weights using the CPU's dtype policy**, even on a machine with an FP8-capable GPU. This saves VRAM but increases system RAM compared with retaining the packed weights: approximately 16.8 to 32.3 GiB for the scaled-FP8 Mistral 24B encoder, and 4.4 to 8.9 GiB for Qwen3-VL 4B when unpacked to BF16. Allow more RAM where BF16 is unsupported and FP32 is required. The CPU-only encoder can share its unpacked CPU copy with another load using the same policy; the GPU's packed copy stays separate.+## Turning it on<Steps>diff --git a/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py b/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.pyindex 2fdf129bc3..731adc97f8 100644--- a/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py+++ b/invokeai/app/services/working_memory_calibration/working_memory_calibration_fits.py@@ -28,7 +28,7 @@ from invokeai.app.services.working_memory_calibration.working_memory_calibrationWorkingMemoryCalibrationModelLine,WorkingMemoryCalibrationPixelRange,)-from invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.model_manager.cache_key import model_key_from_cache_keyfrom invokeai.backend.working_memory import fragmentation, user_fitfrom invokeai.backend.working_memory.coefficients import shipped_coefficientsfrom invokeai.backend.working_memory.fingerprint import Environment@@ -191,15 +191,11 @@ def _changed(old: Mapping[str, Optional[str]], new: Mapping[str, Optional[str]])return sorted(key for key in set(old) | set(new) if old.get(key) != new.get(key))-_SUBMODEL_TYPES: Final = frozenset(submodel.value for submodel in SubModelType)--def measured_models(point: CalibrationPoint, run_models: Mapping[str, str]) -> frozenset[str]:"""The models a window is attributed to: the model its run calibrated (`run_models`, by run id), and the model itmeasured, where a submodel's window (`<key>:vae`) counts for its model. The summary shows a model's windows bythis, and resetting the model removes exactly these."""- head, separator, tail = point.model_key.rpartition(":")- measured = head if separator and tail in _SUBMODEL_TYPES else point.model_key+ measured = model_key_from_cache_key(point.model_key)run_model = run_models.get(point.run_id)return frozenset({measured} if run_model is None else {measured, run_model})diff --git a/invokeai/backend/model_manager/cache_key.py b/invokeai/backend/model_manager/cache_key.pynew file mode 100644index 0000000000..0b23e645eb--- /dev/null+++ b/invokeai/backend/model_manager/cache_key.py@@ -0,0 +1,44 @@+"""Model cache identity and measurement ownership, without importing the cache runtime."""++import re+from typing import Optional++from invokeai.backend.model_manager.taxonomy import ModelType, SubModelType++_SUBMODEL_TYPES = frozenset(submodel.value for submodel in SubModelType)+_ROLE_SUFFIXES = frozenset(f"as_{model_type.value}" for model_type in ModelType)+_STORAGE_VARIANT = re.compile(r"(?:fp8-|full-)?(?:float16|bfloat16|float32)(?:-layerwise)?")+_LEGACY_T5_SUBMODELS = frozenset({SubModelType.TextEncoder2.value, SubModelType.TextEncoder3.value})+++def get_model_cache_key(+ model_key: str,+ submodel_type: Optional[SubModelType] = None,+ *,+ role: Optional[ModelType] = None,+ variant: str = "",+) -> str:+ key = f"{model_key}:{submodel_type.value}" if submodel_type else model_key+ if role is not None:+ key = f"{key}:as_{role.value}"+ return f"{key}:storage={variant}" if variant else key+++def model_key_from_cache_key(cache_key: str) -> str:+ """Remove only recognized cache suffixes; model keys themselves may contain colons.++ Keep the legacy T5 decoder. A bare role suffix or an unmarked Qwen dtype can be part of an exact+ historical model ID. Decode roles only with a storage marker and leave unmarked Qwen keys intact.+ """+ head, separator, tail = cache_key.rpartition(":")+ if separator and tail.startswith("storage=") and _STORAGE_VARIANT.fullmatch(tail.removeprefix("storage=")):+ cache_key = head+ model_and_submodel, role_separator, role = head.rpartition(":")+ if role_separator and role in _ROLE_SUFFIXES:+ cache_key = model_and_submodel+ elif separator and _STORAGE_VARIANT.fullmatch(tail):+ _owner, slot_separator, slot = head.rpartition(":")+ if slot_separator and slot in _LEGACY_T5_SUBMODELS:+ cache_key = head+ head, separator, tail = cache_key.rpartition(":")+ return head if separator and tail in _SUBMODEL_TYPES else cache_keydiff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex 46251aa098..979dd07691 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -4,6 +4,7 @@ import copyimport itertoolsimport refrom contextlib import nullcontext+from dataclasses import dataclassfrom logging import Loggerfrom pathlib import Pathfrom typing import Callable, ContextManager, Optional@@ -266,12 +267,35 @@ def _model_declared_skip_patterns(model: torch.nn.Module) -> tuple[str, ...]:return tuple(patterns)-# The construction path is not thread-safe on its own; it monkey-patches process-global torch state-# (see MODEL_LOAD_LOCK). Concurrent callers must hold the MODEL_LOAD_LOCK write lock (see-# _load_and_cache).+@dataclass(frozen=True)+class _LoadDecision:+ config: AnyModelConfig+ submodel_type: Optional[SubModelType]+ device: torch.device+ dtype: torch.dtype+ fp8_compute: bool+ storage_supported: bool+ layerwise_storage: bool+ keep_checkpoint_fp8: bool+++# Construction patches process-global torch state, serialized by MODEL_LOAD_LOCK in _load_and_cache.class ModelLoader(ModelLoaderBase):"""Default implementation of ModelLoaderBase."""+ # Components whose checkpoint decoding can retain float8 even without FP8 Storage.+ # Other components retain their ordinary keys, including tokenizers and VAEs.+ _fp8_checkpoint_submodels: frozenset[SubModelType] = frozenset()+ # Only loaders where None aliases one component declare this. Whole pipelines retain None.+ _default_submodel_type: Optional[SubModelType] = None+ _fixed_dtype: Optional[torch.dtype] = None+ _bfloat16_safe = False+ # These standalone encoders retain checkpoint fp8 whenever the execution device supports storage,+ # independently of a denoiser's FP8 Storage setting. Qwen3-VL also casts its dense remainder.+ _encoder_fp8_storage = False+ _encoder_layerwise_storage = False+ _load_decision: Optional[_LoadDecision] = None+# Optionally set on an instance before `load_model()`: on a cache miss, entered with the caller's config# before MODEL_LOAD_LOCK is taken (entering may block) and exited after it is released; the callable it# yields is called once construction is serialized against cache invalidation, must not block, and False@@ -308,6 +332,8 @@ class ModelLoader(ModelLoaderBase):if not model_path.exists():raise FileNotFoundError(f"Files for model '{model_config.name}' not found at {model_path}")+ # ModelLoadService creates a fresh loader per load; also bound the snapshot if a caller reuses one.+ self._load_decision = Nonecache_record, first_use_claim = self._load_and_cache(model_config, submodel_type)return LoadedModel(config=model_config,@@ -364,10 +390,95 @@ class ModelLoader(ModelLoaderBase):Device caches share one canonical CPU copy per key, which a second device adopts instead of rerunning theloader. A loader whose stored format depends on the device (float8 where supported, the dtype it computes in)- returns the format here, so only devices that build the same weights share a copy. Empty by default. Appended after- the role suffix (`:as_<type>`, see `_load_and_cache`).+ returns the format here, so only devices that build the same weights share a copy. This deliberately+ partitions by policy before reading the file, even if a particular file has no float8 weights."""- return ""+ decision = self._decision(config, submodel_type)+ use_storage = decision.layerwise_storage+ checkpoint = submodel_type in self._fp8_checkpoint_submodels+ if checkpoint:+ keep, dtype = decision.keep_checkpoint_fp8, decision.dtype+ use_storage |= self._encoder_layerwise_storage and decision.storage_supported+ elif (+ self._fp8_storage_asked_for(config, submodel_type)+ and fp8_storage_verdict(config.base, config.type, config.format).supported+ ):+ keep, dtype = use_storage, decision.dtype+ elif (+ self._bfloat16_safe+ and self._fixed_dtype is None+ and submodel_type+ not in {+ SubModelType.Tokenizer,+ SubModelType.Tokenizer2,+ SubModelType.Tokenizer3,+ SubModelType.PromptEnhancerTokenizer,+ SubModelType.Processor,+ SubModelType.Scheduler,+ }+ ):+ keep, dtype = False, decision.dtype+ else:+ return ""+ return f"{'fp8' if keep else 'full'}-{str(dtype).removeprefix('torch.')}{'-layerwise' if use_storage else ''}"++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ if self._fixed_dtype is not None:+ return self._fixed_dtype+ if self._bfloat16_safe or submodel_type in self._fp8_checkpoint_submodels:+ return TorchDevice.choose_bfloat16_safe_dtype(device)+ return self._torch_dtype++ def _decision(self, config: AnyModelConfig, submodel_type: Optional[SubModelType]) -> _LoadDecision:+ """One immutable answer for cache lookup and construction, before either can consume weights.++ Only the active component is retained, not a config-id cache. Single-file pipeline prefetch saves+ and restores its requested component's snapshot while admitting the other components.+ """+ decision = self._load_decision+ if decision is not None and decision.config is config and decision.submodel_type == submodel_type:+ return decision+ device = self._get_execution_device(config, submodel_type) or self._torch_device+ checkpoint = submodel_type in self._fp8_checkpoint_submodels+ layerwise_requested = (+ self._fp8_storage_asked_for(config, submodel_type)+ and fp8_storage_verdict(config.base, config.type, config.format).supported+ )+ compute = checkpoint and should_keep_fp8_weights(device)+ # Do not initialize accelerator runtimes for unrelated components. A failed probe gives this+ # load a conservative full-width key; a later load may retry and keep a separate copy until eviction.+ storage = (layerwise_requested or (checkpoint and self._encoder_fp8_storage)) and _device_supports_fp8_storage(+ device, self._logger+ )+ decision = _LoadDecision(+ config=config,+ submodel_type=submodel_type,+ device=device,+ dtype=self._select_model_dtype(config, submodel_type, device),+ fp8_compute=compute,+ storage_supported=storage,+ layerwise_storage=layerwise_requested and storage,+ keep_checkpoint_fp8=compute or storage,+ )+ self._load_decision = decision+ return decision++ def _storage_format(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType]+ ) -> tuple[bool, torch.dtype]:+ decision = self._decision(config, submodel_type)+ return decision.keep_checkpoint_fp8, decision.dtype++ def _get_cache_key(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:+ if submodel_type is None:+ submodel_type = self._default_submodel_type+ # A role view loads the same files through a different loader and needs its own cache entry.+ role = config.type if getattr(config, "role_of", None) is not None else None+ return get_model_cache_key(+ config.key, submodel_type, role=role, variant=self._cache_key_variant(config, submodel_type)+ )def _load_and_cache(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None@@ -382,15 +493,10 @@ class ModelLoader(ModelLoaderBase):raises after the claim is armed, the claim dies with the frame that holds it and releasesthe hold itself."""+ if submodel_type is None:+ submodel_type = self._default_submodel_typestats_name = ":".join([config.base, config.type, config.name, (submodel_type or "")])- cache_key = get_model_cache_key(config.key, submodel_type)- if getattr(config, "role_of", None) is not None:- # A role view loads the record's files through another config class and loader, so it is its own entry.- # The "<key>:" prefix stays, so dropping or offloading the record still covers it.- cache_key = f"{cache_key}:as_{config.type.value}"- variant = self._cache_key_variant(config, submodel_type)- if variant:- cache_key = f"{cache_key}:{variant}"+ cache_key = self._get_cache_key(config, submodel_type)try:return self._ram_cache.get_with_first_use_claim(key=cache_key, stats_name=stats_name)except IndexError:@@ -544,20 +650,7 @@ class ModelLoader(ModelLoaderBase):def _should_use_fp8(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> bool:"""Check if FP8 layerwise casting should be applied to a model."""- if not self._fp8_storage_asked_for(config, submodel_type):- return False-- # 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-- # 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)+ return self._decision(config, submodel_type).layerwise_storagedef _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.@@ -596,7 +689,11 @@ class ModelLoader(ModelLoaderBase):memory nobody asked to save. `_should_use_fp8` already requires the device to support fp8storage, so an unsupported device keeps the folding path."""- return should_keep_fp8_weights(self._torch_device) or self._should_use_fp8(config, submodel_type)+ return self._decision(config, submodel_type).keep_checkpoint_fp8++ def _uses_fp8_compute(self, device: torch.device) -> bool:+ assert self._load_decision is not None+ return self._load_decision.device == device and self._load_decision.fp8_computedef _fp8_kept_reason(self) -> str:"""Which consumer kept a checkpoint's fp8 weights packed, for the line that reports it.@@ -606,7 +703,7 @@ class ModelLoader(ModelLoaderBase):is the case a reader would most want to tell apart. The storage path also dequantizes oneach forward instead of running on the tensor cores, so the line says so."""- if should_keep_fp8_weights(self._torch_device):+ if self._uses_fp8_compute(self._torch_device):return "fp8_compute, on the fp8 tensor cores"return "FP8 Storage, dequantized per forward"diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.pyindex 090c0f7059..5496fc7e85 100644--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py@@ -15,6 +15,7 @@ import psutilimport torchfrom invokeai.app.util.torch_cuda_allocator import expandable_segments_enabled+from invokeai.backend.model_manager.cache_key import get_model_cache_key # noqa: F401 - public import compatibilityfrom invokeai.backend.model_manager.load.memory_snapshot import MemorySnapshotfrom invokeai.backend.model_manager.load.model_cache.cache_record import CacheRecordfrom invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats@@ -34,7 +35,7 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torchapply_custom_layers_to_model,)from invokeai.backend.model_manager.load.model_util import calc_model_size_by_data-from invokeai.backend.model_manager.taxonomy import AnyModel, SubModelType+from invokeai.backend.model_manager.taxonomy import AnyModelfrom invokeai.backend.util.devices import EmptyCacheOutcome, TorchDevice, device_has_dedicated_vramfrom invokeai.backend.util.level_zero import xpu_device_is_integratedfrom invokeai.backend.util.logging import InvokeAILogger@@ -393,15 +394,6 @@ MODEL_LOAD_LOCK = _ModelLoadReadWriteLock()VRAM_MOVE_PASS_BYTES = 1 << 30-# TODO(ryand): Where should this go? The ModelCache shouldn't be concerned with submodels.-def get_model_cache_key(model_key: str, submodel_type: Optional[SubModelType] = None) -> str:- """Get the cache key for a model based on the optional submodel type."""- if submodel_type:- return f"{model_key}:{submodel_type.value}"- else:- return model_key--def synchronized(method: Callable[..., Any]) -> Callable[..., Any]:"""A decorator that applies the class's self._lock to the method.@@ -1247,8 +1239,8 @@ class ModelCache:Used by the session queue's device-affinity heuristic to prefer pending items whosemodels are already warm on the claiming device. Two properties matter to that caller:- - Entries keyed by `get_model_cache_key` (model key plus optional ``:submodel`` and- ``:as_<type>`` role suffixes) are reported with the suffixes stripped so they match plain model keys. Entries keyed by+ - Entries keyed by `get_model_cache_key` are reported without their optional submodel, role,+ and storage suffixes so they match plain model keys. Entries keyed byfilesystem path (`load_model_from_path`) are excluded: a path - or the bare Windowsdrive letter that splitting ``C:\\...`` on ``:`` would leave - is not a model key, andsuch short strings would corrupt substring-based affinity scoring.@@ -3159,10 +3151,8 @@ class ModelCache:def drop_model(self, model_key: str) -> int:"""Drop all cache entries belonging to a model so the next load rebuilds them.- Cache keys are `<model_key>` or `<model_key>:<submodel>` (see `get_model_cache_key`), plus- `:as_<type>` for a role view of the record (see `ModelLoader._load_and_cache`), so a single model may have- multiple entries. Locked entries - and entries inside a- first-use window (a LoadedModel wrapper obtained but not yet locked) - are marked+ Cache keys start with `<model_key>` and may have submodel, role, and storage suffixes+ (see `get_model_cache_key`). Locked entries and entries inside a first-use window are marked`is_stale` and evicted as soon as the last lock (or the window) releases - without that,a setting toggled during an in-flight generation would survive on the locked entry and quietlyget reused by the next generation.diff --git a/invokeai/backend/model_manager/load/model_loaders/anima.py b/invokeai/backend/model_manager/load/model_loaders/anima.pyindex 69aa59f726..db6d402488 100644--- a/invokeai/backend/model_manager/load/model_loaders/anima.py+++ b/invokeai/backend/model_manager/load/model_loaders/anima.py@@ -5,6 +5,7 @@ from pathlib import Pathfrom typing import Any, Optionalimport accelerate+import torchfrom invokeai.backend.anima.checkpoint_layout import (ANIMA_KEY_PREFIXES,@@ -77,6 +78,13 @@ class AnimaCheckpointModel(ModelLoader):the AnimaTransformer model with the correct architecture parameters."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ return TorchDevice.choose_anima_inference_dtype(device)+def _load_model(self,config: AnyModelConfig,@@ -124,8 +132,7 @@ class AnimaCheckpointModel(ModelLoader):# Strip the transformer-key prefix (`net.` or bundled `model.diffusion_model.`).sd = strip_anima_bundle_prefix(sd)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_anima_inference_dtype(target_device)+ _keep, model_dtype = self._storage_format(config, SubModelType.Transformer)# Two ComfyUI side-channel formats share the `weight` + `weight_scale` layout, and a checkpoint# carries one or the other (Anima-2.9B ships an `int8_tensorwise` build beside its bf16 one).diff --git a/invokeai/backend/model_manager/load/model_loaders/cogview4.py b/invokeai/backend/model_manager/load/model_loaders/cogview4.pyindex 6e8490912b..e78e16123a 100644--- a/invokeai/backend/model_manager/load/model_loaders/cogview4.py+++ b/invokeai/backend/model_manager/load/model_loaders/cogview4.py@@ -20,6 +20,8 @@ from invokeai.backend.model_manager.taxonomy import (class CogView4DiffusersModel(GenericDiffusersLoader):"""Class to load CogView4 main models."""+ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,@@ -39,7 +41,7 @@ class CogView4DiffusersModel(GenericDiffusersLoader):# We force bfloat16 for CogView4 models. It produces black images with float16. I haven't tracked down# specifically which model(s) is/are responsible.- dtype = torch.bfloat16+ dtype = self._decision(config, submodel_type).dtypetry:result: AnyModel = load_class.from_pretrained(model_path,diff --git a/invokeai/backend/model_manager/load/model_loaders/ernie_image.py b/invokeai/backend/model_manager/load/model_loaders/ernie_image.pyindex 5c8c2850a1..9d6fe872b7 100644--- a/invokeai/backend/model_manager/load/model_loaders/ernie_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/ernie_image.py@@ -20,7 +20,6 @@ from invokeai.backend.model_manager.taxonomy import ()from invokeai.backend.quantization.fp8_scaled import load_safetensors_checkpoint, reject_quantized_side_channelfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loader, unpack_ggml_at_load-from invokeai.backend.util.devices import TorchDevice# The geometry of the released ERNIE-Image transformer, from the pipeline's `transformer/config.json`.# A single file carries no config, and `ErnieImageTransformer2DModel`'s own defaults describe a@@ -47,6 +46,8 @@ class ErnieImageDiffusersModel(GenericDiffusersLoader):from a diffusers pipeline directory."""+ _bfloat16_safe = True+def _load_model(self,config: AnyModelConfig,@@ -73,8 +74,7 @@ class ErnieImageDiffusersModel(GenericDiffusersLoader):result: AnyModel = load_class.from_pretrained(model_path, local_files_only=True)return result- target_device = TorchDevice.choose_torch_device()- dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ dtype = self._decision(config, submodel_type).dtypetry:result = load_class.from_pretrained(model_path, torch_dtype=dtype, variant=variant, local_files_only=True)except OSError as e:@@ -94,6 +94,10 @@ class ErnieImageCheckpointModel(ModelLoader):encoder, VAE and (optional) prompt enhancer are separate models, chosen on the loader node."""+ _default_submodel_type = SubModelType.Transformer++ _bfloat16_safe = True+def _load_model(self,config: AnyModelConfig,@@ -109,8 +113,7 @@ class ErnieImageCheckpointModel(ModelLoader):from diffusers import ErnieImageTransformer2DModel- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ model_dtype = self._decision(config, SubModelType.Transformer).dtypesd = load_safetensors_checkpoint(Path(config.path))reject_quantized_side_channel(sd, f"ERNIE-Image checkpoint {Path(config.path).name}")@@ -141,6 +144,9 @@ class ErnieImageGGUFModel(ModelLoader):No `fp8_storage` declaration: FP8 Storage is refused for every quantized format by rule."""+ _default_submodel_type = SubModelType.Transformer+ _bfloat16_safe = True+def _load_model(self,config: AnyModelConfig,@@ -156,8 +162,7 @@ class ErnieImageGGUFModel(ModelLoader):from diffusers import ErnieImageTransformer2DModel- target_device = TorchDevice.choose_torch_device()- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ compute_dtype = self._decision(config, SubModelType.Transformer).dtypesd = gguf_sd_loader(Path(config.path), compute_dtype=compute_dtype)diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.pyindex 5dacf7a0a9..c3708a9daa 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py@@ -72,7 +72,6 @@ from invokeai.backend.model_manager.configs.vae import VAE_Checkpoint_Config_Basfrom invokeai.backend.model_manager.load.fp8_capability import Unimplementedfrom invokeai.backend.model_manager.load.load_default import (ModelLoader,- _device_supports_fp8_storage,_model_declared_skip_patterns,resolve_submodel_path,)@@ -118,7 +117,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,read_safetensors_metadata,reject_quantized_side_channel,- should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,@@ -764,20 +762,13 @@ class T5EncoderSingleFileLoader(ModelLoader):return 0return super().get_size_fs(config, model_path, submodel_type)- def _storage_format(- self, config: AnyModelConfig, submodel_type: Optional[SubModelType]- ) -> tuple[bool, torch.dtype]:- """Whether Linear weights stay float8, and the dtype everything else is held and computed in.+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder2, SubModelType.TextEncoder3})+ _encoder_fp8_storage = True- Decided once per loader (a fresh one serves each load): the cache key and the stored format must agree,- and the capability probes can flip between the key computation and the build under the load lock.- """- device = self._get_execution_device(config, submodel_type) or self._torch_device- decisions = self.__dict__.setdefault("_storage_format_decisions", {})- if device not in decisions:- keep_fp8 = should_keep_fp8_weights(device) or _device_supports_fp8_storage(device, self._logger)- decisions[device] = (keep_fp8, t5_dtype_for_device(device))- return decisions[device]+ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ return t5_dtype_for_device(device)def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:# Both the float8 decision and the dtype depend on the device, and device caches share one canonical CPU@@ -889,6 +880,10 @@ def _transformer_of_flux_bundle(names: dict[str, str]) -> dict[str, str]:class FluxCheckpointModel(ModelLoader):"""Class to load main models."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})++ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,@@ -1161,6 +1156,8 @@ class FluxBnbQuantizednf4bCheckpointModel(ModelLoader):class FluxDiffusersModel(GenericDiffusersLoader):"""Class to load FLUX.1 main models in diffusers format."""+ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,@@ -1179,7 +1176,7 @@ class FluxDiffusersModel(GenericDiffusersLoader):model_path = model_path / submodel_type.value# We force bfloat16 for FLUX models. This is required for correct inference.- dtype = torch.bfloat16+ dtype = self._decision(config, submodel_type).dtypetry:result: AnyModel = load_class.from_pretrained(model_path,@@ -1203,6 +1200,8 @@ class FluxDiffusersModel(GenericDiffusersLoader):class Flux2DiffusersModel(GenericDiffusersLoader):"""Class to load FLUX.2 main models in diffusers format (e.g. FLUX.2 Klein)."""+ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,@@ -1226,7 +1225,7 @@ class Flux2DiffusersModel(GenericDiffusersLoader):# won't be in the checkpoint but the model class still creates them.# We use SilenceWarnings to suppress the "guidance_embeds is not expected" warning# from diffusers Flux2Transformer2DModel.- dtype = torch.bfloat16+ dtype = self._decision(config, submodel_type).dtypewith SilenceWarnings():try:result: AnyModel = load_class.from_pretrained(@@ -1280,6 +1279,10 @@ class Flux2DiffusersModel(GenericDiffusersLoader):class Flux2CheckpointModel(ModelLoader):"""Class to load FLUX.2 transformer models from single-file checkpoints (safetensors)."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})++ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,diff --git a/invokeai/backend/model_manager/load/model_loaders/flux3.py b/invokeai/backend/model_manager/load/model_loaders/flux3.pyindex b8b8b76971..05f1873ea8 100644--- a/invokeai/backend/model_manager/load/model_loaders/flux3.py+++ b/invokeai/backend/model_manager/load/model_loaders/flux3.py@@ -222,6 +222,15 @@ def flux3_transformer_from_single_file(class Flux3DiffusersModel(ModelLoader):"""Loads the submodels of a FLUX.3 Diffusers folder."""+ _bfloat16_safe = True++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ if submodel_type is SubModelType.VAE:+ return TorchDevice.dtype_avoiding_float16(self._torch_dtype, device)+ return super()._select_model_dtype(config, submodel_type, device)+def get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None) -> int:@@ -238,7 +247,7 @@ class Flux3DiffusersModel(ModelLoader):raise ValueError("A submodel type must be provided when loading a FLUX.3 Diffusers model.")model_path = Path(config.path)- dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ dtype = self._decision(config, submodel_type).dtypematch submodel_type:case SubModelType.Transformer:@@ -251,9 +260,7 @@ class Flux3DiffusersModel(ModelLoader):case SubModelType.VAE:from diffusers import AutoencoderKLFlux2- return AutoencoderKLFlux2.from_pretrained(- model_path / "vae", torch_dtype=self._torch_dtype_avoiding_float16(), local_files_only=True- )+ return AutoencoderKLFlux2.from_pretrained(model_path / "vae", torch_dtype=dtype, local_files_only=True)case SubModelType.TextEncoder:encoder_path = model_path / "text_encoder"encoder_config = normalize_qwen3vl_rope_config(@@ -282,6 +289,9 @@ class Flux3CheckpointModel(ModelLoader):"""Loads a FLUX.3 transformer from a single file: bf16 (BFL `model.safetensors`, or its ComfyUI repackage), or oneof the quantized builds `flux3_transformer_from_single_file` reads."""+ _bfloat16_safe = True+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:if not isinstance(config, Main_Checkpoint_Flux3_Config):raise ValueError(f"Unexpected config type {type(config).__name__} for the FLUX.3 single-file loader.")@@ -289,13 +299,13 @@ class Flux3CheckpointModel(ModelLoader):raise ValueError("A single-file FLUX.3 model holds only the transformer.")model_path = Path(config.path)- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ decision = self._decision(config, SubModelType.Transformer)model = flux3_transformer_from_single_file(load_safetensors_checkpoint(model_path),- model_dtype,+ decision.dtype,self._ram_cache.make_room,metadata=read_safetensors_metadata(model_path, self._logger),- keep_fp8=self._keep_fp8_weights(config, SubModelType.Transformer),+ keep_fp8=decision.keep_checkpoint_fp8,logger=self._logger,)if any(isinstance(module, DequantizingLinear) for module in model.modules()):@@ -319,13 +329,19 @@ class Flux3CheckpointModel(ModelLoader):class Flux3GGUFCheckpointModel(ModelLoader):"""Loads a GGUF-quantized FLUX.3 transformer; the GGML tensors stay packed and dequantize per forward."""+ _bfloat16_safe = True++ def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:+ # Packed GGUF weights also carry a compute dtype; only matching devices can share their CPU copy.+ return str(self._decision(config, submodel_type).dtype).removeprefix("torch.")+def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:if not isinstance(config, Main_GGUF_Flux3_Config):raise ValueError(f"Unexpected config type {type(config).__name__} for the FLUX.3 GGUF loader.")if submodel_type is not SubModelType.Transformer:raise ValueError("A GGUF FLUX.3 model holds only the transformer.")- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ compute_dtype = self._decision(config, SubModelType.Transformer).dtypesd = gguf_sd_loader(Path(config.path), compute_dtype=compute_dtype)sd = CheckpointPrefix.detect(sd).strip(sd)diff --git a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py b/invokeai/backend/model_manager/load/model_loaders/ideogram4.pyindex f10cfb8527..d4e9909ae9 100644--- a/invokeai/backend/model_manager/load/model_loaders/ideogram4.py+++ b/invokeai/backend/model_manager/load/model_loaders/ideogram4.py@@ -55,7 +55,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,read_safetensors_metadata,reject_quantized_side_channel,- should_keep_fp8_weights,split_fp8_scaled_layers,warn_on_unattached_scales,)@@ -355,6 +354,8 @@ class Ideogram4CheckpointModel(ModelLoader):nvfp4 is refused at identification, not here."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self,config: AnyModelConfig,@@ -373,8 +374,7 @@ class Ideogram4CheckpointModel(ModelLoader):from invokeai.backend.ideogram4.modeling_ideogram4 import Ideogram4Config, Ideogram4Transformermodel_path = Path(config.path)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ _keep, model_dtype = self._storage_format(config, SubModelType.Transformer)sd: dict[str, torch.Tensor] = load_safetensors_checkpoint(model_path)@@ -496,7 +496,7 @@ class Ideogram4CheckpointModel(ModelLoader):# Only where the matmul is what runs. Kept for FP8 Storage alone, *every* layer# dequantizes per forward, so the hint decides nothing and the advice below would send a# user to override the checkpoint producer for a speedup that cannot happen.- if marked and should_keep_fp8_weights(self._torch_device):+ if marked and self._uses_fp8_compute(self._torch_device):if full_precision_hints_respected():self._logger.info(f"Ideogram 4: {marked} of {len(fp8_layers)} layer(s) are marked "diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 85eaade33e..dfd61944b4 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -24,7 +24,6 @@ from invokeai.backend.model_manager.configs.qwen3_vl_encoder import ()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 ModelLoaderRegistry@@ -62,7 +61,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,read_safetensors_metadata,reattach_layer_sidechannel,- should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,@@ -420,6 +418,8 @@ class Krea2DiffusersModel(GenericDiffusersLoader):pipeline's tokenizer for reference images. Krea-2's edit mode loads both only when a prompt has references."""+ _bfloat16_safe = True+def get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None) -> int:@@ -461,7 +461,7 @@ class Krea2DiffusersModel(GenericDiffusersLoader):return _load_qwen3vl_visual_tower(qwen3vl_visual_tower_files(encoder_path),AutoConfig.from_pretrained(encoder_path, local_files_only=True).vision_config,- TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()),+ self._decision(config, submodel_type).dtype,reserve=self._ram_cache.make_room,)@@ -470,9 +470,8 @@ class Krea2DiffusersModel(GenericDiffusersLoader):variant = repo_variant.value if repo_variant else Nonemodel_path = model_path / submodel_type.value- # Krea-2 prefers bfloat16; use a safe dtype based on target device capabilities.- target_device = TorchDevice.choose_torch_device()- dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ # Reuse the constructor dtype that selected the shared-weight key.+ dtype = self._decision(config, submodel_type).dtypeextra_kwargs: dict[str, Any] = {}if submodel_type is SubModelType.TextEncoder:@@ -527,6 +526,8 @@ class Krea2CheckpointModel(ModelLoader):build, whose layers the header names too, stays packed as `NVFP4Linear`."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self,config: AnyModelConfig,@@ -548,8 +549,7 @@ class Krea2CheckpointModel(ModelLoader):raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")model_path = Path(config.path)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ _keep, model_dtype = self._storage_format(config, SubModelType.Transformer)# Discard what the key conversion below would discard anyway, before anything is spent on# it: not even read. One repack quantizes `last.up` with a blockwise scale grid this decode does not@@ -1071,6 +1071,10 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncoCONFIG_CLASS = Qwen3VLEncoder_Checkpoint_Config+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder})+ _encoder_fp8_storage = True+ _encoder_layerwise_storage = True+def _vision_encoder_nbytes(self, model_path: Path) -> int:return qwen3vl_visual_tower_nbytes([model_path])@@ -1088,8 +1092,10 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncofrom transformers import Qwen3VLModelmodel_path = Path(config.path)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ decision = self._decision(config, SubModelType.TextEncoder)+ keep_matmul_fp8 = decision.fp8_compute+ storage_supported = decision.storage_supported+ model_dtype = decision.dtype# The tower is never read, so never dequantized, cast, copied or reserved for. (The file *header* is still# read below for quantization metadata, which can therefore still name visual layers; those hints match no@@ -1149,17 +1155,9 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncosource_is_fp8 = bool(fp8_layers) or any(getattr(t, "dtype", None) in (torch.float8_e4m3fn, torch.float8_e5m2) for t in sd.values())- # Resolved once. `device_supports_fp8_matmul` deliberately does not cache an inconclusive- # probe, so two calls can disagree: a transient failure here followed by a success below- # would leave the scales already folded while the raw Linears stay quantized, i.e. the- # encoder silently on the storage path with the matmul log line never printed.- keep_matmul_fp8 = should_keep_fp8_weights(target_device)- # Resolved here, next to the matmul probe and for the same reason: the fold below is- # irreversible, so both consumers have to be known before it runs. Asking only about the- # matmul folded the scales away and then let the storage cast re-quantize the result to- # *unscaled* fp8 -- on a scaled checkpoint that is ~3% of the weights lost to underflow,- # for the byte count the file already had.- use_fp8_storage = source_is_fp8 and _device_supports_fp8_storage(self._torch_device, self._logger)+ # Both consumers were snapshotted before the shared-store lookup. Folding is irreversible,+ # so a later successful probe must not change the choice after the scales are gone.+ use_fp8_storage = source_is_fp8 and storage_supported# Every layer that arrived scaled, before the split folds the ones the matmul cannot take. The storage# pass below must leave those alone: cast again, they would be re-quantized *without* their scale.diff --git a/invokeai/backend/model_manager/load/model_loaders/ltx2.py b/invokeai/backend/model_manager/load/model_loaders/ltx2.pyindex 2f90cabe93..d5c455aace 100644--- a/invokeai/backend/model_manager/load/model_loaders/ltx2.py+++ b/invokeai/backend/model_manager/load/model_loaders/ltx2.py@@ -236,10 +236,9 @@ class _LTX2ComponentLoading:model = factory()return _assign_state_dict(model, sd, what)- def _load_video_vae(self, path: Path) -> AnyModel:+ def _load_video_vae(self, path: Path, dtype: torch.dtype) -> AnyModel:from diffusers import AutoencoderKLLTX2Video- dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())sd = cc.convert_video_vae_keys(_read_dense_component(path, "LTX-2 video VAE", self._logger))return self._build_dense(lambda: AutoencoderKLLTX2Video(**cc.LTX2_5_VIDEO_VAE_CONFIG), sd, "LTX-2 video VAE", dtype@@ -269,7 +268,7 @@ class _LTX2ComponentLoading:def _load_connectors(self, config: Main_Diffusers_LTX2_Config) -> AnyModel:from diffusers.pipelines.ltx2.connectors import LTX2TextConnectors- dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ dtype = self._decision(config, SubModelType.Connectors).dtypesd: dict[str, torch.Tensor] = {}for role in _SUBMODEL_ROLES[SubModelType.Connectors]:path = _component_path(config, role)@@ -284,10 +283,9 @@ class _LTX2ComponentLoading:lambda: LTX2TextConnectors(**cc.LTX2_5_CONNECTORS_CONFIG), sd, "LTX-2 text connectors", dtype)- def _load_upsampler(self, path: Path, temporal: bool) -> AnyModel:+ def _load_upsampler(self, path: Path, temporal: bool, dtype: torch.dtype) -> AnyModel:from diffusers.pipelines.ltx2.latent_upsampler import LTX2LatentUpsamplerModel- dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())what = "LTX-2 temporal latent upsampler" if temporal else "LTX-2 spatial latent upsampler"params = cc.LTX2_5_TEMPORAL_UPSAMPLER_CONFIG if temporal else cc.LTX2_5_SPATIAL_UPSAMPLER_CONFIGsd = _read_dense_component(path, what, self._logger)@@ -303,7 +301,7 @@ class _LTX2ComponentLoading:from safetensors.torch import load_fileassert isinstance(self, ModelLoader)- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ model_dtype = self._decision(config, SubModelType.Transformer).dtypewhat = "LTX-2 transformer"reject_formats_declared_in_the_header(@@ -405,6 +403,15 @@ class _LTX2ComponentLoading:class LTX2FolderModel(_LTX2ComponentLoading, ModelLoader):"""Loader for an LTX-2 component folder (and its transformer, when the folder has one)."""+ _bfloat16_safe = True++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ if submodel_type in (SubModelType.AudioVAE, SubModelType.Vocoder):+ return torch.float32+ return super()._select_model_dtype(config, submodel_type, device)+def get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None) -> int:@@ -434,7 +441,9 @@ class LTX2FolderModel(_LTX2ComponentLoading, ModelLoader):)return self._load_transformer_from_file(_component_path(config, layout.ROLE_TRANSFORMER), config)case SubModelType.VAE:- return self._load_video_vae(_component_path(config, layout.ROLE_VIDEO_VAE))+ return self._load_video_vae(+ _component_path(config, layout.ROLE_VIDEO_VAE), self._decision(config, submodel_type).dtype+ )case SubModelType.AudioVAE:return self._load_audio_vae(_component_path(config, layout.ROLE_AUDIO_VAE))case SubModelType.Vocoder:@@ -442,9 +451,17 @@ class LTX2FolderModel(_LTX2ComponentLoading, ModelLoader):case SubModelType.Connectors:return self._load_connectors(config)case SubModelType.LatentUpsampler:- return self._load_upsampler(_component_path(config, layout.ROLE_SPATIAL_UPSAMPLER), temporal=False)+ return self._load_upsampler(+ _component_path(config, layout.ROLE_SPATIAL_UPSAMPLER),+ temporal=False,+ dtype=self._decision(config, submodel_type).dtype,+ )case SubModelType.TemporalLatentUpsampler:- return self._load_upsampler(_component_path(config, layout.ROLE_TEMPORAL_UPSAMPLER), temporal=True)+ return self._load_upsampler(+ _component_path(config, layout.ROLE_TEMPORAL_UPSAMPLER),+ temporal=True,+ dtype=self._decision(config, submodel_type).dtype,+ )case SubModelType.TextEncoder | SubModelType.Tokenizer:raise ValueError("LTX-2 component folders carry no text encoder. The Gemma-4 encoder is its own model record; "@@ -458,6 +475,8 @@ class LTX2FolderModel(_LTX2ComponentLoading, ModelLoader):class LTX2CheckpointModel(_LTX2ComponentLoading, ModelLoader):"""Loader for LTX-2 single-file transformers (bf16, Comfy int8-convrot or header-named nvfp4)."""+ _bfloat16_safe = True+def _load_model(self,config: AnyModelConfig,diff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex 07fead4003..48881dad79 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -46,7 +46,6 @@ from invokeai.backend.model_manager.configs.mistral_encoder import ()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 ModelLoaderRegistry@@ -79,7 +78,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,read_safetensors_metadata,reject_undecoded_mx_scale,- should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,@@ -1127,6 +1125,10 @@ class MistralEncoderDiffusersLoader(ModelLoader):class MistralEncoderCheckpointLoader(ModelLoader):"""Load a Mistral encoder from a single safetensors file (text-only)."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder})++ _encoder_fp8_storage = True+def _load_model(self,config: AnyModelConfig,@@ -1149,8 +1151,7 @@ class MistralEncoderCheckpointLoader(ModelLoader):def _load_text_encoder(self, config: MistralEncoder_Checkpoint_Config) -> AnyModel:logger = InvokeAILogger.get_logger(self.__class__.__name__)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ keep_fp8, model_dtype = self._storage_format(config, SubModelType.TextEncoder)model_path = Path(config.path)@@ -1209,7 +1210,6 @@ class MistralEncoderCheckpointLoader(ModelLoader):# placed after it would never run on the device almost everyone loads on.reject_int8_layers_a_plain_fold_cannot_decode(sd, "This Mistral encoder checkpoint")- keep_fp8 = should_keep_fp8_weights(target_device) or _device_supports_fp8_storage(target_device, logger)fp8_layers: dict[str, Any] = {}if keep_fp8:layer_hints = {**extract_comfy_quant_hints(sd), **header_hints}diff --git a/invokeai/backend/model_manager/load/model_loaders/moss_image.py b/invokeai/backend/model_manager/load/model_loaders/moss_image.pyindex 0bf6974da0..3ab283af96 100644--- a/invokeai/backend/model_manager/load/model_loaders/moss_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/moss_image.py@@ -201,6 +201,8 @@ def _reject_other_quantization_beside_torchao(sd: Mapping[str, Any], what: str)class _MossImageTransformerLoading(ModelLoader):"""The transformer load both MOSS-Image formats share, once each has a state dict and a geometry."""+ _bfloat16_safe = True+def _load_transformer(self,config: AnyModelConfig,@@ -216,7 +218,7 @@ class _MossImageTransformerLoading(ModelLoader):markers = extract_int8_convrot_markers(sd)# Outside the int8 branch, so an int8 weight whose marker is missing or unreadable is refused, not cast as codes.reject_unmarked_int8_weights(sd, markers, "MOSS-Image")- dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ dtype = self._decision(config, SubModelType.Transformer).dtypewith accelerate.init_empty_weights():model = MOSSImageTransformer(**geometry)@@ -295,6 +297,15 @@ class _MossImageTransformerLoading(ModelLoader):class MossImageDiffusersModel(_MossImageTransformerLoading):"""Loads MOSS-Image submodels from a diffusers pipeline folder (MOSS-Image Base or SFT)."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder})++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ if submodel_type is SubModelType.VAE:+ return TorchDevice.dtype_avoiding_float16(self._torch_dtype, device)+ return super()._select_model_dtype(config, submodel_type, device)+def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:if not isinstance(config, Main_Diffusers_MossImage_Config):raise ValueError(f"Expected Main_Diffusers_MossImage_Config, got {type(config).__name__}.")@@ -319,7 +330,7 @@ class MossImageDiffusersModel(_MossImageTransformerLoading):# The FLUX.2 VAE loaders' dtype: never float16, in which the FLUX autoencoders break.return AutoencoderKLFlux2.from_pretrained(- model_path / "vae", torch_dtype=self._torch_dtype_avoiding_float16(), local_files_only=True+ model_path / "vae", torch_dtype=self._decision(config, submodel_type).dtype, local_files_only=True)raise ValueError(@@ -337,14 +348,16 @@ class MossImageDiffusersModel(_MossImageTransformerLoading):shards = list(moss_image_component_shards(text_encoder_dir))# No FP8 Storage cast follows: text encoders never take it (`_FP8_EXCLUDED_SUBMODEL_TYPES`). `keep_fp8` only# keeps a raw-fp8 checkpoint packed for the fp8 matmul.+ keep_fp8, model_dtype = self._storage_format(config, SubModelType.TextEncoder)return load_qwen3_5_text_encoder(self,shards,text_config,# MOSS-Image reads the last hidden state, after the final norm.final_norm=True,- keep_fp8=self._keep_fp8_weights(config, SubModelType.TextEncoder),+ keep_fp8=keep_fp8,what=f"MOSS-Image text encoder in {Path(config.path).name}",+ model_dtype=model_dtype,)@@ -356,6 +369,9 @@ class MossImageCheckpointModel(_MossImageTransformerLoading):models, chosen on the loader node."""+ _default_submodel_type = SubModelType.Transformer+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:if not isinstance(config, Main_Checkpoint_MossImage_Config):raise ValueError(f"Expected Main_Checkpoint_MossImage_Config, got {type(config).__name__}.")diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py b/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.pyindex 3e9a42da87..2a4110535b 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen3_5_encoder.py@@ -71,6 +71,7 @@ def load_qwen3_5_text_encoder(final_norm: bool,keep_fp8: bool,what: str,+ model_dtype: Optional[torch.dtype] = None,) -> "Qwen35Encoder":"""Build a `Qwen35Encoder` from the language-model tensors of a safetensors file or of a model's shards.@@ -85,11 +86,11 @@ def load_qwen3_5_text_encoder(final_norm: Build and load the final norm, for a caller that reads the last hidden state. Thecheckpoint must then ship `norm.weight` and every layer whole.keep_fp8: Whether a raw-fp8 checkpoint's weights stay packed rather than widened: the calling- loader's `_keep_fp8_weights` answer, asked by the caller because `test_fp8_capability.py`- can only see the fp8 helpers reached through a loader's own methods. For an encoder that- means the fp8 matmul: text encoders never take FP8 Storage's layerwise cast+ loader's snapshotted storage decision. For an encoder that means the fp8 matmul:+ text encoders never take FP8 Storage's layerwise cast(`_FP8_EXCLUDED_SUBMODEL_TYPES`).what: Names the checkpoint in errors and log lines.+ model_dtype: The calling loader's snapshotted dtype; direct callers may use the session default."""from invokeai.backend.qwen3_5.qwen3_5_encoder import Qwen35Encoder@@ -124,7 +125,8 @@ def load_qwen3_5_text_encoder(layer.post_attention_layernorm = nn.Identity()loader._logger.info(f"Qwen3.5 encoder: layer {index} ships without an MLP; running it attention-only.")- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ if model_dtype is None:+ model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())skip_patterns = _model_declared_skip_patterns(model)markers = extract_int8_convrot_markers(sd)# Outside the int8 branch, so an int8 weight whose marker is missing is refused, not cast as codes.@@ -175,6 +177,8 @@ def load_qwen3_5_text_encoder(class Qwen35EncoderCheckpointLoader(ModelLoader):"""Loads a single-file Qwen3.5 text encoder and the vendored Qwen3.5 tokenizer."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder})+def get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None) -> int:@@ -204,6 +208,7 @@ class Qwen35EncoderCheckpointLoader(ModelLoader):from invokeai.backend.qwen3_5.qwen3_5_encoder import qwen3_5_text_configmodel_path = Path(config.path)+ keep_fp8, model_dtype = self._storage_format(config, SubModelType.TextEncoder)model = load_qwen3_5_text_encoder(self,[model_path],@@ -211,7 +216,8 @@ class Qwen35EncoderCheckpointLoader(ModelLoader):# MOSS-Image reads the 9B after its final norm. Anima-3.8B reads intermediate layers of the 4B,# and its checkpoint keeps a projection head under `norm.*` instead.final_norm=config.variant in QWEN3_5_FINAL_NORM_VARIANTS,- keep_fp8=self._keep_fp8_weights(config, SubModelType.TextEncoder),+ keep_fp8=keep_fp8,what=f"Qwen3.5 encoder checkpoint {model_path.name}",+ model_dtype=model_dtype,)return self._apply_fp8_layerwise_casting(model, config, SubModelType.TextEncoder)diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image.pyindex 04b030a057..b3b663d26f 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image.py@@ -18,7 +18,6 @@ from invokeai.backend.model_manager.configs.qwen_vl_encoder import ()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 ModelLoaderRegistry@@ -45,7 +44,6 @@ from invokeai.backend.quantization.fp8_scaled import (load_safetensors_checkpoint,parse_quantization_metadata,read_safetensors_metadata,- should_keep_fp8_weights,split_fp8_scaled_layers,strip_layer_path_prefix,warn_on_unattached_scales,@@ -171,6 +169,8 @@ def _build_qwen_image_transformer_config(sd: dict, is_edit: bool) -> dict:class QwenImageDiffusersModel(GenericDiffusersLoader):"""Class to load Qwen Image Edit main models."""+ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,@@ -197,7 +197,8 @@ class QwenImageDiffusersModel(GenericDiffusersLoader):# We force bfloat16 for Qwen Image Edit models.# Use `dtype` (newer) with fallback to `torch_dtype` (older diffusers).- dtype_kwarg = {"dtype": torch.bfloat16}+ dtype = self._decision(config, submodel_type).dtype+ dtype_kwarg = {"dtype": dtype}try:result: AnyModel = load_class.from_pretrained(model_path,@@ -207,7 +208,7 @@ class QwenImageDiffusersModel(GenericDiffusersLoader):)except TypeError:# Older diffusers uses torch_dtype instead of dtype- dtype_kwarg = {"torch_dtype": torch.bfloat16}+ dtype_kwarg = {"torch_dtype": dtype}result = load_class.from_pretrained(model_path,**dtype_kwarg,@@ -278,6 +279,8 @@ class QwenImageCheckpointModel(ModelLoader):`default_settings.fp8_storage` is on (which then also casts the dense remainder to fp8);otherwise they are dequantized to bf16 at load time. A file carries int8 or scaled fp8, not both."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self,config: AnyModelConfig,@@ -306,8 +309,7 @@ class QwenImageCheckpointModel(ModelLoader):raise TypeError(f"Expected Main_Checkpoint_QwenImage_Config, got {type(config).__name__}.")model_path = Path(config.path)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ keep_checkpoint_fp8, model_dtype = self._storage_format(config, SubModelType.Transformer)sd = load_safetensors_checkpoint(str(model_path))sd = CheckpointPrefix.detect(sd).strip(sd)@@ -349,7 +351,7 @@ class QwenImageCheckpointModel(ModelLoader):# Without either, a dequantize per forward would cost speed for memory nobody asked to save, so they are# folded.use_fp8_storage = bool(fp8_layers) and self._should_use_fp8(config, SubModelType.Transformer)- keep_fp8 = bool(fp8_layers) and (should_keep_fp8_weights(target_device) or use_fp8_storage)+ keep_fp8 = bool(fp8_layers) and keep_checkpoint_fp8is_edit = getattr(config, "variant", None) == QwenImageVariantType.Editmodel_config = _build_qwen_image_transformer_config(sd, is_edit=is_edit)@@ -486,29 +488,8 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):`invokeai.backend.qwen2_5_vl`, so this encoder loads with no network access."""- def _storage_format(self, config: AnyModelConfig) -> tuple[bool, torch.dtype]:- """Whether float8 Linear weights stay float8, and the compute dtype everything else is held in.-- Decided once per loader (a fresh one serves each load): the cache key and the built weights must agree, and the- capability probes can flip between the key computation and the build under the load lock. Float8 follows the- execution device, because a CPU-only encoder reads its weights on the CPU whatever the session's device is.- """- device = self._get_execution_device(config, SubModelType.TextEncoder) or self._torch_device- decisions = self.__dict__.setdefault("_storage_format_decisions", {})- if device not in decisions:- keep_fp8 = should_keep_fp8_weights(device) or _device_supports_fp8_storage(device, self._logger)- decisions[device] = (keep_fp8, TorchDevice.choose_bfloat16_safe_dtype(self._torch_device))- return decisions[device]-- def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:- # Device caches share one canonical CPU copy per key: a device must not adopt float8 it cannot hold, nor folded- # weights that throw away a capable device's saving. The visual tower is part of the text encoder's module, so- # it is covered too. Keyed by the device's decision, not the file's contents, which would take a header read- # on every cache lookup.- if submodel_type == SubModelType.TextEncoder:- keep_fp8, dtype = self._storage_format(config)- return f"{'fp8-' if keep_fp8 else ''}{str(dtype).removeprefix('torch.')}"- return ""+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder})+ _encoder_fp8_storage = Truedef _load_model(self,@@ -539,7 +520,7 @@ class QwenVLEncoderCheckpointLoader(ModelLoader):model_path = Path(config.path)- device_keeps_fp8, model_dtype = self._storage_format(config)+ device_keeps_fp8, model_dtype = self._storage_format(config, SubModelType.TextEncoder)sd = load_safetensors_checkpoint(str(model_path))header_layers = parse_quantization_metadata(read_safetensors_metadata(model_path, logger))diff --git a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.pyindex 6b06bc0321..7686ae6188 100644--- a/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py+++ b/invokeai/backend/model_manager/load/model_loaders/qwen_image_2_1.py@@ -76,13 +76,22 @@ class QwenImage21DiffusersModel(GenericDiffusersLoader):cached encoder while they encode. The language model's weights are cached once for both."""+ _bfloat16_safe = True++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ if submodel_type is SubModelType.VAE:+ return TorchDevice.dtype_avoiding_float16(self._torch_dtype, device)+ return super()._select_model_dtype(config, submodel_type, device)+def get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None) -> int:if submodel_type is SubModelType.VisionEncoder:# A few hundred tensors of the encoder's folder, not the folder: reserving its ~17 GB for the tower# would evict models for nothing. Sized at the dtype they load in, whatever the file stores.- element_size = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device()).itemsize+ element_size = self._decision(config, submodel_type).dtype.itemsizereturn sum(math.prod(shape) * element_sizefor _shard, _key, shape in _vision_tower_tensors(model_path / SubModelType.TextEncoder.value)@@ -105,12 +114,7 @@ class QwenImage21DiffusersModel(GenericDiffusersLoader):return AutoProcessor.from_pretrained(model_path / "processor", local_files_only=True)- if submodel_type is SubModelType.VAE:- # The configured precision, except float16, which is unstable on this autoencoder: bfloat16 where the- # device has it, float32 otherwise.- dtype = self._torch_dtype_avoiding_float16()- else:- dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ dtype = self._decision(config, submodel_type).dtypeif submodel_type is SubModelType.VisionEncoder:tower = _load_vision_tower(model_path / SubModelType.TextEncoder.value, dtype)@@ -213,6 +217,8 @@ class QwenImage21CheckpointModel(ModelLoader):split before any quantization side channel is read, so every quantized layer names a diffusers Linear."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> AnyModel:if not isinstance(config, Main_Checkpoint_QwenImage21_Config):raise TypeError(f"Expected Main_Checkpoint_QwenImage21_Config, got {type(config).__name__}.")@@ -220,7 +226,7 @@ class QwenImage21CheckpointModel(ModelLoader):raise ValueError(f"Only the transformer is in a single file. Received: {submodel_type}")model_path = Path(config.path)- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(TorchDevice.choose_torch_device())+ _keep, model_dtype = self._storage_format(config, SubModelType.Transformer)sd = load_safetensors_checkpoint(model_path)sd = CheckpointPrefix.detect(sd).strip(sd)diff --git a/invokeai/backend/model_manager/load/model_loaders/sd3.py b/invokeai/backend/model_manager/load/model_loaders/sd3.pyindex 51326a1502..31cf2726c5 100644--- a/invokeai/backend/model_manager/load/model_loaders/sd3.py+++ b/invokeai/backend/model_manager/load/model_loaders/sd3.py@@ -4,6 +4,7 @@ from pathlib import Pathfrom typing import Optionalimport accelerate+import torchfrom invokeai.backend.model_manager.checkpoint_prefix import CheckpointPrefixfrom invokeai.backend.model_manager.configs.factory import AnyModelConfig@@ -17,6 +18,7 @@ from invokeai.backend.sd3.checkpoint_layout import (is_mmdit_transformer_key,sd3_transformer_config,)+from invokeai.backend.util.devices import TorchDevicefrom invokeai.backend.util.state_dict_loading import reject_incomplete_load@@ -31,6 +33,14 @@ class SD3GGUFModel(ModelLoader):VAE are separate models, chosen on the SD3 model loader node."""+ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ return TorchDevice.choose_torch_dtype(device)++ def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:+ return f"full-{str(self._decision(config, submodel_type).dtype).removeprefix('torch.')}"+def get_size_fs(self, config: AnyModelConfig, model_path: Path, submodel_type: Optional[SubModelType] = None) -> int:@@ -53,7 +63,8 @@ class SD3GGUFModel(ModelLoader):from diffusers.models.transformers.transformer_sd3 import SD3Transformer2DModel# A bundled VAE or text encoder is never read: only the transformer is this model's.- sd = gguf_sd_loader(Path(config.path), compute_dtype=self._torch_dtype, keep=is_mmdit_transformer_key)+ dtype = self._decision(config, SubModelType.Transformer).dtype+ sd = gguf_sd_loader(Path(config.path), compute_dtype=dtype, keep=is_mmdit_transformer_key)sd = CheckpointPrefix.detect(sd).strip(sd, drop_foreign=True)transformer_config = sd3_transformer_config(sd)sd = convert_mmdit_to_diffusers(sd, transformer_config)diff --git a/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py b/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.pyindex caaf72db81..e52acacdce 100644--- a/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py+++ b/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py@@ -22,7 +22,6 @@ from invokeai.backend.model_manager.configs.main import (Main_Diffusers_SDXL_Config,Main_Diffusers_SDXLRefiner_Config,)-from invokeai.backend.model_manager.load.model_cache.model_cache import get_model_cache_keyfrom 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 (@@ -152,12 +151,17 @@ class StableDiffusionDiffusersModel(GenericDiffusersLoader):if subtype == submodel_type:continueif submodel := getattr(pipeline, subtype.value, None):- self._apply_fp8_layerwise_casting(submodel, config, subtype)+ requested_decision = self._load_decision+ try:+ cache_key = self._get_cache_key(config, subtype)+ self._apply_fp8_layerwise_casting(submodel, config, subtype)+ finally:+ self._load_decision = requested_decision# prefetch: nothing will get()/lock() these submodels during this load, so they# must be admitted without the post-admission grace — otherwise the never-used# records would be skipped by budget reconciles until some later admission on# this cache sweeps the stale flags.- self._ram_cache.put(get_model_cache_key(config.key, subtype), model=submodel, prefetch=True)+ self._ram_cache.put(cache_key, model=submodel, prefetch=True)result = getattr(pipeline, submodel_type.value)result = self._apply_fp8_layerwise_casting(result, config, submodel_type)return resultdiff --git a/invokeai/backend/model_manager/load/model_loaders/wan.py b/invokeai/backend/model_manager/load/model_loaders/wan.pyindex ac3cb3f372..f50b176437 100644--- a/invokeai/backend/model_manager/load/model_loaders/wan.py+++ b/invokeai/backend/model_manager/load/model_loaders/wan.py@@ -91,6 +91,8 @@ class WanDiffusersModel(GenericDiffusersLoader):class for each submodel via the parent loader's ``get_hf_load_class``."""+ _fixed_dtype = torch.bfloat16+def _load_model(self,config: AnyModelConfig,@@ -137,12 +139,13 @@ class WanDiffusersModel(GenericDiffusersLoader):# bfloat16 across the board: matches Diffusers WanPipeline reference and# avoids the fp16 instability seen in the Wan VAE.+ dtype = self._decision(config, submodel_type).dtypetry:- result: AnyModel = _load_with_variant_fallback({"dtype": torch.bfloat16})+ result: AnyModel = _load_with_variant_fallback({"dtype": dtype})except TypeError:# Older diffusers releases use torch_dtype instead of dtype.- result = _load_with_variant_fallback({"torch_dtype": torch.bfloat16})- _copy_tensors_left_on_the_mapping(result, torch.bfloat16)+ result = _load_with_variant_fallback({"torch_dtype": dtype})+ _copy_tensors_left_on_the_mapping(result, dtype)# This override exists to force bfloat16, and in doing so it replaced the parent's whole# `_load_model` -- including the cast at `GenericDiffusersLoader._load_model`, which every@@ -551,6 +554,9 @@ class WanCheckpointModel(ModelLoader):WanModelLoaderInvocation layer."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+ _bfloat16_safe = True+def _load_model(self,config: AnyModelConfig,@@ -577,8 +583,7 @@ class WanCheckpointModel(ModelLoader):logger = InvokeAILogger.get_logger(self.__class__.__name__)model_path = Path(config.path)- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ model_dtype = self._decision(config, SubModelType.Transformer).dtype# Everything up to the read -- the prefix, what is dropped, how the file is quantized, the reservation -- is# decided on the header's `meta` tensors, so a bundled VAE or text encoder is never read and the cache makesdiff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.pyindex 1084e0e2c8..c8f72775e7 100644--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py@@ -27,7 +27,6 @@ from invokeai.backend.model_manager.configs.qwen3_encoder import (from invokeai.backend.model_manager.load.fp8_capability import Unimplementedfrom invokeai.backend.model_manager.load.load_default import (ModelLoader,- _device_supports_fp8_storage,_model_declared_skip_patterns,resolve_submodel_path,)@@ -59,7 +58,6 @@ from invokeai.backend.quantization.fp8_scaled import (parse_quantization_metadata,read_safetensors_metadata,reject_quantized_side_channel,- should_keep_fp8_weights,split_fp8_scaled_layers,split_qkv_sidechannel,strip_layer_path_prefix,@@ -243,6 +241,14 @@ def _convert_z_image_gguf_to_diffusers(sd: dict[str, Any]) -> dict[str, Any]:class ZImageDiffusersModel(GenericDiffusersLoader):"""Class to load Z-Image main models (Z-Image-Turbo, Z-Image-Base, Z-Image-Edit)."""+ _bfloat16_safe = True++ def _select_model_dtype(+ self, config: AnyModelConfig, submodel_type: Optional[SubModelType], device: torch.device+ ) -> torch.dtype:+ # Pipeline weights use the session dtype even when its text encoder is placed on CPU.+ return super()._select_model_dtype(config, submodel_type, self._torch_device)+def _load_model(self,config: AnyModelConfig,@@ -256,21 +262,19 @@ class ZImageDiffusersModel(GenericDiffusersLoader):model_path = Path(config.path)submodel_path = resolve_submodel_path(config, submodel_type, model_path / submodel_type.value)+ dtype = self._decision(config, submodel_type).dtype# Check if submodel folder has SDNQ quantization - if so, use SDNQ loaderif self._is_sdnq_folder(submodel_path):if submodel_type == SubModelType.TextEncoder:- return self._load_sdnq_text_encoder(submodel_path)+ return self._load_sdnq_text_encoder(submodel_path, dtype)elif submodel_type == SubModelType.Transformer:- return self._load_sdnq_transformer(submodel_path)+ return self._load_sdnq_transformer(submodel_path, dtype)load_class = self.get_hf_load_class(model_path, submodel_type)repo_variant = config.repo_variant if isinstance(config, Diffusers_Config_Base) else Nonevariant = repo_variant.value if repo_variant else None- # Z-Image prefers bfloat16, but use safe dtype based on target device capabilities.- target_device = TorchDevice.choose_torch_device()- dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)try:result: AnyModel = load_class.from_pretrained(submodel_path,@@ -295,7 +299,7 @@ class ZImageDiffusersModel(GenericDiffusersLoader):"""return is_sdnq_folder(folder_path)- def _load_sdnq_text_encoder(self, text_encoder_path: Path) -> AnyModel:+ def _load_sdnq_text_encoder(self, text_encoder_path: Path, compute_dtype: torch.dtype) -> AnyModel:"""Load SDNQ-quantized text encoder from folder."""from transformers import Qwen3Config, Qwen3ForCausalLM@@ -305,9 +309,6 @@ class ZImageDiffusersModel(GenericDiffusersLoader):logger = InvokeAILogger.get_logger(self.__class__.__name__)logger.info(f"Loading SDNQ-quantized text encoder from {text_encoder_path}")- target_device = TorchDevice.choose_torch_device()- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)-# Load the SDNQ state dictsd = sdnq_sd_loader(text_encoder_path, compute_dtype=compute_dtype)@@ -420,7 +421,7 @@ class ZImageDiffusersModel(GenericDiffusersLoader):return model- def _load_sdnq_transformer(self, transformer_path: Path) -> AnyModel:+ def _load_sdnq_transformer(self, transformer_path: Path, compute_dtype: torch.dtype) -> AnyModel:"""Load SDNQ-quantized transformer from folder."""from diffusers import ZImageTransformer2DModel@@ -430,9 +431,6 @@ class ZImageDiffusersModel(GenericDiffusersLoader):logger = InvokeAILogger.get_logger(self.__class__.__name__)logger.info(f"Loading SDNQ-quantized transformer from {transformer_path}")- target_device = TorchDevice.choose_torch_device()- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)-# Load the SDNQ state dictsd = sdnq_sd_loader(transformer_path, compute_dtype=compute_dtype)@@ -469,6 +467,8 @@ class ZImageDiffusersModel(GenericDiffusersLoader):class ZImageCheckpointModel(ModelLoader):"""Class to load Z-Image transformer models from single-file checkpoints (safetensors, etc)."""+ _fp8_checkpoint_submodels = frozenset({SubModelType.Transformer})+def _load_model(self,config: AnyModelConfig,@@ -505,9 +505,8 @@ class ZImageCheckpointModel(ModelLoader):# "model.diffusion_model." (ComfyUI-style format). Check if we need to strip this prefix.sd = CheckpointPrefix.detect(sd).strip(sd)- # Determine safe dtype based on target device capabilities- target_device = TorchDevice.choose_torch_device()- model_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)+ # Use the same dtype snapshot that selected the shared-weight cache key.+ _keep, model_dtype = self._storage_format(config, SubModelType.Transformer)# Per-layer hints from the safetensors header and/or the per-tensor `.comfy_quant` markers:# `full_precision_matrix_mult` for scaled fp8, and for nvfp4 the evidence that a layer follows@@ -1064,28 +1063,8 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):compute dtype. Embeddings are always folded; nvfp4 and int8 convrot layers stay packed."""- def _storage_format(self, config: AnyModelConfig) -> tuple[bool, torch.dtype]:- """Whether float8 Linear weights stay float8, and the compute dtype everything else is held in.-- Decided once per loader (a fresh one serves each load): the cache key and the built weights must agree, and the- capability probes can flip between the key computation and the build under the load lock. Float8 follows the- execution device, because a CPU-only encoder reads its weights on the CPU whatever the session's device is.- """- device = self._get_execution_device(config, SubModelType.TextEncoder) or self._torch_device- decisions = self.__dict__.setdefault("_storage_format_decisions", {})- if device not in decisions:- keep_fp8 = should_keep_fp8_weights(device) or _device_supports_fp8_storage(device, self._logger)- decisions[device] = (keep_fp8, TorchDevice.choose_bfloat16_safe_dtype(self._torch_device))- return decisions[device]-- def _cache_key_variant(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> str:- # Device caches share one canonical CPU copy per key: a device must not adopt float8 it cannot hold, nor folded- # weights that throw away a capable device's saving. Keyed by the device's decision, not the file's contents,- # which would take a header read on every cache lookup.- if submodel_type == SubModelType.TextEncoder:- keep_fp8, dtype = self._storage_format(config)- return f"{'fp8-' if keep_fp8 else ''}{str(dtype).removeprefix('torch.')}"- return ""+ _fp8_checkpoint_submodels = frozenset({SubModelType.TextEncoder})+ _encoder_fp8_storage = Truedef _load_model(self,@@ -1133,7 +1112,7 @@ class Qwen3EncoderCheckpointLoader(ModelLoader):)model_path = Path(config.path)- device_keeps_fp8, model_dtype = self._storage_format(config)+ device_keeps_fp8, model_dtype = self._storage_format(config, SubModelType.TextEncoder)# Load the state dict from safetensors filesd = load_safetensors_checkpoint(model_path)diff --git a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.jsonindex 39a69ff3ca..5b8157a0bb 100644--- a/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json+++ b/invokeai/frontend/webv2/src/workbench/palette/docsSearchIndex.json@@ -79,7 +79,7 @@{"s":"configuration/multi-user-mode/user-guide","t":"Multi-User Guide","d":"Sign in to a shared InvokeAI server, share boards and workflows, and work alongside other users.","c":3,"h":[["signing-in","Signing in"],["your-account","Your account"],["what-you-can-do","What you can do"],["working-with-your-content-in-multi-user-mode","Working with Your Content in Multi-User Mode"],["image-boards","Image Boards"],["workflows","Workflows"],["the-generation-queue","The Generation Queue"],["switching-between-single-user-and-multi-user-mode","Switching Between Single-User and Multi-User Mode"],["troubleshooting","Troubleshooting"]]},{"s":"configuration/optimization/async-weight-streaming","t":"Async Weight Streaming","d":"Copy the layers of a partially loaded model from RAM to the GPU while the previous layers compute, with identical images.","c":3,"h":[["requirements","Requirements"],["turning-it-on","Turning it on"],["memory","Memory"]]},{"s":"configuration/optimization/fp8-compute","t":"FP8 Compute","d":"Run checkpoints published in FP8 on the FP8 tensor cores of RTX 40-series and newer GPUs, and what it means for repeatable images.","c":3,"h":[["requirements","Requirements"],["turning-it-on","Turning it on"],["when-the-model-asks-for-full-precision","When the model asks for full precision"]]},-{"s":"configuration/optimization/fp8-storage","t":"FP8 Storage","d":"Halve a full-precision model's VRAM by keeping its weights in FP8 on the GPU, per model, from the Model Manager.","c":3,"h":[["what-it-applies-to","What it applies to"],["by-file-format","By file format"],["by-model","By model"],["by-gpu","By GPU"],["turning-it-on","Turning it on"],["when-installing","When installing"],["checkpoints-that-are-already-fp8","Checkpoints that are already FP8"],["quality","Quality"],["troubleshooting","Troubleshooting"],["reporting-an-issue","Reporting an issue"]]},+{"s":"configuration/optimization/fp8-storage","t":"FP8 Storage","d":"Halve a full-precision model's VRAM by keeping its weights in FP8 on the GPU, per model, from the Model Manager.","c":3,"h":[["what-it-applies-to","What it applies to"],["by-file-format","By file format"],["by-model","By model"],["by-gpu","By GPU"],["sharing-across-devices-and-cpu-encoders","Sharing across devices and CPU encoders"],["turning-it-on","Turning it on"],["when-installing","When installing"],["checkpoints-that-are-already-fp8","Checkpoints that are already FP8"],["quality","Quality"],["troubleshooting","Troubleshooting"],["reporting-an-issue","Reporting an issue"]]},{"s":"configuration/optimization/int8-compute","t":"int8 Compute","d":"Run ComfyUI int8 builds on the int8 tensor cores of RTX 30-series and newer NVIDIA GPUs, up to twice as fast.","c":3,"h":[["requirements","Requirements"],["turning-it-on","Turning it on"],["what-stays-on-the-default-path","What stays on the default path"]]},{"s":"configuration/optimization/low-vram-mode","t":"Low-VRAM mode","d":"How Invoke runs models larger than your GPU's memory, the invokeai.yaml settings that tune it, and what to do when you still run out of memory.","c":3,"h":[["platform-notes","Platform notes"],["settings","Settings"],["calibrating-a-models-working-memory","Calibrating a model’s working memory"],["the-vram-budget","The VRAM budget"],["tiled-vae-decode-and-encode","Tiled VAE decode and encode"],["troubleshooting","Troubleshooting"],["windows-page-file","Windows page file"]]},{"s":"configuration/optimization/memory-options","t":"Which memory option do I need?","d":"Pick your GPU, VRAM and model format to see which of Invoke's memory options apply, and compare GGUF, int8, nvfp4, SDNQ, NF4 and FP8 in one table.","c":3,"h":[["format-comparison","Format comparison"]]},diff --git a/tests/app/services/working_memory_calibration/test_measured_models.py b/tests/app/services/working_memory_calibration/test_measured_models.pynew file mode 100644index 0000000000..a0c6777650--- /dev/null+++ b/tests/app/services/working_memory_calibration/test_measured_models.py@@ -0,0 +1,37 @@+"""Cache storage suffixes must not hide a measured model from reset or attribution."""++import pytest++from invokeai.app.services.working_memory_calibration.working_memory_calibration_common import CalibrationPoint+from invokeai.app.services.working_memory_calibration.working_memory_calibration_fits import measured_models+++ "cache_key,owner",+ [+ ("model", "model"),+ ("model:vae", "model"),+ ("namespace:model:transformer", "namespace:model"),+ ("namespace:model:unknown", "namespace:model:unknown"),+ ("namespace:float32", "namespace:float32"),+ ("model:text_encoder_2:fp8-float32", "model"),+ ("model:text_encoder_3:bfloat16", "model"),+ ("namespace:model:transformer:storage=fp8-float16", "namespace:model"),+ ("namespace:model:storage=full-float32", "namespace:model"),+ ("model:transformer:storage=fp8-bfloat16-layerwise", "model"),+ ("studio:as_text_llm", "studio:as_text_llm"),+ ("studio:as_text_llm:vae", "studio:as_text_llm"),+ ("namespace:model:text_encoder:fp8-bfloat16", "namespace:model:text_encoder:fp8-bfloat16"),+ ("studio:text_encoder:float32", "studio:text_encoder:float32"),+ ("model:text_encoder:full-float32", "model:text_encoder:full-float32"),+ ("model:text_encoder:fp8-bfloat16-layerwise", "model:text_encoder:fp8-bfloat16-layerwise"),+ ("namespace:model:text_encoder:as_qwen3_5_encoder:storage=full-float32", "namespace:model"),+ ("namespace:model:as_unrecognized_type", "namespace:model:as_unrecognized_type"),+ ("model:transformer:storage=unknown", "model:transformer:storage=unknown"),+ ("model:unknown:fp8-float32", "model:unknown:fp8-float32"),+ ],+)+def test_measurement_attribution_understands_only_known_cache_suffixes(cache_key, owner):+ point = CalibrationPoint.model_construct(model_key=cache_key, run_id="run")+ assert measured_models(point, {}) == frozenset({owner})+ assert measured_models(point, {"run": "calibrated"}) == frozenset({owner, "calibrated"})diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.pyindex fe5ce66d4c..1d6daf8323 100644--- a/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_plan.py@@ -1005,6 +1005,8 @@ def test_a_flux2_diffusers_pipelines_own_vae_loads_in_the_dtype_the_plan_sizes_f_save_tiny_vae(tmp_path / "vae", AutoencoderKLFlux2, torch.float32)(tmp_path / "model_index.json").write_text(json.dumps({"vae": ["diffusers", "AutoencoderKLFlux2"]}))loader = Flux2DiffusersModel.__new__(Flux2DiffusersModel)+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.float32loader._apply_fp8_layerwise_casting = lambda model, config, submodel_type: modelvae = loader._load_model(SimpleNamespace(path=str(tmp_path), repo_variant=None), SubModelType.VAE)diff --git a/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py b/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.pyindex 504d198b08..70117ab8d1 100644--- a/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py+++ b/tests/app/services/working_memory_calibration/test_working_memory_calibration_service.py@@ -1332,6 +1332,27 @@ def test_a_model_reset_covers_its_submodels_windows(tmp_path: Path, mock_invokerassert [point["model_key"] for point in points] == ["vae-key"]+def test_a_model_reset_preserves_distinct_records_with_cache_shaped_keys(+ tmp_path: Path, mock_invoker: Invoker, queue: SessionQueue+) -> None:+ service = _service(tmp_path, mock_invoker)+ run = _create(service, "model-b")+ role_shaped_key = "studio:as_text_llm"+ qwen_shaped_key = "studio:text_encoder:float32"+ service.record_windows(+ run.run_id,+ [+ measured_window(run.run_id, node_id="role_shaped", model_key=role_shaped_key),+ measured_window(run.run_id, node_id="qwen_shaped", model_key=qwen_shaped_key),+ measured_window(run.run_id, node_id="other", model_key="studio:vae"),+ ],+ )++ assert service.reset_model("studio").points_removed == 1+ assert service.reset_model(role_shaped_key).points_removed == 1+ assert service.reset_model(qwen_shaped_key).points_removed == 1++ANIMA_LLLITE_GRAPHS = (Path(__file__).parents[4]/ "invokeai"diff --git a/tests/backend/flux3/test_checkpoint_policy.py b/tests/backend/flux3/test_checkpoint_policy.pynew file mode 100644index 0000000000..2787c45280--- /dev/null+++ b/tests/backend/flux3/test_checkpoint_policy.py@@ -0,0 +1,153 @@+"""Native quantized loading and device policy share one captured decision; tensors stay on CPU."""++from contextlib import ExitStack++import gguf+import pytest+import safetensors.torch+import torch++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux3_Config, Main_GGUF_Flux3_Config+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_loaders import flux3+from invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.util.devices import TorchDevice+from tests.backend.flux3.flux3_fixture import (+ QUANTIZED_SCHEMES,+ quantize_flux3_native,+ quantize_flux3_torchao,+ tiny_flux3_model,+ to_native,+ write_flux3_gguf,+)+from tests.backend.model_manager.load.test_fp8_review_regressions import _device_loaders+from tests.backend.model_manager.load.test_layerwise_storage_policy import _public_load++[email protected]("scheme", ["raw_fp8", "torchao", *QUANTIZED_SCHEMES])[email protected]("consumer", ["compute", "storage"])+def test_native_policy_partitions_partial_devices_and_adopts_matching_cpu_weights(+ scheme, consumer, monkeypatch, tmp_path+):+ native = to_native(tiny_flux3_model(True))+ weight = "single_blocks.0.q_proj.weight"+ if scheme == "raw_fp8":+ native[weight] = native[weight].to(torch.float8_e4m3fn)+ metadata = {}+ elif scheme == "torchao":+ build = quantize_flux3_torchao(tiny_flux3_model(True))+ native, metadata = build.state_dict, build.metadata+ else:+ build = quantize_flux3_native(native, scheme)+ native, metadata = build.state_dict, build.metadata+ path = tmp_path / "native.safetensors"+ safetensors.torch.save_file(native, str(path), metadata=metadata)+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda d: consumer == "compute" and d.index == 0)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda d, _logger: d.index == 0)+ calls = []+ factory = flux3.flux3_transformer_from_single_file++ def build(sd, dtype, reserve, **kwargs):+ calls.append((dtype, kwargs["keep_fp8"], kwargs["metadata"]))+ return factory(sd, dtype, reserve, **kwargs)++ monkeypatch.setattr(flux3, "flux3_transformer_from_single_file", build)+ capable, incapable, peer = _device_loaders(flux3.Flux3CheckpointModel, tmp_path, ["cuda:0", "cuda:1", "cuda:0"])++ def config():+ return Main_Checkpoint_Flux3_Config.model_construct(+ key="native",+ name="native",+ path=str(path),+ default_settings=MainModelDefaultSettings(fp8_storage=consumer == "storage"),+ )++ with ExitStack() as stack:+ for loader in (capable, incapable, peer):+ stack.callback(loader._ram_cache.shutdown)+ folded = _public_load(incapable, config(), SubModelType.Transformer)+ kept = _public_load(capable, config(), SubModelType.Transformer)+ adopted = _public_load(peer, config(), SubModelType.Transformer)+ assert calls == [(torch.float32, False, metadata), (torch.float32, True, metadata)]+ name = "single_transformer_blocks.0.attn.to_q.weight"+ a, b, c = (model.get_submodule(name.removesuffix(".weight")).weight for model in (folded, kept, adopted))+ assert a.data_ptr() != b.data_ptr() == c.data_ptr()+ if scheme in ("fp8r", "raw_fp8", "torchao"):+ assert a.dtype == torch.float32+ assert b.dtype == torch.float8_e4m3fn+ # This compares the decoded values, with the real checkpoint scale when present.+ expected = b.float()+ if scheme in ("fp8r", "torchao"):+ expected = expected * kept.get_submodule(name.removesuffix(".weight")).weight_scale[:, None]+ torch.testing.assert_close(a, expected)+ else:+ # int8/nvfp4 remain packed even on the device which cannot retain checkpoint fp8.+ assert a.dtype == b.dtype == (torch.int8 if scheme == "int8_convrot" else torch.uint8)+ assert folded.x_embedders["image"].weight.dtype == kept.x_embedders["image"].weight.dtype == torch.float32+++def test_native_factory_uses_the_key_snapshot_after_bfloat_rejection(monkeypatch, tmp_path):+ path = tmp_path / "native.safetensors"+ native = to_native(tiny_flux3_model(True))+ native["single_blocks.0.q_proj.weight"] = native["single_blocks.0.q_proj.weight"].to(torch.float8_e4m3fn)+ safetensors.torch.save_file(native, str(path))+ empty = torch.empty+ probes = []++ def reject_bfloat(*shape, **kwargs):+ if shape == (0,) and kwargs.get("dtype") == torch.bfloat16:+ probes.append(str(kwargs.get("device")))+ raise TypeError("fixture device rejects bfloat16")+ return empty(*shape, **kwargs)++ monkeypatch.setattr(torch, "empty", reject_bfloat)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda d: d == torch.device("cuda:1"))+ (loader,) = _device_loaders(flux3.Flux3CheckpointModel, tmp_path, ["cuda:1"])+ config = Main_Checkpoint_Flux3_Config.model_construct(key="snapshot", name="native", path=str(path))+ try:+ key = loader._get_cache_key(config, SubModelType.Transformer)+ assert "fp8-float16" in key+ # A different session default must not change construction or redo the dtype/capability probes.+ monkeypatch.setattr(TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _d: False)+ model = loader._load_model(config, SubModelType.Transformer)+ assert probes == ["cuda:1"]+ assert model.x_embedders["image"].weight.dtype == torch.float16+ assert model.single_transformer_blocks[0].attn.to_q.weight.dtype == torch.float8_e4m3fn+ assert loader._get_cache_key(config, SubModelType.Transformer) == key+ finally:+ loader._ram_cache.shutdown()+++def test_gguf_compute_dtype_partitions_shared_weights_after_bfloat_rejection(monkeypatch, tmp_path):+ path = tmp_path / "native.gguf"+ write_flux3_gguf(path, to_native(tiny_flux3_model(True)), qtype=gguf.GGMLQuantizationType.Q8_0)+ empty = torch.empty+ probes = []++ def reject_bfloat(*shape, **kwargs):+ if shape == (0,) and kwargs.get("dtype") == torch.bfloat16:+ probes.append(str(kwargs.get("device")))+ raise TypeError("fixture device rejects bfloat16")+ return empty(*shape, **kwargs)++ monkeypatch.setattr(torch, "empty", reject_bfloat)+ half, full, peer = _device_loaders(flux3.Flux3GGUFCheckpointModel, tmp_path, ["cuda:0", "xpu:0", "cuda:1"])++ def config():+ return Main_GGUF_Flux3_Config.model_construct(key="gguf", name="native", path=str(path))++ with ExitStack() as stack:+ for loader in (half, full, peer):+ stack.callback(loader._ram_cache.shutdown)+ a = _public_load(half, config(), SubModelType.Transformer)+ b = _public_load(full, config(), SubModelType.Transformer)+ c = _public_load(peer, config(), SubModelType.Transformer)+ name = "single_transformer_blocks.0.attn.to_q.weight"+ wa, wb, wc = (model.get_parameter(name) for model in (a, b, c))+ assert wa.compute_dtype == wc.compute_dtype == torch.float16+ assert wb.compute_dtype == torch.float32+ assert wa.quantized_data.data_ptr() == wc.quantized_data.data_ptr() != wb.quantized_data.data_ptr()+ assert probes == ["cuda:0", "xpu:0", "cuda:1"]diff --git a/tests/backend/model_manager/load/test_device_dtype_sharing.py b/tests/backend/model_manager/load/test_device_dtype_sharing.pynew file mode 100644index 0000000000..7021b2e1e3--- /dev/null+++ b/tests/backend/model_manager/load/test_device_dtype_sharing.py@@ -0,0 +1,186 @@+"""Device policies are simulated; model weights and shared storage remain on CPU."""++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.configs.main import (+ Main_Checkpoint_Wan_Config,+ Main_Diffusers_Flux3_Config,+ Main_Diffusers_MossImage_Config,+ Main_Diffusers_QwenImage21_Config,+ Main_Diffusers_ZImage_Config,+)+from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore+from invokeai.backend.model_manager.load.model_loaders.ernie_image import ErnieImageDiffusersModel+from invokeai.backend.model_manager.load.model_loaders.flux3 import Flux3DiffusersModel+from invokeai.backend.model_manager.load.model_loaders.krea2 import Krea2DiffusersModel+from invokeai.backend.model_manager.load.model_loaders.ltx2 import LTX2FolderModel+from invokeai.backend.model_manager.load.model_loaders.moss_image import MossImageDiffusersModel+from invokeai.backend.model_manager.load.model_loaders.qwen_image_2_1 import QwenImage21DiffusersModel+from invokeai.backend.model_manager.load.model_loaders.wan import WanCheckpointModel, WanDiffusersModel+from invokeai.backend.model_manager.load.model_loaders.z_image import ZImageDiffusersModel+from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantType+from invokeai.backend.util.devices import TorchDevice+from tests.backend.model_manager.load.test_fp8_shared_weight_variants import _load, _loader+from tests.backend.model_manager.load.test_wan_checkpoint_loader import _tiny_model++[email protected]("reverse", [False, True])+def test_wan_checkpoint_distinct_dtypes_do_not_adopt_each_other(monkeypatch, tmp_path, reverse):+ monkeypatch.setattr(+ TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda d: torch.float16 if d.index == 0 else torch.float32),+ )+ path = tmp_path / "wan.safetensors"+ save_file(_tiny_model().state_dict(), str(path))+ config = Main_Checkpoint_Wan_Config.model_construct(+ key="wan", name="wan", path=str(path), variant=WanVariantType.T2V_A14B+ )+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ half = _loader(WanCheckpointModel, store, budget, "cuda:0", tmp_path)+ full = _loader(WanCheckpointModel, store, budget, "cuda:1", tmp_path)+ peer = _loader(WanCheckpointModel, store, budget, "cuda:0", tmp_path)+ try:+ order = [full, half] if reverse else [half, full]+ models = {loader: _load(loader, config, SubModelType.Transformer) for loader in order}+ a = models[half].proj_out.weight+ b = models[full].proj_out.weight+ assert a.dtype == torch.float16 and b.dtype == torch.float32+ assert a.data_ptr() != b.data_ptr()+ assert half._get_cache_key(config, SubModelType.Transformer) != full._get_cache_key(+ config, SubModelType.Transformer+ )+ adopted = _load(peer, config, SubModelType.Transformer).proj_out.weight+ assert adopted.data_ptr() == a.data_ptr()+ torch.testing.assert_close(a.float(), b, rtol=1e-3, atol=1e-4)+ finally:+ for loader in (half, full, peer):+ loader._ram_cache.shutdown()+++def test_z_image_pipeline_sdnq_encoder_keys_match_its_session_dtype_when_forced_to_cpu(monkeypatch, tmp_path):+ from transformers import Qwen3Config, Qwen3ForCausalLM++ from invokeai.backend.quantization.sdnq import loaders as sdnq_loaders++ monkeypatch.setattr(+ TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda device: torch.bfloat16 if device.index == 0 else torch.float32),+ )+ text_encoder_path = tmp_path / "text_encoder"+ text_encoder_path.mkdir()+ (text_encoder_path / "quantization_config.json").write_text('{"quant_method":"sdnq"}', encoding="utf-8")+ tiny_config = Qwen3Config(+ vocab_size=32,+ hidden_size=16,+ intermediate_size=24,+ num_hidden_layers=1,+ num_attention_heads=1,+ num_key_value_heads=1,+ head_dim=128,+ tie_word_embeddings=True,+ )+ source = Qwen3ForCausalLM(tiny_config).state_dict()+ reads = []++ def read(path, *, compute_dtype):+ assert path == text_encoder_path+ reads.append(compute_dtype)+ return {key: tensor.to(dtype=compute_dtype, copy=True) for key, tensor in source.items()}++ monkeypatch.setattr(sdnq_loaders, "sdnq_sd_loader", read)+ config = Main_Diffusers_ZImage_Config.model_construct(+ key="z-image", name="Z-Image", path=str(tmp_path), default_settings=MainModelDefaultSettings(cpu_only=True)+ )+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ reduced = _loader(ZImageDiffusersModel, store, budget, "cuda:0", tmp_path)+ full = _loader(ZImageDiffusersModel, store, budget, "cuda:1", tmp_path)+ try:+ submodel = SubModelType.TextEncoder+ reduced_weights = _load(reduced, config, submodel).model.embed_tokens.weight+ full_weights = _load(full, config, submodel).model.embed_tokens.weight++ assert reduced_weights.dtype is torch.bfloat16+ assert full_weights.dtype is torch.float32+ assert reads == [torch.bfloat16, torch.float32]+ assert reduced._get_cache_key(config, submodel).endswith(":storage=full-bfloat16")+ assert full._get_cache_key(config, submodel).endswith(":storage=full-float32")+ finally:+ reduced._ram_cache.shutdown()+ full._ram_cache.shutdown()+++def test_component_variants_follow_actual_dtype_and_keep_dtype_independent_components_shared(monkeypatch, tmp_path):+ monkeypatch.setattr(+ TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda d: torch.float16 if d.index == 0 else torch.float32),+ )+ config = Main_Checkpoint_Wan_Config.model_construct(key="model", name="m", path="m")+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ loaders = []+ try:++ def keys(cls, subtype):+ a = _loader(cls, store, budget, "cuda:0", tmp_path)+ b = _loader(cls, store, budget, "cuda:1", tmp_path)+ loaders.extend((a, b))+ return a._get_cache_key(config, subtype), b._get_cache_key(config, subtype)++ assert len(set(keys(ErnieImageDiffusersModel, SubModelType.TextEncoder))) == 2+ assert len(set(keys(ErnieImageDiffusersModel, SubModelType.Tokenizer))) == 1+ assert len(set(keys(ErnieImageDiffusersModel, SubModelType.PromptEnhancerTokenizer))) == 1+ assert len(set(keys(Krea2DiffusersModel, SubModelType.Processor))) == 1+ assert len(set(keys(WanDiffusersModel, SubModelType.VAE))) == 1+ assert len(set(keys(LTX2FolderModel, SubModelType.VAE))) == 2+ assert len(set(keys(LTX2FolderModel, SubModelType.AudioVAE))) == 1+ assert len(set(keys(LTX2FolderModel, SubModelType.Vocoder))) == 1+ for cls in (Flux3DiffusersModel, MossImageDiffusersModel, QwenImage21DiffusersModel):+ # The configured float32 is fixed even when the device's preferred dtype differs.+ assert len(set(keys(cls, SubModelType.VAE))) == 1+ finally:+ for loader in loaders:+ loader._ram_cache.shutdown()+++ ("cls", "config_cls"),+ [+ (Flux3DiffusersModel, Main_Diffusers_Flux3_Config),+ (MossImageDiffusersModel, Main_Diffusers_MossImage_Config),+ (QwenImage21DiffusersModel, Main_Diffusers_QwenImage21_Config),+ ],+)+def test_vae_build_uses_the_dtype_selected_for_its_cache_key(monkeypatch, tmp_path, cls, config_cls):+ import diffusers++ state = {"dtype": torch.float32}+ built = []+ monkeypatch.setattr(TorchDevice, "dtype_avoiding_float16", lambda *_args: state["dtype"])+ monkeypatch.setattr(+ diffusers.AutoencoderKLFlux2,+ "from_pretrained",+ lambda *_args, **kwargs: built.append(kwargs["torch_dtype"]) or torch.nn.Linear(1, 1),+ )+ store = SharedCpuWeightsStore()+ loader = _loader(cls, store, RamBudget(10**9, store), "cuda:0", tmp_path)+ config = config_cls.model_construct(key="vae", name="vae", path=str(tmp_path))+ try:+ if isinstance(loader, QwenImage21DiffusersModel):+ monkeypatch.setattr(loader, "get_hf_load_class", lambda *_args: diffusers.AutoencoderKLFlux2)+ monkeypatch.setattr(loader, "_apply_fp8_layerwise_casting", lambda model, *_args: model)+ key = loader._get_cache_key(config, SubModelType.VAE)+ state["dtype"] = torch.bfloat16+ loader._load_model(config, SubModelType.VAE)+ assert key.endswith("full-float32")+ assert built == [torch.float32]+ finally:+ loader._ram_cache.shutdown()diff --git a/tests/backend/model_manager/load/test_ernie_image_checkpoint_loader.py b/tests/backend/model_manager/load/test_ernie_image_checkpoint_loader.pyindex aebdd219b4..fcc6f5f3c1 100644--- a/tests/backend/model_manager/load/test_ernie_image_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_ernie_image_checkpoint_loader.py@@ -9,7 +9,6 @@ wrong network. Both the values and the kwarg contract are pinned here.from pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import MagicMockimport accelerateimport pytest@@ -23,6 +22,7 @@ from invokeai.backend.model_manager.load.model_loaders.ernie_image import (ErnieImageCheckpointModel,)from invokeai.backend.model_manager.taxonomy import SubModelType+from tests.fixtures.loader_seams import Seam, SeamRun, prepare# `baidu/ERNIE-Image`'s released `transformer/config.json`, verbatim. Kept as a literal so this# fails when the loader's constant drifts, rather than agreeing with whatever the loader says.@@ -58,6 +58,8 @@ TINY_TRANSFORMER_CONFIG = {"text_in_dim": 16,}+SEAM = Seam(loader=ErnieImageCheckpointModel, module=loader_module, entry="_load_model", patches_device=True)+def test_the_carried_geometry_is_the_released_one() -> None:"""The file has no config of its own, so this constant *is* the architecture."""@@ -80,23 +82,16 @@ def test_the_released_geometry_still_builds_a_model() -> None:assert model.config.text_in_dim == RELEASED_TRANSFORMER_CONFIG["text_in_dim"]-def _loader(monkeypatch: pytest.MonkeyPatch) -> tuple[ErnieImageCheckpointModel, MagicMock]:- ram_cache = MagicMock()- loader = object.__new__(ErnieImageCheckpointModel)- loader._ram_cache = ram_cache- loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model- monkeypatch.setattr(loader_module.TorchDevice, "choose_torch_device", staticmethod(lambda: torch.device("cpu")))- monkeypatch.setattr(- loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: torch.float32)- )- return loader, ram_cache+def _loader(monkeypatch: pytest.MonkeyPatch) -> tuple[ErnieImageCheckpointModel, SeamRun]:+ run = prepare(SEAM, monkeypatch)+ return run.loader, rundef _tiny_checkpoint(path: Path) -> torch.nn.Module:from diffusers import ErnieImageTransformer2DModeltorch.manual_seed(0)- reference = ErnieImageTransformer2DModel(**TINY_TRANSFORMER_CONFIG)+ reference = ErnieImageTransformer2DModel(**TINY_TRANSFORMER_CONFIG).to(dtype=torch.float16)save_file({key: value.contiguous() for key, value in reference.state_dict().items()}, str(path))return reference@@ -106,7 +101,7 @@ def test_a_single_file_loads_into_the_model_it_describes(monkeypatch: pytest.Monmonkeypatch.setattr(loader_module, "ERNIE_IMAGE_TRANSFORMER_CONFIG", TINY_TRANSFORMER_CONFIG)checkpoint = tmp_path / "ernie-image.safetensors"reference = _tiny_checkpoint(checkpoint)- loader, ram_cache = _loader(monkeypatch)+ loader, run = _loader(monkeypatch)config = Main_Checkpoint_ErnieImage_Config.model_construct(path=str(checkpoint), name="ernie-image")model = loader._load_model(config, SubModelType.Transformer)@@ -114,10 +109,11 @@ def test_a_single_file_loads_into_the_model_it_describes(monkeypatch: pytest.Monassert [name for name, param in model.named_parameters() if param.is_meta] == []expected = reference.state_dict()for name, param in model.named_parameters():- assert torch.equal(param, expected[name]), name+ assert expected[name].dtype == torch.float16, name+ assert param.dtype == torch.float32, name+ assert torch.equal(param, expected[name].to(torch.float32)), name# The reservation is what keeps a 16GB file from evicting itself mid-load.- ram_cache.make_room.assert_called_once()- assert ram_cache.make_room.call_args.args[0] > 0+ assert run.reserved == [sum(tensor.numel() * torch.float32.itemsize for tensor in expected.values())]def test_the_checkpoint_refuses_submodels_it_does_not_contain(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:diff --git a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.pyindex cb42cd4a15..512bf74eaf 100644--- a/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_flux2_int8_convrot_loader.py@@ -15,7 +15,9 @@ import jsonimport pytestimport torch+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_Flux2_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_loaders import fluxfrom invokeai.backend.model_manager.load.model_loaders.flux import Flux2CheckpointModelfrom invokeai.backend.model_manager.taxonomy import Flux2VariantType, SubModelType@@ -136,22 +138,30 @@ SEAM = Seam()-def _driver(monkeypatch, tmp_path, state_dict: dict, header: dict | None = None, observe: tuple[str, ...] = ()):+def _driver(+ monkeypatch,+ tmp_path,+ state_dict: dict,+ header: dict | None = None,+ observe: tuple[str, ...] = (),+ *,+ fp8_storage: bool = False,+):checkpoint = tmp_path / "flux-2-klein-9b-int8-convrot.safetensors"checkpoint.touch()config = Main_Checkpoint_Flux2_Config.model_construct(- path=str(checkpoint), name="klein-9b-int8", variant=Flux2VariantType.Klein9B+ path=str(checkpoint),+ name="klein-9b-int8",+ variant=Flux2VariantType.Klein9B,+ default_settings=MainModelDefaultSettings(fp8_storage=fp8_storage),)- def geometry(patch):- # Both spellings of the same decision: the module-level helper, and the loader method that- # supersedes it once FP8 Storage counts as a consumer too. `raising=False` tolerates the- # module symbol being gone.- patch.setattr(flux, "should_keep_fp8_weights", lambda _device: False, raising=False)-- run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, geometry=geometry, observe=observe)- # An instance attribute shadows the method, which is what keeps this working either way.- run.loader._keep_fp8_weights = lambda _config, _submodel=None: False+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger: fp8_storage)+ run = prepare(SEAM, monkeypatch, state_dict=state_dict, metadata=header, observe=observe)+ if fp8_storage:+ # Simulate capability only; the native constructor and all tensor operations still run on CPU.+ run.loader._torch_device = torch.device("cuda:0")return run, config@@ -490,11 +500,12 @@ def test_a_header_hint_reaches_every_projection_the_fused_qkv_became(monkeypatch# whichever test this worker runs next.monkeypatch.setattr(fp8_scaled, "_full_precision_hints_override", True)- run, config = _driver(monkeypatch, tmp_path, state_dict, header)- # The scales only stay attached where something keeps the weights quantized.- run.loader._keep_fp8_weights = lambda _config, _submodel=None: True+ run, config = _driver(monkeypatch, tmp_path, state_dict, header, fp8_storage=True)+ assert state_dict[STORED_FP32].dtype is torch.float32model = run.load(config)+ assert model.x_embedder.weight.dtype is torch.bfloat16+ assert run.loader._get_cache_key(config, SubModelType.Transformer).endswith("storage=fp8-bfloat16-layerwise")for projection in ("to_q", "to_k", "to_v"):marked = model.get_submodule(f"transformer_blocks.0.attn.{projection}")assert marked._fp8_full_precision_matmul is True, projectiondiff --git a/tests/backend/model_manager/load/test_fp8_review_regressions.py b/tests/backend/model_manager/load/test_fp8_review_regressions.pynew file mode 100644index 0000000000..a33ecdbd38--- /dev/null+++ b/tests/backend/model_manager/load/test_fp8_review_regressions.py@@ -0,0 +1,224 @@+"""Review regressions through native loaders and real shared CPU allocations; no accelerator execution."""++from contextlib import ExitStack++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore+from invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR+from tests.backend.model_manager.load.test_fp8_shared_weight_variants import FP8, _checkpoint_case, _loader+from tests.backend.model_manager.load.test_layerwise_storage_policy import _public_load+++def _device_loaders(cls, tmp_path, devices):+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ return [_loader(cls, store, budget, device, tmp_path) for device in devices]++[email protected]("family", ["mistral", "qwen", "krea", "ideogram"])[email protected]("reverse", [False, True])+def test_checkpoint_storage_without_fp8_compute_partitions_and_adopts(family, reverse, monkeypatch, tmp_path):+ cls, config, subtype, reads = _checkpoint_case(family, monkeypatch, tmp_path)+ from invokeai.backend.model_manager.load.model_loaders import mistral_encoder, qwen_image++ # M1 imported probe aliases in these modules. The same fixtures cover both native implementations.+ for module in (load_default, mistral_encoder, qwen_image):+ if hasattr(module, "should_keep_fp8_weights"):+ monkeypatch.setattr(module, "should_keep_fp8_weights", lambda _device: False)+ for module in (load_default, mistral_encoder):+ if hasattr(module, "_device_supports_fp8_storage"):+ monkeypatch.setattr(module, "_device_supports_fp8_storage", lambda device, _logger: device.index == 0)+ capable, incapable, peer, folded_peer = _device_loaders(cls, tmp_path, ["cuda:0", "cuda:1", "cuda:0", "cuda:1"])+ settings = MainModelDefaultSettings(fp8_storage=True)+ with ExitStack() as stack:+ for loader in (capable, incapable, peer, folded_peer):+ stack.callback(loader._ram_cache.shutdown)+ order = [incapable, capable] if reverse else [capable, incapable]+ models = {loader: _public_load(loader, config(default_settings=settings), subtype) for loader in order}+ assert models[capable].proj.weight.dtype == FP8+ assert models[incapable].proj.weight.dtype == torch.float32+ torch.testing.assert_close(models[incapable].proj.weight, torch.full((4, 4), 0.5))+ assert models[capable].proj.weight.data_ptr() != models[incapable].proj.weight.data_ptr()+ assert len(reads) == 2+ adopted = _public_load(peer, config(default_settings=settings), subtype)+ assert adopted.proj.weight.data_ptr() == models[capable].proj.weight.data_ptr()+ folded = _public_load(folded_peer, config(default_settings=settings), subtype)+ assert folded.proj.weight.data_ptr() == models[incapable].proj.weight.data_ptr()+ assert len(reads) == 2+++def _qwen_vl_checkpoint(monkeypatch, tmp_path):+ from transformers import Qwen3VLModel++ from invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_Checkpoint_Config+ from invokeai.backend.model_manager.load.model_loaders import krea2+ from invokeai.backend.model_manager.taxonomy import Qwen3VLVariantType+ from tests.backend.model_manager.load.qwen3vl_gguf_fixture import tiny_qwen3vl_config++ geometry = tiny_qwen3vl_config()+ reference = Qwen3VLModel(geometry)+ weights = {name: value.detach().clone().contiguous() for name, value in reference.state_dict().items()}+ weight = "language_model.layers.0.self_attn.q_proj.weight"+ weights[weight] = torch.ones_like(weights[weight]).to(FP8)+ weights[weight.removesuffix(".weight") + ".weight_scale"] = torch.tensor(0.5)+ path = tmp_path / "qwen-vl.safetensors"+ save_file(weights, str(path))+ monkeypatch.setattr(krea2.Qwen3VLEncoderCheckpointLoader, "_load_te_config", lambda *_args: geometry)+ reads = []+ original = krea2.load_safetensors_checkpoint++ def read(*args, **kwargs):+ reads.append(True)+ return original(*args, **kwargs)++ monkeypatch.setattr(krea2, "load_safetensors_checkpoint", read)++ def config(**extra):+ return Qwen3VLEncoder_Checkpoint_Config.model_construct(+ key="qwen-vl", name="qwen-vl", path=str(path), variant=Qwen3VLVariantType.Qwen3VL_4B, **extra+ )++ return krea2.Qwen3VLEncoderCheckpointLoader, config, weight, reads++[email protected]("consumer", ["compute", "storage"])[email protected]("reverse", [False, True])+def test_issue_qwen_vl_native_body_preserves_scales_and_adopts(consumer, reverse, monkeypatch, tmp_path):+ from invokeai.backend.model_manager.load.model_loaders import krea2++ cls, config, weight, reads = _qwen_vl_checkpoint(monkeypatch, tmp_path)+ for module in (load_default, krea2):+ if hasattr(module, "should_keep_fp8_weights"):+ monkeypatch.setattr(module, "should_keep_fp8_weights", lambda d: consumer == "compute" and d.index == 0)+ if hasattr(module, "_device_supports_fp8_storage"):+ monkeypatch.setattr(+ module, "_device_supports_fp8_storage", lambda d, _logger: consumer == "storage" and d.index == 0+ )+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: torch.float32))+ capable, incapable, peer, folded_peer = _device_loaders(cls, tmp_path, ["cuda:0", "cuda:1", "cuda:0", "cuda:1"])+ with ExitStack() as stack:+ for loader in (capable, incapable, peer, folded_peer):+ stack.callback(loader._ram_cache.shutdown)+ order = [incapable, capable] if reverse else [capable, incapable]+ models = {loader: _public_load(loader, config(), SubModelType.TextEncoder) for loader in order}+ packed, folded = (models[loader].get_parameter(weight) for loader in (capable, incapable))+ assert packed.dtype == FP8 and folded.dtype == torch.float32+ torch.testing.assert_close(folded, torch.full_like(folded, 0.5))+ torch.testing.assert_close(+ models[capable].language_model.layers[0].self_attn.q_proj.weight_scale, torch.tensor(0.5)+ )+ assert packed.data_ptr() != folded.data_ptr()+ assert len(reads) == 2+ adopted = _public_load(peer, config(), SubModelType.TextEncoder)+ assert adopted.get_parameter(weight).data_ptr() == packed.data_ptr()+ adopted_folded = _public_load(folded_peer, config(), SubModelType.TextEncoder)+ assert adopted_folded.get_parameter(weight).data_ptr() == folded.data_ptr()+ assert len(reads) == 2+++def test_cpu_only_qwen_vl_folds_and_shares_with_cpu(monkeypatch, tmp_path):+ from invokeai.backend.model_manager.load.model_loaders import krea2++ cls, config, weight, reads = _qwen_vl_checkpoint(monkeypatch, tmp_path)+ for module in (load_default, krea2):+ if hasattr(module, "should_keep_fp8_weights"):+ monkeypatch.setattr(module, "should_keep_fp8_weights", lambda d: d.type == "cuda")+ if hasattr(module, "_device_supports_fp8_storage"):+ monkeypatch.setattr(module, "_device_supports_fp8_storage", lambda d, _logger: d.type == "cuda")+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: torch.float32))+ cpu, cpu_only, gpu = _device_loaders(cls, tmp_path, ["cpu", "cuda:0", "cuda:0"])+ with ExitStack() as stack:+ for loader in (cpu, cpu_only, gpu):+ stack.callback(loader._ram_cache.shutdown)+ a = _public_load(cpu, config(), SubModelType.TextEncoder).get_parameter(weight)+ b = _public_load(cpu_only, config(cpu_only=True), SubModelType.TextEncoder).get_parameter(weight)+ c = _public_load(gpu, config(), SubModelType.TextEncoder).get_parameter(weight)+ assert a.dtype == b.dtype == torch.float32+ assert c.dtype == FP8+ assert a.data_ptr() == b.data_ptr() != c.data_ptr()+ torch.testing.assert_close(a, torch.full_like(a, 0.5))+ assert len(reads) == 2+++def _native_dtype_case(family, monkeypatch, tmp_path):+ from invokeai.backend.model_manager.configs import main+ from invokeai.backend.model_manager.load.model_loaders import flux3, ltx2, wan++ path = tmp_path / family+ if family.startswith("flux3"):+ from tests.backend.flux3.flux3_fixture import tiny_flux3_model, to_native++ reference = tiny_flux3_model(False)+ if family == "flux3-folder":+ reference.save_pretrained(path / "transformer")+ cls, config_cls = flux3.Flux3DiffusersModel, main.Main_Diffusers_Flux3_Config+ else:+ save_file(to_native(reference), str(path))+ cls, config_cls = flux3.Flux3CheckpointModel, main.Main_Checkpoint_Flux3_Config+ elif family == "wan":+ from tests.backend.model_manager.load.test_wan_checkpoint_loader import _tiny_model++ save_file(_tiny_model().state_dict(), str(path))+ cls, config_cls = wan.WanCheckpointModel, main.Main_Checkpoint_Wan_Config+ else:+ from invokeai.backend.ltx2 import component_configs as cc+ from tests.backend.model_manager.load.ltx2_transformer_fixture import (+ TINY_TRANSFORMER,+ tiny_transformer_checkpoint,+ )++ monkeypatch.setattr(cc, "LTX2_5_TRANSFORMER_CONFIG", TINY_TRANSFORMER)+ save_file(tiny_transformer_checkpoint(), str(path))+ cls, config_cls = ltx2.LTX2CheckpointModel, main.Main_Checkpoint_LTX2_Config++ def config():+ return config_cls.model_construct(+ key="dtype", name="dtype", path=str(path), default_settings=MainModelDefaultSettings(fp8_storage=True)+ )++ return cls, config++[email protected]("family", ["flux3", "flux3-folder", "wan", "ltx2"])[email protected]("reverse", [False, True])+def test_native_constructor_key_matches_real_bfloat_rejection_fallback(family, reverse, monkeypatch, tmp_path):+ cls, config = _native_dtype_case(family, monkeypatch, tmp_path)+ empty = torch.empty+ probes = []++ def reject_bfloat(*shape, **kwargs):+ device = kwargs.get("device")+ if shape == (0,) and kwargs.get("dtype") == torch.bfloat16 and device is not None:+ device = torch.device(device)+ if device.type in ("cuda", "xpu"):+ probes.append(str(device))+ raise TypeError("fixture backend rejects bfloat16")+ return empty(*shape, **kwargs)++ # Exercise the real choose_bfloat16_safe_dtype, including its device-specific TypeError fallback.+ monkeypatch.setattr(torch, "empty", reject_bfloat)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)+ half, full, peer = _device_loaders(cls, tmp_path, ["cuda:0", "xpu:0", "cuda:1"])+ for loader in (half, full, peer):+ loader._torch_dtype = torch.float16+ with ExitStack() as stack:+ for loader in (half, full, peer):+ stack.callback(loader._ram_cache.shutdown)+ order = [full, half] if reverse else [half, full]+ models = {loader: _public_load(loader, config(), SubModelType.Transformer) for loader in order}+ for loader, dtype in ((half, torch.float16), (full, torch.float32)):+ assert getattr(models[loader], FP8_COMPUTE_DTYPE_ATTR) == dtype+ assert str(dtype).removeprefix("torch.") in loader._get_cache_key(config(), SubModelType.Transformer)+ a, b = (next(model.parameters()) for model in (models[half], models[full]))+ assert a.data_ptr() != b.data_ptr()+ adopted = _public_load(peer, config(), SubModelType.Transformer)+ assert next(adopted.parameters()).data_ptr() == a.data_ptr()+ assert {"cuda:0", "xpu:0"} <= set(probes)diff --git a/tests/backend/model_manager/load/test_fp8_shared_weight_variants.py b/tests/backend/model_manager/load/test_fp8_shared_weight_variants.pynew file mode 100644index 0000000000..e293d878c8--- /dev/null+++ b/tests/backend/model_manager/load/test_fp8_shared_weight_variants.py@@ -0,0 +1,369 @@+"""Real cross-cache storage adoption; device labels select policy, all tensors stay on CPU."""++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.configs.main import Main_Diffusers_FLUX_Config+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.load_default import ModelLoader+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache+from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore+from invokeai.backend.model_manager.taxonomy import Krea2VariantType, MistralVariantType, SubModelType+from invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.logging import InvokeAILogger++FP8 = torch.float8_e4m3fn+++class _TinyModel(torch.nn.Module):+ def __init__(self, *_args, **_kwargs):+ super().__init__()+ self.proj = torch.nn.Linear(4, 4, bias=False)+++class _LayerwiseLoader(ModelLoader):+ builds = 0++ def get_size_fs(self, *_args):+ return 64++ def _load_model(self, config, submodel_type=None):+ self.builds += 1+ model = _TinyModel()+ model.load_state_dict({"proj.weight": torch.ones(4, 4)}, assign=True)+ return self._apply_fp8_layerwise_casting(model, config, submodel_type)+++def _loader(cls, store, budget, device, tmp_path):+ cache = ModelCache(+ execution_device_working_mem_gb=1.0,+ enable_partial_loading=False,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=InvokeAILogger.get_logger("test"),+ shared_cpu_weights=store,+ ram_budget=budget,+ )+ loader = object.__new__(cls)+ loader._ram_cache = cache+ loader._torch_device = torch.device(device)+ loader._torch_dtype = torch.float32+ loader._logger = InvokeAILogger.get_logger("test")+ loader._app_config = MagicMock(log_memory_usage=False, models_path=tmp_path)+ return loader+++def _load(loader, config, subtype):+ # The legacy loaders choose the session device during construction. Match that session to the+ # simulated loader, so a red result measures cross-cache adoption, not an incorrect first build.+ with patch.object(TorchDevice, "choose_torch_device", return_value=loader._torch_device):+ record, claim = loader._load_and_cache(config, subtype)+ if claim is not None:+ claim.release()+ return record.cached_model.model+++def _config():+ return Main_Diffusers_FLUX_Config.model_construct(+ key="model", name="tiny", path="tiny", default_settings=MainModelDefaultSettings(fp8_storage=True)+ )++[email protected]("capable_first", [True, False])+def test_layerwise_device_caches_never_adopt_an_incompatible_storage_format(monkeypatch, tmp_path, capable_first):+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda device, _logger: device.index == 0)+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**9, shared_store=store)+ capable = _loader(_LayerwiseLoader, store, budget, "cuda:0", tmp_path)+ incapable = _loader(_LayerwiseLoader, store, budget, "cuda:1", tmp_path)+ try:+ loaders = [capable, incapable] if capable_first else [incapable, capable]+ models = {loader: _load(loader, _config(), SubModelType.Transformer) for loader in loaders}+ assert models[capable].proj.weight.dtype == FP8+ assert models[incapable].proj.weight.dtype == torch.float32+ assert models[capable].proj.weight.data_ptr() != models[incapable].proj.weight.data_ptr()+ assert capable.builds == incapable.builds == 1+ assert budget.total_in_use() == 16 + 64+ finally:+ capable._ram_cache.shutdown()+ incapable._ram_cache.shutdown()+++def test_compatible_layerwise_devices_adopt_one_canonical_cpu_allocation(monkeypatch, tmp_path):+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger: True)+ store = SharedCpuWeightsStore()+ budget = RamBudget(max_bytes=10**9, shared_store=store)+ first = _loader(_LayerwiseLoader, store, budget, "cuda:0", tmp_path)+ second = _loader(_LayerwiseLoader, store, budget, "cuda:1", tmp_path)+ try:+ a = _load(first, _config(), SubModelType.Transformer)+ b = _load(second, _config(), SubModelType.Transformer)+ assert a is not b+ assert a.proj.weight.dtype == b.proj.weight.dtype == FP8+ assert a.proj.weight.data_ptr() == b.proj.weight.data_ptr()+ assert first.builds == 1 and second.builds == 0+ assert budget.total_in_use() == 16+ finally:+ first._ram_cache.shutdown()+ second._ram_cache.shutdown()+++def test_layerwise_key_and_build_use_one_capability_answer(monkeypatch, tmp_path):+ answers = iter([False, True])+ calls = []++ def supports(device, _logger):+ calls.append(device)+ return next(answers)++ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", supports)+ store = SharedCpuWeightsStore()+ loader = _loader(_LayerwiseLoader, store, RamBudget(10**9, store), "cuda:0", tmp_path)+ config = _config()+ try:+ loader._cache_key_variant(config, SubModelType.Transformer)+ model = _load(loader, config, SubModelType.Transformer)+ assert model.proj.weight.dtype == torch.float32+ assert len(calls) == 1+ finally:+ loader._ram_cache.shutdown()++[email protected](params=["mistral", "qwen", "krea", "ideogram"])+def checkpoint_case(request, monkeypatch, tmp_path):+ return _checkpoint_case(request.param, monkeypatch, tmp_path)+++def _checkpoint_case(family, monkeypatch, tmp_path):+ """Use a tiny real checkpoint and model geometry with the production reader and loader bodies."""+ import diffusers++ from invokeai.backend.ideogram4 import modeling_ideogram4+ from invokeai.backend.model_manager.configs.main import (+ Main_Checkpoint_Ideogram4_Config,+ Main_Checkpoint_Krea2_Config,+ Main_Checkpoint_QwenImage_Config,+ )+ from invokeai.backend.model_manager.configs.mistral_encoder import MistralEncoder_Checkpoint_Config+ from invokeai.backend.model_manager.load.model_loaders import ideogram4, krea2, mistral_encoder, qwen_image++ cases = {+ "mistral": (mistral_encoder, mistral_encoder.MistralEncoderCheckpointLoader, MistralEncoder_Checkpoint_Config),+ "qwen": (qwen_image, qwen_image.QwenImageCheckpointModel, Main_Checkpoint_QwenImage_Config),+ "krea": (krea2, krea2.Krea2CheckpointModel, Main_Checkpoint_Krea2_Config),+ "ideogram": (ideogram4, ideogram4.Ideogram4CheckpointModel, Main_Checkpoint_Ideogram4_Config),+ }+ module, cls, config_class = cases[family]+ subtype = SubModelType.TextEncoder if family == "mistral" else SubModelType.Transformer+ prefix = "model." if family == "mistral" else ""+ source = {prefix + "proj.weight": torch.ones(4, 4).to(FP8), prefix + "proj.weight_scale": torch.tensor(0.5)}+ path = tmp_path / "tiny.safetensors"+ save_file(source, str(path))+ reads = []+ original = module.load_safetensors_checkpoint++ def read(*args, **kwargs):+ reads.append(str(args[0]))+ return original(*args, **kwargs)++ monkeypatch.setattr(module, "load_safetensors_checkpoint", read)+ if family == "ideogram":+ monkeypatch.setattr(modeling_ideogram4, "Ideogram4Transformer", _TinyModel)+ elif family == "qwen":+ monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _TinyModel)+ monkeypatch.setattr(qwen_image, "_build_qwen_image_transformer_config", lambda *_a, **_kw: {})+ elif family == "krea":+ # Model construction is the same boundary as test_krea2_loader_boundaries.py.+ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyModel, raising=False)+ else:+ monkeypatch.setattr(mistral_encoder, "MistralModel", _TinyModel)+ monkeypatch.setattr(+ mistral_encoder,+ "_build_mistral_config",+ lambda *_a, **_kw: SimpleNamespace(+ num_hidden_layers=1, hidden_size=4, num_attention_heads=1, num_key_value_heads=1, intermediate_size=4+ ),+ )+ monkeypatch.setattr(module, "read_safetensors_metadata", lambda *_a: {})+ monkeypatch.setattr(TorchDevice, "choose_torch_device", staticmethod(lambda: torch.device("cpu")))+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: torch.float32))+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda device: device.index == 0)+ for host in (mistral_encoder, qwen_image):+ if hasattr(host, "should_keep_fp8_weights"):+ monkeypatch.setattr(host, "should_keep_fp8_weights", lambda device: device.index == 0)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: False)+ if hasattr(mistral_encoder, "_device_supports_fp8_storage"):+ monkeypatch.setattr(mistral_encoder, "_device_supports_fp8_storage", lambda *_a: False)++ def config(**extra):+ if family == "mistral":+ extra.setdefault("variant", MistralVariantType.Mistral24B)+ if family == "krea":+ extra.setdefault("variant", Krea2VariantType.Turbo)+ return config_class.model_construct(key="checkpoint", name="tiny", path=str(path), **extra)++ return cls, config, subtype, reads++[email protected]("capable_first", [True, False])+def test_checkpoint_caches_preserve_fp8_or_folded_storage(checkpoint_case, monkeypatch, tmp_path, capable_first):+ cls, config, subtype, reads = checkpoint_case+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ capable = _loader(cls, store, budget, "cuda:0", tmp_path)+ incapable = _loader(cls, store, budget, "cuda:1", tmp_path)+ try:+ loaders = [capable, incapable] if capable_first else [incapable, capable]+ first = _load(loaders[0], config(), subtype)+ assert first.proj.weight.dtype == (FP8 if capable_first else torch.float32)+ assert len(reads) == 1+ models = {loaders[0]: first, loaders[1]: _load(loaders[1], config(), subtype)}+ assert models[capable].proj.weight.dtype == FP8+ assert models[incapable].proj.weight.dtype == torch.float32+ torch.testing.assert_close(models[incapable].proj.weight, torch.full((4, 4), 0.5))+ assert models[capable].proj.weight.data_ptr() != models[incapable].proj.weight.data_ptr()+ assert len(reads) == 2+ # A third cache with matching policy adopts the first device's canonical storage without reading again.+ peer = _loader(cls, store, budget, "cuda:0", tmp_path)+ try:+ adopted = _load(peer, config(), subtype)+ assert adopted.proj.weight.data_ptr() == models[capable].proj.weight.data_ptr()+ assert len(reads) == 2+ finally:+ peer._ram_cache.shutdown()+ finally:+ capable._ram_cache.shutdown()+ incapable._ram_cache.shutdown()++[email protected]("reverse", [True, False])+def test_checkpoint_caches_do_not_adopt_a_different_folded_dtype(checkpoint_case, monkeypatch, tmp_path, reverse):+ cls, config, subtype, reads = checkpoint_case+ from invokeai.backend.model_manager.load.model_loaders import mistral_encoder, qwen_image++ for module in (load_default, mistral_encoder, qwen_image):+ if hasattr(module, "should_keep_fp8_weights"):+ monkeypatch.setattr(module, "should_keep_fp8_weights", lambda _d: False)+ monkeypatch.setattr(+ TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda d: torch.float16 if d.index == 0 else torch.float32),+ )+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ half = _loader(cls, store, budget, "cuda:0", tmp_path)+ full = _loader(cls, store, budget, "cuda:1", tmp_path)+ try:+ loaders = [full, half] if reverse else [half, full]+ first = _load(loaders[0], config(), subtype)+ assert first.proj.weight.dtype == (torch.float32 if reverse else torch.float16)+ assert len(reads) == 1+ models = {loaders[0]: first, loaders[1]: _load(loaders[1], config(), subtype)}+ assert models[half].proj.weight.dtype == torch.float16+ assert models[full].proj.weight.dtype == torch.float32+ assert models[half].proj.weight.data_ptr() != models[full].proj.weight.data_ptr()+ assert len(reads) == 2+ finally:+ half._ram_cache.shutdown()+ full._ram_cache.shutdown()+++def test_checkpoint_key_freezes_the_build_capability_and_dtype(checkpoint_case, monkeypatch, tmp_path):+ cls, config_factory, subtype, _reads = checkpoint_case+ from invokeai.backend.model_manager.load.model_loaders import mistral_encoder, qwen_image++ state = {"keep": False, "dtype": torch.float32}+ calls = []++ def keep(_device):+ calls.append(True)+ return state["keep"]++ for module in (load_default, mistral_encoder, qwen_image):+ if hasattr(module, "should_keep_fp8_weights"):+ monkeypatch.setattr(module, "should_keep_fp8_weights", keep)+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: state["dtype"]))+ store = SharedCpuWeightsStore()+ loader = _loader(cls, store, RamBudget(10**9, store), "cuda:0", tmp_path)+ config = config_factory()+ try:+ loader._cache_key_variant(config, subtype)+ state.update(keep=True, dtype=torch.float16)+ model = _load(loader, config, subtype)+ assert model.proj.weight.dtype == torch.float32+ assert len(calls) == 1+ finally:+ loader._ram_cache.shutdown()+++def test_cpu_only_mistral_shares_with_cpu_instead_of_the_loaders_gpu(monkeypatch, tmp_path):+ cls, config, subtype, reads = _checkpoint_case("mistral", monkeypatch, tmp_path)+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ cpu = _loader(cls, store, budget, "cpu", tmp_path)+ cpu_only = _loader(cls, store, budget, "cuda:0", tmp_path)+ try:+ a = _load(cpu, config(), subtype)+ b = _load(cpu_only, config(cpu_only=True), subtype)+ assert a.proj.weight.dtype == b.proj.weight.dtype == torch.float32+ assert a.proj.weight.data_ptr() == b.proj.weight.data_ptr()+ assert len(reads) == 1+ # The original GPU policy still needs its own fp8 canonical copy.+ gpu = _loader(cls, store, budget, "cuda:0", tmp_path)+ try:+ c = _load(gpu, config(), subtype)+ assert c.proj.weight.dtype == FP8+ assert c.proj.weight.data_ptr() != a.proj.weight.data_ptr()+ assert len(reads) == 2+ finally:+ gpu._ram_cache.shutdown()+ finally:+ cpu._ram_cache.shutdown()+ cpu_only._ram_cache.shutdown()+++def test_single_file_prefetch_uses_the_same_variant_as_a_later_load(monkeypatch, tmp_path):+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config+ from invokeai.backend.model_manager.load.model_loaders.stable_diffusion import (+ StableDiffusionDiffusersModel,+ StableDiffusionPipeline,+ )+ from invokeai.backend.model_manager.taxonomy import ModelVariantType++ calls = []++ def pipeline(*_a, **_kw):+ calls.append(True)+ parts = {}+ for name in ("unet", "text_encoder", "vae"):+ model = _TinyModel()+ model.load_state_dict({"proj.weight": torch.ones(4, 4)}, assign=True)+ parts[name] = model+ return SimpleNamespace(**parts)++ monkeypatch.setattr(StableDiffusionPipeline, "from_single_file", pipeline)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ store = SharedCpuWeightsStore()+ loader = _loader(StableDiffusionDiffusersModel, store, RamBudget(10**9, store), "cuda:0", tmp_path)+ config = Main_Checkpoint_SD1_Config.model_construct(+ key="pipeline",+ name="tiny",+ path="tiny.safetensors",+ variant=ModelVariantType.Normal,+ default_settings=MainModelDefaultSettings(fp8_storage=True),+ )+ try:+ _load(loader, config, SubModelType.TextEncoder)+ model = _load(loader, config, SubModelType.UNet)+ assert model.proj.weight.dtype == FP8+ assert len(calls) == 1+ assert store.peek("pipeline:unet") is None+ finally:+ loader._ram_cache.shutdown()diff --git a/tests/backend/model_manager/load/test_fp8_sibling_adoption.py b/tests/backend/model_manager/load/test_fp8_sibling_adoption.pynew file mode 100644index 0000000000..56314f1707--- /dev/null+++ b/tests/backend/model_manager/load/test_fp8_sibling_adoption.py@@ -0,0 +1,107 @@+"""Registered sibling loaders run their native bodies against real shared stores and small geometry."""++import json+from contextlib import ExitStack++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry+from invokeai.backend.model_manager.taxonomy import FluxVariantType, Qwen35VariantType, SubModelType+from invokeai.backend.util.devices import TorchDevice+from tests.backend.model_manager.load.test_fp8_review_regressions import _device_loaders+from tests.backend.model_manager.load.test_fp8_shared_weight_variants import FP8, _TinyModel+from tests.backend.model_manager.load.test_layerwise_storage_policy import _public_load+++def _sibling(family, monkeypatch, tmp_path):+ import diffusers++ from invokeai.backend.anima import anima_transformer+ from invokeai.backend.model_manager.configs import main+ from invokeai.backend.model_manager.configs.qwen3_5_encoder import Qwen35Encoder_Checkpoint_Config+ from invokeai.backend.model_manager.load.model_loaders import anima, flux++ # Only the large geometry is substituted on these five transformer paths. No loader class,+ # cache lookup, quantization operation, admission or adoption implementation is replaced.+ config_cls = {+ "anima": main.Main_Checkpoint_Anima_Config,+ "flux": main.Main_Checkpoint_FLUX_Config,+ "flux2": main.Main_Checkpoint_Flux2_Config,+ "z": main.Main_Checkpoint_ZImage_Config,+ "qwen21": main.Main_Checkpoint_QwenImage21_Config,+ "qwen35": Qwen35Encoder_Checkpoint_Config,+ "moss-text": main.Main_Diffusers_MossImage_Config,+ }[family]+ subtype = SubModelType.TextEncoder if family in ("qwen35", "moss-text") else SubModelType.Transformer+ source = {"proj.weight": torch.ones(4, 4).to(FP8)}+ weight = "proj.weight"+ path = tmp_path / "sibling.safetensors"+ extra = {}+ if family == "anima":+ monkeypatch.setattr(anima_transformer, "AnimaTransformer", _TinyModel)+ monkeypatch.setattr(anima, "anima_transformer_config", lambda _sd: {})+ monkeypatch.setattr(TorchDevice, "choose_anima_inference_dtype", staticmethod(lambda _d: torch.float32))+ elif family == "flux":+ monkeypatch.setattr(flux, "Flux", _TinyModel)+ monkeypatch.setattr(flux, "get_flux_transformers_params", lambda _variant: None)+ extra["variant"] = FluxVariantType.Dev+ elif family == "flux2":+ monkeypatch.setattr(diffusers, "Flux2Transformer2DModel", _TinyModel)+ elif family in ("z", "qwen21"):+ prefix = "layers" if family == "z" else "transformer_blocks"++ class TinyBlocks(torch.nn.Module):+ def __init__(self, **_kwargs):+ super().__init__()+ setattr(self, prefix, torch.nn.ModuleList([_TinyModel()]))++ weight = f"{prefix}.0.proj.weight"+ source = {weight: torch.ones(4, 4).to(FP8)}+ name = "ZImageTransformer2DModel" if family == "z" else "QwenImage21Transformer2DModel"+ monkeypatch.setattr(diffusers, name, TinyBlocks)+ else:+ from invokeai.backend.qwen3_5 import qwen3_5_encoder+ from tests.backend.model_manager.load.test_moss_image_loader import _TINY_TEXT_ENCODER_CONFIG+ from tests.backend.qwen3_5.test_qwen3_5_loading import _config, _reference++ reference = _reference(final_norm=True)+ source = {name: value.detach().clone().contiguous() for name, value in reference.state_dict().items()}+ weight = "layers.3.self_attn.q_proj.weight"+ source[weight] = torch.ones_like(source[weight]).to(FP8)+ if family == "qwen35":+ monkeypatch.setattr(qwen3_5_encoder, "qwen3_5_text_config", lambda _variant: _config())+ extra["variant"] = Qwen35VariantType.Qwen35_9B+ else:+ path = tmp_path / "moss"+ (path / "text_encoder").mkdir(parents=True)+ (path / "text_encoder" / "config.json").write_text(json.dumps(_TINY_TEXT_ENCODER_CONFIG))+ checkpoint = path / "text_encoder" / "model.safetensors" if family == "moss-text" else path+ save_file(source, str(checkpoint))+ config = config_cls.model_construct(key="sibling", name="sibling", path=str(path), **extra)+ cls, config, subtype = ModelLoaderRegistry.get_implementation(config, subtype)+ return cls, config, subtype, weight++[email protected]("family", ["anima", "flux", "flux2", "z", "qwen21", "qwen35", "moss-text"])[email protected]("reverse", [False, True])+def test_registered_checkpoint_siblings_partition_and_adopt(family, reverse, monkeypatch, tmp_path):+ cls, config, subtype, weight = _sibling(family, monkeypatch, tmp_path)+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: torch.float32))+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda d: d.index == 0)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: False)+ capable, incapable, peer = _device_loaders(cls, tmp_path, ["cuda:0", "cuda:1", "cuda:0"])+ with ExitStack() as stack:+ for loader in (capable, incapable, peer):+ stack.callback(loader._ram_cache.shutdown)+ order = [incapable, capable] if reverse else [capable, incapable]+ models = {loader: _public_load(loader, config.model_copy(), subtype) for loader in order}+ packed, folded = (models[loader].get_parameter(weight) for loader in (capable, incapable))+ assert packed.dtype == FP8+ assert folded.dtype == (torch.bfloat16 if family in ("flux", "flux2") else torch.float32)+ torch.testing.assert_close(folded.float(), torch.ones_like(folded, dtype=torch.float32))+ assert packed.data_ptr() != folded.data_ptr()+ adopted = _public_load(peer, config.model_copy(), subtype)+ assert adopted.get_parameter(weight).data_ptr() == packed.data_ptr()diff --git a/tests/backend/model_manager/load/test_gguf_device_dtype_sharing.py b/tests/backend/model_manager/load/test_gguf_device_dtype_sharing.pynew file mode 100644index 0000000000..067938eb5d--- /dev/null+++ b/tests/backend/model_manager/load/test_gguf_device_dtype_sharing.py@@ -0,0 +1,117 @@+"""Real CPU-resident GGUF weights with simulated execution-device policies."""++import pytest+import torch++from invokeai.backend.model_manager.configs.main import Main_GGUF_ErnieImage_Config, Main_GGUF_SD3_Config+from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore+from invokeai.backend.model_manager.load.model_loaders import ernie_image, sd3+from invokeai.backend.model_manager.load.model_loaders.ernie_image import ErnieImageGGUFModel+from invokeai.backend.model_manager.load.model_loaders.sd3 import SD3GGUFModel+from invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor+from invokeai.backend.util.devices import TorchDevice+from tests.backend.model_manager.load.ernie_image_gguf_fixture import TINY_CONFIG, write_ernie_image_gguf+from tests.backend.model_manager.load.sd3_gguf_fixture import write_sd3_gguf+from tests.backend.model_manager.load.test_fp8_shared_weight_variants import _load, _loader++[email protected]("family", ["ernie", "sd3"])[email protected]("reverse", [False, True])+def test_gguf_sharing_respects_frozen_execution_dtype(monkeypatch, tmp_path, family, reverse):+ policy = {"cuda:0": torch.float16, "cuda:1": torch.float32, "cpu": torch.float32}++ def choose(device):+ return policy[str(device)]++ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(choose))+ monkeypatch.setattr(TorchDevice, "choose_torch_dtype", staticmethod(choose))+ path = tmp_path / f"{family}.gguf"+ if family == "ernie":+ write_ernie_image_gguf(path)+ monkeypatch.setattr(ernie_image, "ERNIE_IMAGE_TRANSFORMER_CONFIG", TINY_CONFIG)+ cls, config_cls, module = ErnieImageGGUFModel, Main_GGUF_ErnieImage_Config, ernie_image+ packed_name = "layers.0.mlp.gate_proj.weight"+ dense_name = "x_embedder.proj.weight"+ else:+ write_sd3_gguf(path)+ cls, config_cls, module = SD3GGUFModel, Main_GGUF_SD3_Config, sd3+ packed_name = "transformer_blocks.0.attn.to_q.weight"+ dense_name = "pos_embed.proj.weight"+ config = config_cls.model_construct(key=family, name=family, path=str(path))+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ half = _loader(cls, store, budget, "cuda:0", tmp_path)+ full = _loader(cls, store, budget, "cuda:1", tmp_path)+ peer = _loader(cls, store, budget, "cuda:0", tmp_path)+ reads = []+ reader = module.gguf_sd_loader++ def read(*args, **kwargs):+ reads.append(kwargs["compute_dtype"])+ return reader(*args, **kwargs)++ monkeypatch.setattr(module, "gguf_sd_loader", read)+ try:+ order = [full, half] if reverse else [half, full]+ models = {+ loader: _load(+ loader, config, None if family == "ernie" and loader is half and reverse else SubModelType.Transformer+ )+ for loader in order+ }+ a = models[half].get_parameter(packed_name).data+ b = models[full].get_parameter(packed_name).data+ assert isinstance(a, GGMLTensor) and isinstance(b, GGMLTensor)+ assert a.compute_dtype == torch.float16 and b.compute_dtype == torch.float32+ assert models[half].get_parameter(dense_name).dtype == torch.float16+ assert models[full].get_parameter(dense_name).dtype == torch.float32+ assert a.quantized_data.data_ptr() != b.quantized_data.data_ptr()+ assert half._get_cache_key(config, SubModelType.Transformer) != full._get_cache_key(+ config, SubModelType.Transformer+ )+ adopted = _load(peer, config, None if family == "ernie" and not reverse else SubModelType.Transformer)+ c = adopted.get_parameter(packed_name).data+ assert c.compute_dtype == torch.float16+ assert c.quantized_data.data_ptr() == a.quantized_data.data_ptr()+ assert len(reads) == 2+ finally:+ for loader in (half, full, peer):+ loader._ram_cache.shutdown()++[email protected]("family", ["ernie", "sd3"])+def test_gguf_cpu_only_freezes_dtype_for_key_and_build(monkeypatch, tmp_path, family):+ policy = {"cpu": torch.float32, "cuda:0": torch.float16}+ devices = []++ def choose(device):+ devices.append(device.type)+ return policy[str(device)]++ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(choose))+ monkeypatch.setattr(TorchDevice, "choose_torch_dtype", staticmethod(choose))+ path = tmp_path / f"{family}.gguf"+ if family == "ernie":+ write_ernie_image_gguf(path)+ monkeypatch.setattr(ernie_image, "ERNIE_IMAGE_TRANSFORMER_CONFIG", TINY_CONFIG)+ cls, config_cls = ErnieImageGGUFModel, Main_GGUF_ErnieImage_Config+ packed_name = "layers.0.mlp.gate_proj.weight"+ else:+ write_sd3_gguf(path)+ cls, config_cls = SD3GGUFModel, Main_GGUF_SD3_Config+ packed_name = "transformer_blocks.0.attn.to_q.weight"+ config = config_cls.model_construct(key=family, name=family, path=str(path)).model_copy(update={"cpu_only": True})+ store = SharedCpuWeightsStore()+ loader = _loader(cls, store, RamBudget(10**9, store), "cuda:0", tmp_path)+ try:+ key = loader._get_cache_key(config, SubModelType.Transformer)+ policy["cpu"] = torch.float16+ model = _load(loader, config, SubModelType.Transformer)+ packed = model.get_parameter(packed_name).data+ assert key.endswith("full-float32")+ assert isinstance(packed, GGMLTensor) and packed.compute_dtype == torch.float32+ assert devices == ["cpu"]+ finally:+ loader._ram_cache.shutdown()diff --git a/tests/backend/model_manager/load/test_keep_fp8_weights.py b/tests/backend/model_manager/load/test_keep_fp8_weights.pyindex 291501d6d2..a012dd8f01 100644--- a/tests/backend/model_manager/load/test_keep_fp8_weights.py+++ b/tests/backend/model_manager/load/test_keep_fp8_weights.py@@ -15,13 +15,14 @@ import torchfrom invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.main import Main_Checkpoint_FLUX_Configfrom invokeai.backend.model_manager.load import load_default-from invokeai.backend.model_manager.load.load_default import ModelLoader+from invokeai.backend.model_manager.load.model_loaders.flux import FluxCheckpointModelfrom invokeai.backend.model_manager.taxonomy import SubModelType-def _loader() -> ModelLoader:- loader = object.__new__(ModelLoader)+def _loader() -> FluxCheckpointModel:+ loader = object.__new__(FluxCheckpointModel)loader._torch_device = torch.device("cuda")+ loader._torch_dtype = torch.float16loader._logger = MagicMock()return loaderdiff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex 20d8a2f8eb..daa2c3037f 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -257,6 +257,7 @@ def test_single_file_loader_keeps_a_mixed_int4_build_named_only_in_its_header_padef test_diffusers_loader_reaches_transformer_from_pretrained(monkeypatch, tmp_path) -> None:config = Main_Diffusers_Krea2_Config.model_construct(path=str(tmp_path), repo_variant=None)loader = object.__new__(Krea2DiffusersModel)+ loader._torch_device = torch.device("cpu")loaded_model = object()load_class = SimpleNamespace(from_pretrained=MagicMock(return_value=loaded_model))loader.get_hf_load_class = lambda _path, _submodel: load_class@@ -495,7 +496,7 @@ def test_checkpoint_encoder_loader_decodes_int8_and_does_not_call_it_fp8(monkeyplambda _device: torch.float32,)monkeypatch.setattr(- "invokeai.backend.model_manager.load.model_loaders.krea2._device_supports_fp8_storage",+ "invokeai.backend.model_manager.load.load_default._device_supports_fp8_storage",lambda _device, _logger: True,)@@ -595,6 +596,7 @@ def test_an_int8_weight_without_a_marker_is_refused(monkeypatch, tmp_path) -> Noloader._logger = MagicMock()monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyInt8Krea2Transformer, raising=False)+ loader._torch_device = torch.device("cpu")monkeypatch.setattr("invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",served_checkpoint(state_dict),diff --git a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.pyindex 190dfa0962..a1fc60ceaa 100644--- a/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_krea2_nvfp4_loader.py@@ -135,7 +135,7 @@ def _load(monkeypatch: pytest.MonkeyPatch, tmp_path, neighbour: str, fp8_storage"read_safetensors_metadata",lambda _path, _logger: {"_quantization_metadata": json.dumps({"layers": header_layers})},)- monkeypatch.setattr(krea2, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)monkeypatch.setattr(krea2.TorchDevice, "choose_torch_device", lambda: torch.device("cpu"))monkeypatch.setattr(krea2.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: COMPUTE_DTYPE)diff --git a/tests/backend/model_manager/load/test_layerwise_storage_policy.py b/tests/backend/model_manager/load/test_layerwise_storage_policy.pynew file mode 100644index 0000000000..e86b825517--- /dev/null+++ b/tests/backend/model_manager/load/test_layerwise_storage_policy.py@@ -0,0 +1,355 @@+"""Exercise storage policy through public loaders, real admission, shells and CPU tensors."""++from contextlib import contextmanager+from types import SimpleNamespace+from unittest.mock import patch++import pytest+import torch+from safetensors.torch import save_file++from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettings+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_cache.ram_budget import RamBudget+from invokeai.backend.model_manager.load.model_cache.shared_cpu_weights import SharedCpuWeightsStore+from invokeai.backend.model_manager.taxonomy import SubModelType+from invokeai.backend.util.devices import TorchDevice+from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR+from tests.backend.model_manager.load.test_fp8_shared_weight_variants import _loader as device_loader+++class _TinyTransformer(torch.nn.Module):+ def __init__(self, **_kwargs):+ super().__init__()+ self.proj = torch.nn.Linear(4, 4, bias=False)+ self.norm = torch.nn.LayerNorm(4)+ self.rope = torch.nn.Module()+ self.rope.register_buffer("bands", torch.ones(2))+++def _public_load(loader, config, subtype=None):+ with patch.object(TorchDevice, "choose_torch_device", return_value=loader._torch_device):+ loaded = loader.load_model(config, subtype)+ with loaded.model_in_ram() as model:+ return model+++def _constructor_case(family, monkeypatch, tmp_path):+ """Use tiny geometry and real files for checkpoint constructors, with lightweight folder loaders."""+ import diffusers++ from invokeai.backend.model_manager.configs import main+ from invokeai.backend.model_manager.load.model_loaders import (+ cogview4,+ ernie_image,+ flux,+ krea2,+ moss_image,+ qwen_image,+ qwen_image_2_1,+ wan,+ z_image,+ )+ from invokeai.backend.model_manager.load.model_loaders.generic_diffusers import GenericDiffusersLoader++ cases = {+ "z": (z_image.ZImageDiffusersModel, main.Main_Diffusers_ZImage_Config),+ "krea": (krea2.Krea2DiffusersModel, main.Main_Diffusers_Krea2_Config),+ "moss": (moss_image.MossImageCheckpointModel, main.Main_Checkpoint_MossImage_Config),+ "moss-folder": (moss_image.MossImageDiffusersModel, main.Main_Diffusers_MossImage_Config),+ "ernie": (ernie_image.ErnieImageCheckpointModel, main.Main_Checkpoint_ErnieImage_Config),+ "flux": (flux.FluxDiffusersModel, main.Main_Diffusers_FLUX_Config),+ "flux2": (flux.Flux2DiffusersModel, main.Main_Diffusers_Flux2_Config),+ "qwen": (qwen_image.QwenImageDiffusersModel, main.Main_Diffusers_QwenImage_Config),+ "cogview": (cogview4.CogView4DiffusersModel, main.Main_Diffusers_CogView4_Config),+ "wan": (wan.WanDiffusersModel, main.Main_Diffusers_Wan_Config),+ "ernie-folder": (ernie_image.ErnieImageDiffusersModel, main.Main_Diffusers_ErnieImage_Config),+ "qwen21": (qwen_image_2_1.QwenImage21DiffusersModel, main.Main_Diffusers_QwenImage21_Config),+ "generic": (GenericDiffusersLoader, main.Main_Diffusers_FLUX_Config),+ }+ cls, config_cls = cases[family]+ reads = []+ source = {key: tensor.detach().clone() for key, tensor in _TinyTransformer().state_dict().items()}+ model_path = tmp_path / family++ def read(*_args):+ reads.append(True)+ return {key: tensor.clone() for key, tensor in source.items()}++ class TinyPretrained:+ @staticmethod+ def from_pretrained(_path, *, torch_dtype=None, dtype=None, **_kwargs):+ compute_dtype = torch_dtype if torch_dtype is not None else dtype+ assert compute_dtype is not None+ model = _TinyTransformer().to(compute_dtype)+ model.load_state_dict({k: v.to(compute_dtype) for k, v in read().items()}, assign=True)+ return model++ if family in ("moss", "moss-folder"):+ monkeypatch.setattr(moss_image, "MOSSImageTransformer", _TinyTransformer)+ monkeypatch.setattr(moss_image, "moss_image_transformer_config", lambda _sd: {})+ if family == "moss-folder":+ transformer = model_path / "transformer"+ transformer.mkdir(parents=True)+ (transformer / "config.json").write_text("{}")+ checkpoint = transformer / "model.safetensors"+ else:+ checkpoint = model_path+ save_file(source, str(checkpoint))+ original = moss_image.load_safetensors_checkpoint++ def read_checkpoint(*args, **kwargs):+ reads.append(True)+ return original(*args, **kwargs)++ monkeypatch.setattr(moss_image, "load_safetensors_checkpoint", read_checkpoint)+ elif family == "ernie":+ monkeypatch.setattr(diffusers, "ErnieImageTransformer2DModel", _TinyTransformer)+ save_file(source, str(model_path))+ original = ernie_image.load_safetensors_checkpoint++ def read_checkpoint(*args, **kwargs):+ reads.append(True)+ return original(*args, **kwargs)++ monkeypatch.setattr(ernie_image, "load_safetensors_checkpoint", read_checkpoint)+ else:+ monkeypatch.setattr(cls, "get_hf_load_class", lambda *_a: TinyPretrained)+ model_path.mkdir()++ def config():+ return config_cls.model_construct(+ key="same-model",+ name="tiny",+ path=str(model_path),+ repo_variant=None,+ default_settings=MainModelDefaultSettings(fp8_storage=True),+ )++ return cls, config, reads++[email protected]("family", ["moss", "ernie"])[email protected]("changing_first", [True, False])+def test_default_transformer_alias_freezes_capability_before_public_adoption(+ family, changing_first, monkeypatch, tmp_path+):+ cls, config, reads = _constructor_case(family, monkeypatch, tmp_path)+ state = {"supports": False}+ calls = []++ def supports(device, _logger):+ calls.append(device)+ return state["supports"] if device.index == 0 else False++ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", supports)+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: torch.float32))+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ changing = device_loader(cls, store, budget, "cuda:0", tmp_path)+ unsupported = device_loader(cls, store, budget, "cuda:1", tmp_path)++ @contextmanager+ def change_after_key(_config):+ state["supports"] = True+ yield lambda: True++ changing.config_check = change_after_key+ loaders = [changing, unsupported] if changing_first else [unsupported, changing]+ try:+ first = _public_load(loaders[0], config())+ second = _public_load(loaders[1], config())+ assert first.proj.weight.dtype == second.proj.weight.dtype == torch.float32+ assert getattr(first, FP8_COMPUTE_DTYPE_ATTR, None) is None+ assert getattr(second, FP8_COMPUTE_DTYPE_ATTR, None) is None+ assert first.proj.weight.data_ptr() == second.proj.weight.data_ptr()+ assert calls.count(torch.device("cuda:0")) == 1+ assert len(reads) == 1+ # Explicit Transformer is the same public component as the default, including across caches.+ state["supports"] = False+ peer = device_loader(cls, store, budget, "cuda:2", tmp_path)+ try:+ explicit = _public_load(peer, config(), SubModelType.Transformer)+ assert explicit.proj.weight.data_ptr() == first.proj.weight.data_ptr()+ assert len(reads) == 1+ finally:+ peer._ram_cache.shutdown()+ finally:+ changing._ram_cache.shutdown()+ unsupported._ram_cache.shutdown()++[email protected]("family", ["z", "krea", "moss", "moss-folder"])[email protected]("reverse", [False, True])+def test_equal_global_dtype_does_not_share_different_constructor_dtypes(family, reverse, monkeypatch, tmp_path):+ cls, config, reads = _constructor_case(family, monkeypatch, tmp_path)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ monkeypatch.setattr(+ TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda d: torch.float16 if d.index == 0 else torch.float32),+ )+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ half = device_loader(cls, store, budget, "cuda:0", tmp_path)+ full = device_loader(cls, store, budget, "cuda:1", tmp_path)+ try:+ loaders = [full, half] if reverse else [half, full]+ models = {loader: _public_load(loader, config(), SubModelType.Transformer) for loader in loaders}+ for loader, dtype in ((half, torch.float16), (full, torch.float32)):+ assert models[loader].norm.weight.dtype == dtype+ assert getattr(models[loader], FP8_COMPUTE_DTYPE_ATTR) == dtype+ assert models[half].proj.weight.data_ptr() != models[full].proj.weight.data_ptr()+ assert len(reads) == 2+ finally:+ half._ram_cache.shutdown()+ full._ram_cache.shutdown()+++def test_flux_fixed_bf16_shares_despite_different_global_dtypes(monkeypatch, tmp_path):+ cls, config, reads = _constructor_case("flux", monkeypatch, tmp_path)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ a = device_loader(cls, store, budget, "cuda:0", tmp_path)+ b = device_loader(cls, store, budget, "cuda:1", tmp_path)+ a._torch_dtype, b._torch_dtype = torch.float16, torch.float32+ try:+ first = _public_load(a, config(), SubModelType.Transformer)+ second = _public_load(b, config(), SubModelType.Transformer)+ assert first.norm.weight.dtype == second.norm.weight.dtype == torch.bfloat16+ assert getattr(first, FP8_COMPUTE_DTYPE_ATTR) == getattr(second, FP8_COMPUTE_DTYPE_ATTR) == torch.bfloat16+ assert first.proj.weight.data_ptr() == second.proj.weight.data_ptr()+ assert len(reads) == 1+ finally:+ a._ram_cache.shutdown()+ b._ram_cache.shutdown()++[email protected]("family", ["flux2", "qwen", "cogview", "wan"])+def test_fixed_bf16_constructors_share_one_canonical_copy_across_global_precisions(family, monkeypatch, tmp_path):+ cls, config, reads = _constructor_case(family, monkeypatch, tmp_path)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ first_loader = device_loader(cls, store, budget, "cuda:0", tmp_path)+ second_loader = device_loader(cls, store, budget, "cuda:1", tmp_path)+ peer_loader = device_loader(cls, store, budget, "cuda:2", tmp_path)+ first_loader._torch_dtype = peer_loader._torch_dtype = torch.float16+ second_loader._torch_dtype = torch.float32+ try:+ first = _public_load(first_loader, config(), SubModelType.Transformer)+ second = _public_load(second_loader, config(), SubModelType.Transformer)+ # Both constructors already force BF16 on V2: only identity/sharing should fail there.+ assert first.norm.weight.dtype == second.norm.weight.dtype == torch.bfloat16+ assert getattr(first, FP8_COMPUTE_DTYPE_ATTR) == getattr(second, FP8_COMPUTE_DTYPE_ATTR) == torch.bfloat16+ assert first.proj.weight.data_ptr() == second.proj.weight.data_ptr()+ assert len(reads) == 1+ peer = _public_load(peer_loader, config(), SubModelType.Transformer)+ assert peer.proj.weight.data_ptr() == first.proj.weight.data_ptr()+ assert len(reads) == 1+ finally:+ first_loader._ram_cache.shutdown()+ second_loader._ram_cache.shutdown()+ peer_loader._ram_cache.shutdown()++[email protected]("family", ["ernie-folder", "qwen21"])[email protected]("reverse", [False, True])+def test_additional_bfloat_safe_constructors_partition_actual_dtypes(family, reverse, monkeypatch, tmp_path):+ cls, config, reads = _constructor_case(family, monkeypatch, tmp_path)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ monkeypatch.setattr(+ TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda d: torch.float16 if d.index == 0 else torch.float32),+ )+ store = SharedCpuWeightsStore()+ budget = RamBudget(10**9, store)+ half = device_loader(cls, store, budget, "cuda:0", tmp_path)+ full = device_loader(cls, store, budget, "cuda:1", tmp_path)+ try:+ loaders = [full, half] if reverse else [half, full]+ first = _public_load(loaders[0], config(), SubModelType.Transformer)+ assert first.norm.weight.dtype == (torch.float32 if reverse else torch.float16)+ assert len(reads) == 1+ models = {loaders[0]: first, loaders[1]: _public_load(loaders[1], config(), SubModelType.Transformer)}+ for loader, dtype in ((half, torch.float16), (full, torch.float32)):+ assert models[loader].norm.weight.dtype == dtype+ assert getattr(models[loader], FP8_COMPUTE_DTYPE_ATTR) == dtype+ assert models[half].proj.weight.data_ptr() != models[full].proj.weight.data_ptr()+ assert len(reads) == 2+ finally:+ half._ram_cache.shutdown()+ full._ram_cache.shutdown()+++def test_generic_loader_keeps_its_configured_constructor_dtype(monkeypatch, tmp_path):+ cls, config, _reads = _constructor_case("generic", monkeypatch, tmp_path)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _d: torch.float32))+ store = SharedCpuWeightsStore()+ loader = device_loader(cls, store, RamBudget(10**9, store), "cuda:0", tmp_path)+ loader._torch_dtype = torch.float16+ try:+ model = _public_load(loader, config())+ assert model.norm.weight.dtype == torch.float16+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) == torch.float16+ finally:+ loader._ram_cache.shutdown()++[email protected]("family", ["z", "krea", "moss", "moss-folder"])+def test_constructor_reuses_the_dtype_selected_before_the_load_lock(family, monkeypatch, tmp_path):+ cls, config, _reads = _constructor_case(family, monkeypatch, tmp_path)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_a: True)+ state = {"dtype": torch.float32}+ choices = []++ def choose(_device):+ choices.append(state["dtype"])+ return state["dtype"]++ monkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(choose))+ store = SharedCpuWeightsStore()+ loader = device_loader(cls, store, RamBudget(10**9, store), "cuda:0", tmp_path)++ @contextmanager+ def change_after_key(_config):+ state["dtype"] = torch.float16+ yield lambda: True++ loader.config_check = change_after_key+ try:+ model = _public_load(loader, config(), SubModelType.Transformer)+ assert model.norm.weight.dtype == torch.float32+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) == torch.float32+ assert choices == [torch.float32]+ finally:+ loader._ram_cache.shutdown()+++def test_a_pipeline_none_still_loads_the_whole_pipeline(monkeypatch, tmp_path):+ from invokeai.backend.model_manager.configs.main import Main_Checkpoint_SD1_Config+ from invokeai.backend.model_manager.load.model_loaders.stable_diffusion import (+ StableDiffusionDiffusersModel,+ StableDiffusionPipeline,+ )+ from invokeai.backend.model_manager.taxonomy import ModelVariantType++ pipeline = SimpleNamespace(unet=_TinyTransformer(), text_encoder=_TinyTransformer())+ monkeypatch.setattr(StableDiffusionPipeline, "from_single_file", lambda *_a, **_kw: pipeline)+ path = tmp_path / "pipeline.safetensors"+ path.touch()+ config = Main_Checkpoint_SD1_Config.model_construct(+ key="pipeline",+ name="pipeline",+ path=str(path),+ variant=ModelVariantType.Normal,+ )+ store = SharedCpuWeightsStore()+ loader = device_loader(StableDiffusionDiffusersModel, store, RamBudget(10**9, store), "cpu", tmp_path)+ try:+ assert _public_load(loader, config) is pipeline+ finally:+ loader._ram_cache.shutdown()diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex e2c55d52ff..5d2b0745d1 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -145,9 +145,10 @@ def test_should_use_fp8_probes_the_device_when_fp8_is_requested():with patch(_STORAGE_PROBE, return_value=True) as mock_probe:assert loader._should_use_fp8(config, None) is Truemock_probe.assert_called_once()- # An unsupported device still vetoes, just without probing on every unrelated load.+ # The key/build answer stays frozen. A fresh load can observe a new capability verdict.with patch(_STORAGE_PROBE, return_value=False):- assert loader._should_use_fp8(config, None) is False+ assert loader._should_use_fp8(config, None) is True+ assert _make_loader("xpu")._should_use_fp8(config, None) is Falsedef test_should_use_fp8_excludes_control_lora():diff --git a/tests/backend/model_manager/load/test_ministral3_encoder_loader.py b/tests/backend/model_manager/load/test_ministral3_encoder_loader.pyindex eb64ea4ef3..202d2d71ac 100644--- a/tests/backend/model_manager/load/test_ministral3_encoder_loader.py+++ b/tests/backend/model_manager/load/test_ministral3_encoder_loader.py@@ -79,6 +79,8 @@ def _write_checkpoint(path: Path, reference: torch.nn.Module, *, with_vision: bodef _load(path: Path, variant: MistralVariantType) -> torch.nn.Module:config = MistralEncoder_Checkpoint_Config.model_construct(path=str(path), name=path.stem, variant=variant)loader = object.__new__(MistralEncoderCheckpointLoader)+ loader._torch_device = torch.device("cpu")+ loader._logger = loader_module.InvokeAILogger.get_logger("test")# The loader reserves before it folds or casts. Nothing here is about the size it asks for, but the# reservation is sized from the model it just built, so a variant the prediction cannot walk fails here.loader._ram_cache = SimpleNamespace(make_room=MagicMock())diff --git a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.pyindex c8752c1e54..d5dd74d227 100644--- a/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_mistral_encoder_checkpoint_loader.py@@ -14,6 +14,7 @@ import torchfrom safetensors.torch import load_file, save_filefrom invokeai.backend.model_manager.configs.mistral_encoder import MistralEncoder_Checkpoint_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_loaders import mistral_encoderfrom invokeai.backend.model_manager.load.model_loaders.mistral_encoder import MistralEncoderCheckpointLoaderfrom invokeai.backend.model_manager.taxonomy import MistralVariantType@@ -131,7 +132,7 @@ def _fp8_matmul(available: bool):asking stay green."""def geometry(patch):- patch.setattr(mistral_encoder, "should_keep_fp8_weights", lambda _device: available)+ patch.setattr(load_default, "should_keep_fp8_weights", lambda _device: available)return geometrydiff --git a/tests/backend/model_manager/load/test_moss_image_loader.py b/tests/backend/model_manager/load/test_moss_image_loader.pyindex d86e23e980..54e6d65aa0 100644--- a/tests/backend/model_manager/load/test_moss_image_loader.py+++ b/tests/backend/model_manager/load/test_moss_image_loader.py@@ -606,12 +606,27 @@ class TestTorchaoFp8Checkpoint:monkeypatch.setattr(loader_module.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: dtype))- loader._should_use_fp8 = lambda _config, _submodel=None: keep_fp8- if fp8_compute_only:- loader._keep_fp8_weights = lambda _config, _submodel=None: True- config = Main_Checkpoint_MossImage_Config.model_construct(path=str(path), name="moss")+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: fp8_compute_only)+ config = Main_Checkpoint_MossImage_Config.model_construct(+ path=str(path), name="moss", default_settings=MainModelDefaultSettings(fp8_storage=keep_fp8)+ )return loader._load_model(config, SubModelType.Transformer), loader, loaded+ @pytest.mark.parametrize(+ ("storage", "compute", "expected"),+ [(False, False, "full-float32"), (False, True, "fp8-float32"), (True, False, "fp8-float32-layerwise")],+ )+ def test_checkpoint_cache_identity_matches_the_loaded_fp8_format(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, storage: bool, compute: bool, expected: str+ ) -> None:+ path, _, _ = self._file(tmp_path)+ model, loader, _ = self._load(monkeypatch, path, keep_fp8=storage, fp8_compute_only=compute)+ config = loader._load_decision.config+ key = loader._get_cache_key(config, SubModelType.Transformer)+ assert key.endswith(f":transformer:storage={expected}")+ assert (model.layers[0].proj["k"].weight.dtype is torch.float8_e4m3fn) == (storage or compute)+@pytest.mark.parametrize("prefix", ["", "model.diffusion_model."])def test_with_fp8_storage_the_file_keeps_its_fp8_layers_and_the_dense_remainder_stays_dense(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, prefix: strdiff --git a/tests/backend/model_manager/load/test_qwen3_embedding_reservation.py b/tests/backend/model_manager/load/test_qwen3_embedding_reservation.pyindex c61817a2ac..5e0306f74b 100644--- a/tests/backend/model_manager/load/test_qwen3_embedding_reservation.py+++ b/tests/backend/model_manager/load/test_qwen3_embedding_reservation.py@@ -95,7 +95,7 @@ def test_qwen3_loader_reserves_live_storage_before_embedding_decode(monkeypatch,else:loader = object.__new__(z_image.ZImageDiffusersModel)loader._ram_cache = cache- model = loader._load_sdnq_text_encoder(path)+ model = loader._load_sdnq_text_encoder(path, torch.float32)output_bytes = VOCAB * HIDDEN * torch.float32.itemsizedecode_budget = 7 * output_bytes if kind == "gguf" else 6 * output_bytesdiff --git a/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.py b/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.pyindex 5d8c89c444..81dd4e9aa8 100644--- a/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.py+++ b/tests/backend/model_manager/load/test_qwen3_encoder_scaled_fp8.py@@ -22,6 +22,7 @@ from safetensors.torch import save_filefrom transformers import Qwen3Config, Qwen3ForCausalLMfrom invokeai.backend.model_manager.configs.qwen3_encoder import Qwen3Encoder_Checkpoint_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules import custom_linearfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (apply_custom_layers_to_model,@@ -160,8 +161,10 @@ def _decide("""The session runs on `device`; only a CUDA device passes the gates that are switched on."""monkeypatch.setattr(z_image.TorchDevice, "choose_torch_device", lambda: torch.device(device))monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)- monkeypatch.setattr(z_image, "should_keep_fp8_weights", lambda d: matmul and d.type == "cuda")- monkeypatch.setattr(z_image, "_device_supports_fp8_storage", lambda d, _logger=None: storage and d.type == "cuda")+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda d: matmul and d.type == "cuda")+ monkeypatch.setattr(+ load_default, "_device_supports_fp8_storage", lambda d, _logger=None: storage and d.type == "cuda"+ )def _loader() -> Qwen3EncoderCheckpointLoader:@@ -374,10 +377,29 @@ def test_the_cache_key_and_the_stored_format_come_from_one_capability_decision(checkpoint = _write(tmp_path)_decide(monkeypatch)loader = _loader()- assert loader._cache_key_variant(_config(checkpoint), SubModelType.TextEncoder) == "float32"+ config = _config(checkpoint)+ assert loader._cache_key_variant(config, SubModelType.TextEncoder) == "full-float32"++ _decide(monkeypatch, storage=True)+ model = loader._load_from_singlefile(config)++ assert all(param.dtype is torch.float32 for param in model.parameters())++def test_cpu_only_encoder_uses_cpu_dtype_for_key_and_weights(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ checkpoint = _write(tmp_path)_decide(monkeypatch, storage=True)- model = loader._load_from_singlefile(_config(checkpoint))+ monkeypatch.setattr(+ z_image.TorchDevice,+ "choose_bfloat16_safe_dtype",+ lambda device: torch.float32 if device.type == "cpu" else torch.bfloat16,+ )+ loader = _loader()+ config = _config(checkpoint, cpu_only=True)+ assert loader._cache_key_variant(config, SubModelType.TextEncoder) == "full-float32"+ monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float16)++ model = loader._load_from_singlefile(config)assert all(param.dtype is torch.float32 for param in model.parameters())@@ -416,8 +438,10 @@ def test_device_caches_share_weights_only_with_a_device_that_builds_the_same_forcheckpoint = _write(tmp_path)monkeypatch.setattr(z_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)- monkeypatch.setattr(z_image, "should_keep_fp8_weights", lambda _device: False)- monkeypatch.setattr(z_image, "_device_supports_fp8_storage", lambda d, _logger=None: d == torch.device("cuda:0"))+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(+ load_default, "_device_supports_fp8_storage", lambda d, _logger=None: d == torch.device("cuda:0")+ )config = Qwen3Encoder_Checkpoint_Config.model_construct(key="qwen3",path=checkpoint.path.name,diff --git a/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.pyindex be51fa49ff..22afc04480 100644--- a/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_qwen3_vl_encoder_nvfp4_loader.py@@ -19,6 +19,7 @@ import torchfrom transformers import Qwen3VLConfig, Qwen3VLModelfrom invokeai.backend.model_manager.configs.qwen3_vl_encoder import Qwen3VLEncoder_Checkpoint_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_loaders import krea2from invokeai.backend.model_manager.load.model_loaders.krea2 import Qwen3VLEncoderCheckpointLoaderfrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear@@ -164,8 +165,8 @@ def _prepare(safetensors.torch.save_file({key: value.contiguous() for key, value in state_dict.items()}, path, metadata)run = prepare(SEAM, monkeypatch, observe=("dequantize_fp8_scaled", "split_fp8_scaled_layers"))run.loader._load_te_config = lambda _config: _te_config()- monkeypatch.setattr(krea2, "should_keep_fp8_weights", lambda _device: matmul)- monkeypatch.setattr(krea2, "_device_supports_fp8_storage", lambda *_args: storage)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: matmul)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: storage)return run, Qwen3VLEncoder_Checkpoint_Config.model_construct(path=str(path), name="encoder")diff --git a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.pyindex 0967380b73..b5e9d76dc8 100644--- a/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py+++ b/tests/backend/model_manager/load/test_qwen3_vl_visual_tower.py@@ -20,6 +20,7 @@ from unittest.mock import MagicMockimport pytestimport torch+from invokeai.backend.model_manager.configs.default_settings import MainModelDefaultSettingsfrom invokeai.backend.model_manager.configs.qwen3_vl_encoder import (Qwen3VLEncoder_Checkpoint_Config,Qwen3VLEncoder_Qwen3VLEncoder_Config,@@ -189,7 +190,7 @@ def _checkpoint_loader(monkeypatch, te_config) -> Qwen3VLEncoderCheckpointLoaderlambda _device: torch.float32,)monkeypatch.setattr(- "invokeai.backend.model_manager.load.model_loaders.krea2._device_supports_fp8_storage",+ "invokeai.backend.model_manager.load.load_default._device_supports_fp8_storage",lambda _device, _logger: False,)return loader@@ -293,6 +294,7 @@ def test_the_bundled_pipeline_encoder_drops_the_tower(monkeypatch, tmp_path: Patencoder = _tiny_encoder()config = Main_Diffusers_Krea2_Config.model_construct(path=str(tmp_path), repo_variant=None)loader = object.__new__(Krea2DiffusersModel)+ loader._torch_device = torch.device("cpu")loader.get_hf_load_class = lambda _path, _submodel: SimpleNamespace(from_pretrained=MagicMock(return_value=encoder))loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: modelmonkeypatch.setattr(@@ -356,6 +358,7 @@ def _qwen_image_2_1_pipeline()config = Main_Diffusers_QwenImage21_Config.model_construct(path=str(tmp_path), repo_variant=None)loader = object.__new__(QwenImage21DiffusersModel)+ loader._torch_device = torch.device("cpu")loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: modelencoder = saved.model if conditional_generation else savedreturn loader, config, encoder@@ -423,6 +426,31 @@ def test_the_tower_reserves_its_own_size_at_the_dtype_it_loads_in(monkeypatch, tassert loader.get_size_fs(config, tmp_path, SubModelType.VisionEncoder) == 4 * elements[email protected]("cpu_dtype", [torch.float32, torch.bfloat16])+def test_cpu_only_tower_reservation_matches_frozen_load_dtype(+ monkeypatch, tmp_path: Path, cpu_dtype: torch.dtype+) -> None:+ loader, config, saved = _qwen_image_2_1_pipeline(monkeypatch, tmp_path, conditional_generation=True)+ config.default_settings = MainModelDefaultSettings(cpu_only=True)+ loader._torch_device = torch.device("cuda:0")+ other_dtype = torch.bfloat16 if cpu_dtype == torch.float32 else torch.float32+ monkeypatch.setattr("invokeai.backend.util.devices.TorchDevice.choose_torch_device", lambda: torch.device("cuda:0"))+ monkeypatch.setattr(+ "invokeai.backend.util.devices.TorchDevice.choose_bfloat16_safe_dtype",+ lambda device: cpu_dtype if device.type == "cpu" else other_dtype,+ )++ # Cache-key lookup freezes the decision before the reservation and construction.+ loader._decision(config, SubModelType.VisionEncoder)+ reserved = loader.get_size_fs(config, tmp_path, SubModelType.VisionEncoder)+ monkeypatch.setattr("invokeai.backend.util.devices.TorchDevice.choose_bfloat16_safe_dtype", lambda _d: other_dtype)+ tower = loader._load_model(config, SubModelType.VisionEncoder)++ assert all(t.dtype == cpu_dtype for t in tower.state_dict().values())+ assert reserved == sum(t.numel() * t.element_size() for t in tower.state_dict().values())+ assert reserved == sum(t.numel() for t in saved.visual.state_dict().values()) * cpu_dtype.itemsize++@needs_mapping_that_shows_file_writesdef test_the_tower_does_not_keep_the_text_encoders_shards_mapped(monkeypatch, tmp_path: Path) -> None:"""Saved in the dtype it loads in, the tower's cast is a no-op, so each tensor read from a shard would stay a viewdiff --git a/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py b/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.pyindex a7f8394fcd..c24c10a728 100644--- a/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py+++ b/tests/backend/model_manager/load/test_qwen_image_encoder_fp8.py@@ -21,6 +21,7 @@ from safetensors.torch import save_filefrom transformers import Qwen2_5_VLConfig, Qwen2_5_VLForConditionalGenerationfrom invokeai.backend.model_manager.configs.qwen_vl_encoder import QwenVLEncoder_Checkpoint_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules import custom_linearfrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (apply_custom_layers_to_model,@@ -165,9 +166,9 @@ def _decide(monkeypatch: pytest.MonkeyPatch, *, device: str, matmul: bool = Falsmonkeypatch.setattr(qwen_image, "load_bundled_qwen2_5_vl_config_dict", _toy_config_dict)monkeypatch.setattr(qwen_image.TorchDevice, "choose_torch_device", lambda: torch.device(device))monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)- monkeypatch.setattr(qwen_image, "should_keep_fp8_weights", lambda d: matmul and d.type == "cuda")+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda d: matmul and d.type == "cuda")monkeypatch.setattr(- qwen_image, "_device_supports_fp8_storage", lambda d, _logger=None: storage and d.type == "cuda"+ load_default, "_device_supports_fp8_storage", lambda d, _logger=None: storage and d.type == "cuda")@@ -179,8 +180,9 @@ def _loader() -> QwenVLEncoderCheckpointLoader:return loader-def _load(checkpoint: _Checkpoint, loader: QwenVLEncoderCheckpointLoader | None = None):- config = QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint.path))+def _load(checkpoint: _Checkpoint, loader: QwenVLEncoderCheckpointLoader | None = None, config=None):+ if config is None:+ config = QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint.path))return (loader or _loader())._load_text_encoder_from_singlefile(config)@@ -426,10 +428,28 @@ def test_the_cache_key_and_the_stored_format_come_from_one_capability_decision(_decide(monkeypatch, device="cuda:0")loader = _loader()config = QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint.path))- assert loader._cache_key_variant(config, SubModelType.TextEncoder) == "float32"+ assert loader._cache_key_variant(config, SubModelType.TextEncoder) == "full-float32"_decide(monkeypatch, device="cuda:0", storage=True)- model = _load(checkpoint, loader)+ model = _load(checkpoint, loader, config)++ assert all(param.dtype is torch.float32 for param in model.parameters())+++def test_cpu_encoder_uses_cpu_dtype_for_key_and_weights(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ checkpoint = _write(tmp_path)+ _decide(monkeypatch, device="cpu", storage=True)+ monkeypatch.setattr(+ qwen_image.TorchDevice,+ "choose_bfloat16_safe_dtype",+ lambda device: torch.float32 if device.type == "cpu" else torch.bfloat16,+ )+ loader = _loader()+ config = QwenVLEncoder_Checkpoint_Config.model_construct(path=str(checkpoint.path))+ assert loader._cache_key_variant(config, SubModelType.TextEncoder) == "full-float32"+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float16)++ model = _load(checkpoint, loader, config)assert all(param.dtype is torch.float32 for param in model.parameters())@@ -469,8 +489,10 @@ def test_device_caches_share_weights_only_with_a_device_that_builds_the_same_forcheckpoint = _write(tmp_path)monkeypatch.setattr(qwen_image, "load_bundled_qwen2_5_vl_config_dict", _toy_config_dict)monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)- monkeypatch.setattr(qwen_image, "should_keep_fp8_weights", lambda _device: False)- monkeypatch.setattr(qwen_image, "_device_supports_fp8_storage", lambda d, _logger=None: d == torch.device("cuda:0"))+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: False)+ monkeypatch.setattr(+ load_default, "_device_supports_fp8_storage", lambda d, _logger=None: d == torch.device("cuda:0")+ )config = QwenVLEncoder_Checkpoint_Config.model_construct(key="qwen-vl",path=checkpoint.path.name,diff --git a/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.py b/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.pyindex c82a216751..43e9f29823 100644--- a/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.py+++ b/tests/backend/model_manager/load/test_qwen_image_encoder_lm_head.py@@ -63,8 +63,7 @@ def _load_standalone(root: Path) -> torch.nn.Module:def _load_from_main_model(root: Path) -> torch.nn.Module:index = {"text_encoder": ["transformers", "Qwen2_5_VLForConditionalGeneration"]}(root / "model_index.json").write_text(json.dumps(index))- loader = object.__new__(QwenImageDiffusersModel)- loader._logger = MagicMock()+ loader = QwenImageDiffusersModel(MagicMock(), MagicMock(), MagicMock())config = Main_Diffusers_QwenImage_Config.model_construct(path=str(root), repo_variant=None)return loader._load_model(config, SubModelType.TextEncoder)diff --git a/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.py b/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.pyindex 2d05e21b77..fa6a6a7660 100644--- a/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.py+++ b/tests/backend/model_manager/load/test_qwen_image_int8_convrot_loader.py@@ -226,6 +226,34 @@ def test_the_reservation_is_one_call_made_before_the_split_and_the_cast_widen_anassert widening_steps == [("split_int8_convrot_layers", 1), ("cast_unquantized", 1)][email protected]("dtype,later_dtype", [(torch.float32, torch.bfloat16), (torch.bfloat16, torch.float32)])+def test_int8_loading_uses_the_dtype_captured_for_its_cache_key(monkeypatch, tmp_path, dtype, later_dtype) -> None:+ state_dict, expected = _state_dict()+ run, config = _run(monkeypatch, tmp_path, state_dict)+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: dtype))+ key = run.loader._get_cache_key(config, SubModelType.Transformer)+ monkeypatch.setattr(qwen_image.TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _device: later_dtype))++ model = run.loader._load_model(config, SubModelType.Transformer)++ assert model.img_in.weight.dtype is dtype+ torch.testing.assert_close(model.img_in.weight, state_dict["img_in.weight"].to(dtype))+ for path, weight in expected.items():+ layer = model.get_submodule(path)+ assert isinstance(layer, Int8ConvrotLinear), path+ assert layer.weight.dtype is torch.int8, path+ assert layer.weight_scale.dtype is torch.float32, path+ x = torch.arange(64, dtype=torch.float32).reshape(1, 64) / 64+ bias = state_dict[f"{path}.bias"].to(dtype).float()+ torch.testing.assert_close(layer(x), torch.nn.functional.linear(x, weight, bias), rtol=1e-4, atol=1e-4)+ # Packed codes and fp32 column scales are fixed; only the dense remainder follows the captured dtype.+ int8 = sum(out * inp for out, inp in LAYERS.values())+ scales = sum(out for out, _ in LAYERS.values()) * 4+ dense = sum(out for out, _ in LAYERS.values()) + 2 * (128 * 64 + 128)+ assert run.reserved == [int8 + scales + dense * dtype.itemsize]+ assert run.loader._get_cache_key(config, SubModelType.Transformer) == key++def test_fp8_storage_leaves_an_int8_build_as_loaded(monkeypatch, tmp_path) -> None:"""The int8 layers stay int8 and the dense remainder (`img_in`, the modulation) stays at the compute dtype: thebuild is the same tensor for tensor as the load without FP8 Storage."""diff --git a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.pyindex 65c315c81e..2c8fa41eb1 100644--- a/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py+++ b/tests/backend/model_manager/load/test_qwen_image_nvfp4_loader.py@@ -144,7 +144,7 @@ def test_the_transformer_keeps_nvfp4_packed_and_scaled_fp8_only_where_something_log = _patch_common(monkeypatch, state_dict, {"_quantization_metadata": json.dumps({"layers": header})})monkeypatch.setattr(diffusers, "QwenImageTransformer2DModel", _TinyQwenImageTransformer, raising=False)- monkeypatch.setattr(qwen_image, "should_keep_fp8_weights", lambda _device: mode == "fp8_compute")+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: mode == "fp8_compute")monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: True)checkpoint = tmp_path / "qwen_image_nvfp4.safetensors"checkpoint.touch()diff --git a/tests/backend/model_manager/load/test_shared_weight_adoption.py b/tests/backend/model_manager/load/test_shared_weight_adoption.pyindex 75d12c014d..3ec267af80 100644--- a/tests/backend/model_manager/load/test_shared_weight_adoption.py+++ b/tests/backend/model_manager/load/test_shared_weight_adoption.py@@ -201,9 +201,9 @@ class _AdmissionModel(torch.nn.Module):class _FileLoader(ModelLoader):def __init__(self, cache, path, layout):- self._ram_cache = cache- self._logger = logging.getLogger(__name__)- self._app_config = SimpleNamespace(log_memory_usage=False, models_path=path.parent)+ super().__init__(+ SimpleNamespace(log_memory_usage=False, models_path=path.parent), logging.getLogger(__name__), cache+ )self.layout = layoutself.disk_loads = 0diff --git a/tests/backend/model_manager/load/test_t5_single_file_loader.py b/tests/backend/model_manager/load/test_t5_single_file_loader.pyindex 07ef962a60..e0c15da935 100644--- a/tests/backend/model_manager/load/test_t5_single_file_loader.py+++ b/tests/backend/model_manager/load/test_t5_single_file_loader.py@@ -16,8 +16,8 @@ import torchfrom safetensors.torch import save_filefrom transformers import T5Config, T5EncoderModel-import invokeai.backend.model_manager.load.model_loaders.flux as loader_modulefrom invokeai.backend.model_manager.configs.t5_encoder import T5Encoder_Checkpoint_Config+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.load_default import put_in_eval_modefrom invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (apply_custom_layers_to_model,@@ -121,8 +121,8 @@ def loader() -> T5EncoderSingleFileLoader:def _keep_fp8(monkeypatch: pytest.MonkeyPatch, keep: bool) -> None:- monkeypatch.setattr(loader_module, "should_keep_fp8_weights", lambda _device: keep)- monkeypatch.setattr(loader_module, "_device_supports_fp8_storage", lambda _device, _logger=None: keep)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: keep)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda _device, _logger=None: keep)def _load_encoder(loader: T5EncoderSingleFileLoader, path: Path) -> T5EncoderModel:@@ -254,8 +254,8 @@ def test_device_caches_share_weights_only_with_a_device_that_builds_the_same_forfrom invokeai.backend.model_manager.taxonomy import BaseModelType, ModelTypemonkeypatch.setattr(TorchDevice, "choose_bfloat16_safe_dtype", staticmethod(lambda _: torch.float32))- monkeypatch.setattr(loader_module, "should_keep_fp8_weights", lambda device: device.type == "cuda")- monkeypatch.setattr(loader_module, "_device_supports_fp8_storage", lambda device, _logger=None: False)+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda device: device.type == "cuda")+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda device, _logger=None: False)path = tmp_path / "t5xxl.safetensors"_write_scaled_fp8(_tiny_reference(), path)config = T5Encoder_Checkpoint_Config.model_construct(diff --git a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py b/tests/backend/model_manager/load/test_wan_checkpoint_loader.pyindex c978fa447d..6a7d20a324 100644--- a/tests/backend/model_manager/load/test_wan_checkpoint_loader.py+++ b/tests/backend/model_manager/load/test_wan_checkpoint_loader.py@@ -28,7 +28,7 @@ from invokeai.backend.model_manager.load.model_loaders.wan import (WanCheckpointModel,_build_wan_transformer_config,)-from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantType+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType, WanVariantTypefrom invokeai.backend.quantization.fp8_scaled import is_scale_metadata_key, set_full_precision_hints_respectedfrom invokeai.backend.quantization.int8_convrot import Int8ConvrotLinearfrom tests.fixtures.loader_seams import assert_fp8_storage_declined, logged_info@@ -106,6 +106,7 @@ def _recording_model() -> tuple[MagicMock, dict[str, torch.Tensor]]:def _make_loader() -> WanCheckpointModel:loader = object.__new__(WanCheckpointModel)loader._ram_cache = MagicMock()+ loader._logger = MagicMock()loader._torch_device = torch.device("cpu")return loader@@ -121,6 +122,8 @@ def _load(config = MagicMock()config.path = str(path)config.variant = variant+ config.base, config.type, config.format = BaseModelType.Wan, ModelType.Main, ModelFormat.Checkpoint+ config.default_settings.fp8_storage = getattr(loader, "_test_fp8_storage", False)with (patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_torch_device"),@@ -918,8 +921,9 @@ def _mxfp8_checkpoint(layers: list[str]) -> tuple[torch.nn.Module, dict[str, tordef _storage_loader(monkeypatch: pytest.MonkeyPatch, *, storage: bool, fp8_matmul: bool = False) -> WanCheckpointModel:"""A loader whose settings are as given and whose FP8 Storage cast is the real one."""loader = _make_loader()- loader._should_use_fp8 = lambda *_args: storage+ loader._test_fp8_storage = storagemonkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda _device: fp8_matmul)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: storage)return loaderdiff --git a/tests/backend/model_manager/load/test_wan_fp8_wiring.py b/tests/backend/model_manager/load/test_wan_fp8_wiring.pyindex 9c35448217..478fd772bb 100644--- a/tests/backend/model_manager/load/test_wan_fp8_wiring.py+++ b/tests/backend/model_manager/load/test_wan_fp8_wiring.py@@ -26,8 +26,9 @@ from unittest.mock import MagicMock, patchimport torchfrom safetensors.torch import save_file+from invokeai.backend.model_manager.load import load_defaultfrom invokeai.backend.model_manager.load.model_loaders.wan import WanCheckpointModel, WanDiffusersModel-from invokeai.backend.model_manager.taxonomy import SubModelType, WanVariantType+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType, WanVariantType# Same tiny-but-faithful transformer the sibling loader tests use; `attention_head_dim` must stay 128,# because the loader derives `num_attention_heads` from it.@@ -68,9 +69,10 @@ def _checkpoint(path: Path, scaled: bool) -> Path:def _loader(cast_calls: list, *, asks_for_fp8: bool = True) -> WanCheckpointModel:loader = object.__new__(WanCheckpointModel)loader._ram_cache = MagicMock()+ loader._logger = MagicMock()loader._torch_device = torch.device("cpu")- # The gate itself has its own cells in `test_load_default_fp8.py`.- loader._should_use_fp8 = lambda *_args, **_kwargs: asks_for_fp8+ loader._torch_dtype = torch.float32+ loader._test_fp8_storage = asks_for_fp8loader._apply_fp8_layerwise_casting = lambda model, config, submodel: (cast_calls.append((config, submodel)),model,@@ -82,9 +84,13 @@ def _load(loader: WanCheckpointModel, path: Path):config = MagicMock()config.path = str(path)config.variant = WanVariantType.T2V_A14B+ config.base, config.type, config.format = BaseModelType.Wan, ModelType.Main, ModelFormat.Checkpoint+ config.default_settings.fp8_storage = getattr(loader, "_test_fp8_storage", False)with (patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_torch_device"),+ patch("invokeai.backend.model_manager.load.load_default.should_keep_fp8_weights", return_value=False),+ patch("invokeai.backend.model_manager.load.load_default._device_supports_fp8_storage", return_value=True),patch("invokeai.backend.model_manager.load.model_loaders.wan.TorchDevice.choose_bfloat16_safe_dtype",return_value=torch.bfloat16,@@ -133,6 +139,8 @@ class TestTheCheckpointLoader:observed: list[int] = []loader = object.__new__(WanCheckpointModel)loader._ram_cache = MagicMock()+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.float32loader._should_use_fp8 = lambda *_args, **_kwargs: Truecaptured: dict[str, dict] = {}@@ -155,6 +163,32 @@ class TestTheCheckpointLoader:assert observed == [0], "the loader still held every bf16 tensor while the cast allocated fp8 copies"+def test_checkpoint_cache_key_and_scaled_weights_share_one_device_decision(monkeypatch, tmp_path: Path) -> None:+ path = _checkpoint(tmp_path / "wan_fp8_scaled.safetensors", scaled=True)+ config = MagicMock()+ config.path, config.key, config.variant = str(path), "wan", WanVariantType.T2V_A14B+ config.base, config.type, config.format = BaseModelType.Wan, ModelType.Main, ModelFormat.Checkpoint+ config.default_settings.fp8_storage = False+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda device: device.index == 0)+ monkeypatch.setattr(load_default, "_device_supports_fp8_storage", lambda *_args: False)+ monkeypatch.setattr(load_default.TorchDevice, "choose_bfloat16_safe_dtype", lambda _device: torch.float32)+ capable, incapable = _loader([]), _loader([])+ capable._torch_device, incapable._torch_device = torch.device("cuda:0"), torch.device("cuda:1")++ capable_key = capable._get_cache_key(config, SubModelType.Transformer)+ incapable_key = incapable._get_cache_key(config, SubModelType.Transformer)+ assert capable_key != incapable_key+ # Probe changes after lookup cannot change the weights constructed under either key.+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda device: device.index == 1)+ packed = capable._load_from_singlefile(config).get_submodule("blocks.0.attn1.to_q")+ folded = incapable._load_from_singlefile(config).get_submodule("blocks.0.attn1.to_q")++ assert packed.weight.dtype is torch.float8_e4m3fn+ assert packed.weight_scale.item() == SCALE+ assert folded.weight.dtype is torch.float32+ torch.testing.assert_close(folded.weight, packed.weight.float() * SCALE)++class TestTheDiffusersLoader:def test_a_diffusers_folder_reaches_the_cast(self, tmp_path: Path) -> None:"""`WanDiffusersModel` overrides `_load_model` to force bfloat16, and in doing so replaced the@@ -163,6 +197,8 @@ class TestTheDiffusersLoader:there to be found in the parent's source."""cast_calls: list = []loader = object.__new__(WanDiffusersModel)+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.float32loader._apply_fp8_layerwise_casting = lambda model, config, submodel: (cast_calls.append((config, submodel)),model,diff --git a/tests/backend/model_manager/load/test_wan_loader.py b/tests/backend/model_manager/load/test_wan_loader.pyindex 0606651b1f..6900831723 100644--- a/tests/backend/model_manager/load/test_wan_loader.py+++ b/tests/backend/model_manager/load/test_wan_loader.py@@ -436,6 +436,7 @@ class TestDiffusersFolderLoad:return modelloader = object.__new__(WanDiffusersModel)+ loader._torch_device = torch.device("cpu")loader.get_hf_load_class = lambda *_args, **_kwargs: Recordedloader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: modelreturn loader._load_model(config, SubModelType.Transformer), as_loadeddiff --git a/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.py b/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.pyindex a719f9f9b3..0e277d498a 100644--- a/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.py+++ b/tests/backend/qwen2_5_vl/test_qwen2_5_vl_tokenizer.py@@ -8,6 +8,8 @@ whose ``tokenizer/`` lost its vocabulary — vendoring cannot repair somebody elimport jsonfrom pathlib import Path+import torch+from invokeai.backend.qwen2_5_vl.qwen2_5_vl_assets import (load_bundled_qwen2_5_vl_tokenizer,tokenizer_can_encode,@@ -123,6 +125,8 @@ def test_the_diffusers_main_loader_serves_a_usable_tokenizer(tmp_path: Path) ->)loader = object.__new__(QwenImageDiffusersModel)+ loader._torch_device = torch.device("cpu")+ loader._torch_dtype = torch.float32config = Main_Diffusers_QwenImage_Config.model_construct(path=str(tmp_path), name="qwen-image", repo_variant=None)tokenizer = loader._load_model(config, SubModelType.Tokenizer)diff --git a/tests/backend/qwen3_5/test_qwen3_5_loading.py b/tests/backend/qwen3_5/test_qwen3_5_loading.pyindex 5e59912ac8..8502dcba1b 100644--- a/tests/backend/qwen3_5/test_qwen3_5_loading.py+++ b/tests/backend/qwen3_5/test_qwen3_5_loading.py@@ -18,6 +18,8 @@ from transformers.models.qwen3_5.configuration_qwen3_5 import Qwen3_5TextConfigfrom invokeai.backend.model_manager.configs.qwen3_5_encoder import Qwen35Encoder_Checkpoint_Configfrom invokeai.backend.model_manager.configs.roles import view_as+from invokeai.backend.model_manager.load import load_default+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCachefrom invokeai.backend.model_manager.load.model_loaders import qwen3_5_encoder as loader_modulefrom invokeai.backend.model_manager.load.model_loaders.qwen3_5_encoder import (Qwen35EncoderCheckpointLoader,@@ -87,6 +89,7 @@ def loader(monkeypatch: pytest.MonkeyPatch) -> Qwen35EncoderCheckpointLoader:loader = object.__new__(Qwen35EncoderCheckpointLoader)loader._ram_cache = MagicMock()loader._logger = logging.getLogger(__name__)+ loader._torch_device = torch.device("cpu")return loader@@ -239,6 +242,53 @@ def test_a_text_llm_record_viewed_as_the_encoder_loads_the_same_language_model_a_assert_loaded(from_native, weights)+def test_a_role_view_caches_each_storage_variant_under_its_record(+ tmp_path: Path, loader: Qwen35EncoderCheckpointLoader, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr("invokeai.backend.qwen3_5.qwen3_5_encoder.qwen3_5_text_config", lambda _variant: _config())+ monkeypatch.setattr(load_default, "should_keep_fp8_weights", lambda device: device.type == "cuda")+ monkeypatch.setattr(+ loader_module.TorchDevice,+ "choose_bfloat16_safe_dtype",+ staticmethod(lambda device: torch.bfloat16 if device.type == "cuda" else torch.float32),+ )+ projection = "layers.0.mlp.gate_proj.weight"+ weights = _reference(final_norm=True).state_dict()+ weights[projection] = weights[projection].to(torch.float8_e4m3fn)+ path = tmp_path / "whole.safetensors"+ save_file({f"{_PREFIX}{key}": tensor for key, tensor in weights.items()}, path)+ key = "aaaaaaaa-1111-2222-3333-444444444444"+ record = text_llm_file(key).model_copy(update={"path": str(path)})+ encoder = view_as(record, ModelType.Qwen35Encoder)+ loader._app_config = MagicMock(log_memory_usage=False, models_path=tmp_path)+ cache = ModelCache(+ execution_device_working_mem_gb=1.0,+ enable_partial_loading=False,+ keep_ram_copy_of_weights=True,+ execution_device="cpu",+ storage_device="cpu",+ logger=loader._logger,+ )+ loader._ram_cache = cache+ try:+ folded = loader.load_model(encoder, SubModelType.TextEncoder)+ # Only the capability decision uses the simulated device. Model buffers stay on CPU.+ loader._torch_device = torch.device("cuda:0")+ packed = loader.load_model(encoder, SubModelType.TextEncoder)++ with folded.model_in_ram() as model:+ assert model.state_dict()[projection].dtype is torch.float32+ with packed.model_in_ram() as model:+ assert model.state_dict()[projection].dtype is torch.float8_e4m3fn+ assert model.state_dict()["embed_tokens.weight"].dtype is torch.bfloat16+ assert folded._cache_record.key == f"{key}:text_encoder:as_qwen3_5_encoder:storage=full-float32"+ assert packed._cache_record.key == f"{key}:text_encoder:as_qwen3_5_encoder:storage=fp8-bfloat16"+ assert cache.cached_model_keys() == {key}+ assert cache.drop_model(key) == 2+ finally:+ cache.shutdown()++# -- ComfyUI's int8_tensorwise build: the whole vision-language model, of which the encoder reads the language model. --_PREFIX = "model.language_model."