Skip to content

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.

feat: add per-model FP8 layerwise casting for VRAM reduction (#8945)

Alexander Eichhorn6f42ad0ee78f
diff --git a/docs/src/content/docs/configuration/fp8-storage.mdx b/docs/src/content/docs/configuration/fp8-storage.mdx
new file mode 100644
index 0000000000..8ced984ac9
--- /dev/null
+++ b/docs/src/content/docs/configuration/fp8-storage.mdx
@@ -0,0 +1,89 @@
+---
+title: FP8 Storage
+sidebar:
+ order: 3
+---
+
+import { Steps } from '@astrojs/starlight/components';
+
+FP8 Storage cuts a model's VRAM footprint roughly in half by keeping weights on the GPU in 8-bit floating-point format (`float8_e4m3fn`). During inference, each layer's weights are cast on-the-fly back up to the compute precision (FP16/BF16), then cast back to FP8 after the forward pass — so quality is largely preserved.
+
+It pairs well with [Low-VRAM mode](/configuration/low-vram-mode/): low-VRAM mode streams layers between RAM and VRAM, while FP8 Storage shrinks the layers themselves.
+
+## Requirements
+
+- **Nvidia GPU on Windows or Linux.** FP8 Storage uses CUDA tensor types and is silently disabled on CPU and MPS.
+- **CUDA 12.x and recent PyTorch.** The `float8_e4m3fn` dtype was added in PyTorch 2.1 — InvokeAI's bundled versions satisfy this.
+
+There is no hardware requirement for FP8 *compute* — InvokeAI casts back to FP16/BF16 for math. This means FP8 Storage works on GPUs that do not natively support FP8 matmul (e.g. RTX 30-series), at a small per-step throughput cost.
+
+## Enabling FP8 Storage
+
+FP8 Storage is a **per-model setting**, configured from the Model Manager:
+
+<Steps>
+1. Open the **Model Manager**.
+2. Select a model (Main, ControlNet, or T2I-Adapter).
+3. Under **Default Settings**, toggle **FP8 Storage (Save VRAM)**.
+4. Click **Save**.
+</Steps>
+
+The setting takes effect on the next load. If the model is already in the cache, InvokeAI evicts the cached copy automatically so the new setting applies — even if a generation is currently using the model (the eviction is deferred until the generation finishes).
+
+:::tip[When to enable]
+ Enable FP8 Storage on large models that don't fit comfortably in VRAM — FLUX dev/Klein, large SDXL checkpoints, ControlNet-XL adapters. For smaller SD1 / SD2 models, the savings are negligible and not worth the small precision trade-off.
+:::
+
+## What FP8 Storage applies to
+
+FP8 Storage is **only** applied to layers where the precision trade-off is acceptable:
+
+| Model type | FP8 applied? |
+| ----------------------------- | -------------------------------------- |
+| Main models (SD1, SD2, SDXL) | Yes |
+| FLUX.1 / FLUX.2 Klein | Yes |
+| ControlNet, T2I-Adapter | Yes |
+| VAE | No — visible decode-quality regression |
+| Text encoders, tokenizers | No — small models, no benefit |
+| Z-Image (any variant) | No — dtype mismatch with skipped layers|
+| LoRA, ControlLoRA | No — patched into base, not run alone |
+
+Within a supported model, **norm layers, position/patch embeddings, and `proj_in`/`proj_out` are skipped** so precision-sensitive tiny learned scalars (e.g. FLUX `RMSNorm.scale`) aren't crushed to FP8. This mirrors the diffusers default skip list.
+
+## Quality trade-offs
+
+FP8 Storage is **near-lossless** for most workloads because:
+
+- Norms and embeddings (the precision-sensitive layers) are skipped.
+- The actual matmul still happens in FP16/BF16 — FP8 is only the on-GPU storage format.
+
+That said, some artifacts have been reported on:
+
+- **VAEs** — never cast (the toggle has no effect on VAE submodels).
+- **Heavy LoRA stacks** — patching is unaffected, but very precision-sensitive LoRAs may show slight drift. Compare a side-by-side if your workflow depends on subtle LoRA behavior.
+
+If you see unexpected quality regressions, disable FP8 Storage on the affected model and re-run.
+
+## Combining with Low-VRAM mode and quantized models
+
+- **FP8 + partial loading**: fully supported. FP8 Storage shrinks the layers; partial loading streams them between RAM and VRAM as needed. Use both on tight VRAM budgets.
+- **FP8 + GGUF / NF4 / int8 quantized checkpoints**: these formats already have their own storage precision. FP8 Storage is not applied on top — the toggle is silently a no-op for quantized formats, since the loader returns a different module type.
+
+## Troubleshooting
+
+### "I toggled FP8 Storage but VRAM usage didn't change"
+
+The cache eviction is immediate for idle models, but **deferred until the next unlock** if the model is mid-generation. Wait for the current generation to finish, then start a new one — the next load will use the new setting.
+
+If VRAM still hasn't dropped:
+
+- Check the InvokeAI log for `FP8 layerwise casting enabled for <model name>`. If the line isn't there, the model is on the exclusion list (VAE, text encoder, Z-Image, LoRA — see table above).
+- Confirm you are on CUDA. FP8 Storage is silently disabled on CPU and MPS.
+
+### Quality regression on a specific model
+
+Disable FP8 Storage for that model in Model Manager and reload. If quality is restored, the model has FP8-sensitive layers that fall outside the default skip list. Please open an issue with the model name and a side-by-side comparison.
+
+### "RuntimeError: ... float8_e4m3fn ..."
+
+You're on a PyTorch version that predates FP8 support. Reinstall InvokeAI using the official launcher — the bundled torch version supports FP8.
diff --git a/invokeai/app/api/routers/model_manager.py b/invokeai/app/api/routers/model_manager.py
index 40d4f48b63..bdd2e40644 100644
--- a/invokeai/app/api/routers/model_manager.py
+++ b/invokeai/app/api/routers/model_manager.py
@@ -437,7 +437,17 @@ async def update_model_record(
logger = ApiDependencies.invoker.services.logger
record_store = ApiDependencies.invoker.services.model_manager.store
try:
+ previous_config = record_store.get_model(key)
config = record_store.update_model(key, changes=changes, allow_class_change=True)
+ # Settings that change how the model loads (e.g. fp8_storage, cpu_only) are baked into the cached
+ # nn.Module at load time, so toggling them on a cached model is otherwise silently a no-op until
+ # the entry is evicted. Drop any unlocked cached entries for this model so the next load rebuilds.
+ if _load_settings_changed(previous_config, config):
+ dropped = ApiDependencies.invoker.services.model_manager.load.ram_cache.drop_model(key)
+ if dropped:
+ logger.info(
+ f"Dropped {dropped} cached entr{'y' if dropped == 1 else 'ies'} for model {key} after settings change."
+ )
config = prepare_model_config_for_response(config, ApiDependencies)
logger.info(f"Updated model: {key}")
except UnknownModelException as e:
@@ -448,6 +458,26 @@ async def update_model_record(
return config
+_LOAD_AFFECTING_SETTINGS: tuple[str, ...] = ("fp8_storage", "cpu_only")
+
+
+def _load_settings_changed(previous: AnyModelConfig, updated: AnyModelConfig) -> bool:
+ """Return True if any setting that influences how the model is loaded changed.
+
+ Such settings are read by the loader during `_load_model` and baked into the resulting
+ nn.Module, so a cached entry built under the old value must be evicted for the change
+ to take effect.
+ """
+ if getattr(previous, "cpu_only", None) != getattr(updated, "cpu_only", None):
+ return True
+ previous_settings = getattr(previous, "default_settings", None)
+ updated_settings = getattr(updated, "default_settings", None)
+ for field in _LOAD_AFFECTING_SETTINGS:
+ if getattr(previous_settings, field, None) != getattr(updated_settings, field, None):
+ return True
+ return False
+
+
@model_manager_router.get(
"/i/{key}/image",
operation_id="get_model_image",
diff --git a/invokeai/backend/model_manager/configs/controlnet.py b/invokeai/backend/model_manager/configs/controlnet.py
index 6688ec95ff..1c73df4120 100644
--- a/invokeai/backend/model_manager/configs/controlnet.py
+++ b/invokeai/backend/model_manager/configs/controlnet.py
@@ -54,6 +54,10 @@ MODEL_NAME_TO_PREPROCESSOR = {
class ControlAdapterDefaultSettings(BaseModel):
# This could be narrowed to controlnet processor nodes, but they change. Leaving this a string is safer.
preprocessor: str | None
+ fp8_storage: bool | None = Field(
+ default=None,
+ description="Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference.",
+ )
model_config = ConfigDict(extra="forbid")
@classmethod
diff --git a/invokeai/backend/model_manager/configs/main.py b/invokeai/backend/model_manager/configs/main.py
index 2d002d68dc..e1e408a348 100644
--- a/invokeai/backend/model_manager/configs/main.py
+++ b/invokeai/backend/model_manager/configs/main.py
@@ -52,6 +52,10 @@ class MainModelDefaultSettings(BaseModel):
height: int | None = Field(default=None, multiple_of=8, ge=64, description="Default height for this model")
guidance: float | None = Field(default=None, ge=1, description="Default Guidance for this model")
cpu_only: bool | None = Field(default=None, description="Whether this model should run on CPU only")
+ fp8_storage: bool | None = Field(
+ default=None,
+ description="Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference.",
+ )
model_config = ConfigDict(extra="forbid")
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index ea69920734..542a6774d5 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -1,6 +1,7 @@
# Copyright (c) 2024, Lincoln D. Stein and the InvokeAI Development Team
"""Default implementation of model loading in InvokeAI."""
+import re
from logging import Logger
from pathlib import Path
from typing import Optional
@@ -21,6 +22,35 @@ from invokeai.backend.model_manager.taxonomy import (
)
from invokeai.backend.util.devices import TorchDevice
+# Layer classes that benefit from FP8 storage. Mirrors diffusers'
+# `_GO_LC_SUPPORTED_PYTORCH_LAYERS` so the plain-nn.Module fallback path makes the same
+# precision/quality trade-offs as the ModelMixin path. Notably excludes norm and embedding
+# wrapper modules — those are handled by their direct param types (Embedding is included
+# but pos_embed/patch_embed are filtered by `_FP8_DEFAULT_SKIP_PATTERNS`).
+_FP8_SUPPORTED_PYTORCH_LAYERS: tuple[type[torch.nn.Module], ...] = (
+ torch.nn.Linear,
+ torch.nn.Conv1d,
+ torch.nn.Conv2d,
+ torch.nn.Conv3d,
+ torch.nn.ConvTranspose1d,
+ torch.nn.ConvTranspose2d,
+ torch.nn.ConvTranspose3d,
+ torch.nn.Embedding,
+)
+
+# Module-path regexes (matched against `named_modules()` dotted paths) for precision-sensitive
+# layers that should never be cast to FP8. Mirrors diffusers' `DEFAULT_SKIP_MODULES_PATTERN`
+# — without these, FLUX RMSNorm.scale and similar tiny learned scalars get crushed to FP8 and
+# inference quality degrades. Includes anything named `norm`, position/patch embeddings, and
+# the in/out projection of transformer blocks.
+_FP8_DEFAULT_SKIP_PATTERNS: tuple[str, ...] = (
+ "pos_embed",
+ "patch_embed",
+ "norm",
+ r"^proj_in$",
+ r"^proj_out$",
+)
+
# TO DO: The loader is not thread safe!
class ModelLoader(ModelLoaderBase):
@@ -124,6 +154,151 @@ class ModelLoader(ModelLoaderBase):
variant=config.repo_variant if isinstance(config, Diffusers_Config_Base) else None,
)
+ def _should_use_fp8(self, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None) -> bool:
+ """Check if FP8 layerwise casting should be applied to a model."""
+ # FP8 storage only works on CUDA
+ if self._torch_device.type != "cuda":
+ return False
+
+ # Z-Image has dtype mismatch issues with diffusers' layerwise casting
+ # (skipped modules produce bf16, hooked modules expect fp16).
+ from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+
+ if hasattr(config, "base") and config.base == BaseModelType.ZImage:
+ return False
+
+ # VAEs are excluded — fp8 storage causes noticeable quality degradation in decode.
+ if hasattr(config, "type") and config.type == ModelType.VAE:
+ return False
+
+ # LoRAs (including ControlLoRA) are excluded — they are not run as a standalone forward pass,
+ # they are patched into a base model, so the layerwise-casting hooks would never fire. The
+ # toggle is also hidden in the UI for ControlLoRA; this guard handles legacy persisted values.
+ if hasattr(config, "type") and config.type in (ModelType.LoRA, ModelType.ControlLoRa):
+ return False
+
+ # Don't apply FP8 to text encoders, tokenizers, schedulers, VAEs, etc.
+ _excluded_submodel_types = {
+ SubModelType.TextEncoder,
+ SubModelType.TextEncoder2,
+ SubModelType.TextEncoder3,
+ SubModelType.Tokenizer,
+ SubModelType.Tokenizer2,
+ SubModelType.Tokenizer3,
+ SubModelType.Scheduler,
+ SubModelType.SafetyChecker,
+ SubModelType.VAE,
+ SubModelType.VAEDecoder,
+ SubModelType.VAEEncoder,
+ }
+ if submodel_type in _excluded_submodel_types:
+ return False
+
+ # Check default_settings.fp8_storage (Main models, ControlNet)
+ if hasattr(config, "default_settings") and config.default_settings is not None:
+ if hasattr(config.default_settings, "fp8_storage") and config.default_settings.fp8_storage is True:
+ return True
+
+ return False
+
+ def _apply_fp8_layerwise_casting(
+ self, model: AnyModel, config: AnyModelConfig, submodel_type: Optional[SubModelType] = None
+ ) -> AnyModel:
+ """Apply FP8 layerwise casting to a model if enabled in its config."""
+ if not self._should_use_fp8(config, submodel_type):
+ return model
+
+ storage_dtype = torch.float8_e4m3fn
+ compute_dtype = self._torch_dtype
+
+ # Detect the model's current dtype to use as compute dtype, since models
+ # (e.g. Flux) may require a specific dtype (bf16) that differs from the global torch dtype (fp16).
+ if isinstance(model, torch.nn.Module):
+ first_param = next(model.parameters(), None)
+ if first_param is not None:
+ compute_dtype = first_param.dtype
+
+ from diffusers.models.modeling_utils import ModelMixin
+
+ if isinstance(model, ModelMixin):
+ model.enable_layerwise_casting(
+ storage_dtype=storage_dtype,
+ compute_dtype=compute_dtype,
+ )
+ elif isinstance(model, torch.nn.Module):
+ self._apply_fp8_to_nn_module(model, storage_dtype=storage_dtype, compute_dtype=compute_dtype)
+ else:
+ return model
+
+ param_bytes = sum(p.nelement() * p.element_size() for p in model.parameters())
+ self._logger.info(
+ f"FP8 layerwise casting enabled for {config.name} "
+ f"(storage=float8_e4m3fn, compute={compute_dtype}, "
+ f"param_size={param_bytes / (1024**2):.0f}MB)"
+ )
+ return model
+
+ @staticmethod
+ def _apply_fp8_to_nn_module(model: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtype) -> None:
+ """Apply FP8 layerwise casting to a plain nn.Module.
+
+ Mirrors diffusers' `apply_layerwise_casting` semantics: only the layer classes in
+ `_FP8_SUPPORTED_PYTORCH_LAYERS` are cast, and modules whose dotted path matches any of
+ `_FP8_DEFAULT_SKIP_PATTERNS` (norm, pos_embed, patch_embed, proj_in/out) are skipped.
+ Without the skip list, precision-sensitive tiny learned scalars (e.g. FLUX RMSNorm.scale)
+ get crushed to FP8 and quality degrades noticeably.
+ """
+ for module_name, module in model.named_modules():
+ if not isinstance(module, _FP8_SUPPORTED_PYTORCH_LAYERS):
+ continue
+ if any(re.search(pattern, module_name) for pattern in _FP8_DEFAULT_SKIP_PATTERNS):
+ continue
+ params = list(module.parameters(recurse=False))
+ if not params:
+ continue
+
+ for param in params:
+ param.data = param.data.to(storage_dtype)
+
+ ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)
+
+ @staticmethod
+ def _wrap_forward_with_fp8_cast(
+ module: torch.nn.Module, storage_dtype: torch.dtype, compute_dtype: torch.dtype
+ ) -> None:
+ """Register pre/post forward hooks that cast params to compute dtype on entry and back
+ to storage dtype on exit.
+
+ We use hooks (rather than overriding `module.forward`) for two reasons:
+
+ 1. **Correct dispatch after `apply_custom_layers_to_model`.** `ModelCache.put()` calls
+ `apply_custom_layers_to_model`, which creates a NEW `CustomLinear` instance and
+ shares the original `Linear.__dict__` (see `wrap_custom_layer`). Anything stored in
+ that dict — including an instance-level `forward` attribute — gets carried over to
+ the new object. An overridden `forward` would close over the OLD instance, so calls
+ to the new `CustomLinear` would silently route to `Linear.forward(old_instance, ...)`
+ and bypass the LoRA-patch-aware branch in `CustomLinear.forward`. Hooks, by contrast,
+ live in `_forward_hooks` / `_forward_pre_hooks` and are dispatched by
+ `nn.Module.__call__` with the *actual* called instance — so they run on the new
+ `CustomLinear` and the class's `forward` is still resolved normally.
+
+ 2. **Exception safety.** `register_forward_hook(..., always_call=True)` fires the
+ post-hook even when `forward` raises. The plain pre-hook/post-hook pair without
+ `always_call` would leave params in compute dtype on exception, defeating FP8
+ storage savings and making cache size accounting stale.
+ """
+
+ def pre_hook(mod: torch.nn.Module, _args: object) -> None:
+ for p in mod.parameters(recurse=False):
+ p.data = p.data.to(compute_dtype)
+
+ def post_hook(mod: torch.nn.Module, _args: object, _output: object) -> None:
+ for p in mod.parameters(recurse=False):
+ p.data = p.data.to(storage_dtype)
+
+ module.register_forward_pre_hook(pre_hook)
+ module.register_forward_hook(post_hook, always_call=True)
+
# This needs to be implemented in the subclass
def _load_model(
self,
diff --git a/invokeai/backend/model_manager/load/model_cache/cache_record.py b/invokeai/backend/model_manager/load/model_cache/cache_record.py
index c48435d0ef..5b4880a177 100644
--- a/invokeai/backend/model_manager/load/model_cache/cache_record.py
+++ b/invokeai/backend/model_manager/load/model_cache/cache_record.py
@@ -17,6 +17,11 @@ class CacheRecord:
# Model in memory.
cached_model: CachedModelWithPartialLoad | CachedModelOnlyFullLoad
_locks: int = 0
+ # Set by ModelCache.drop_model() when the entry was locked at invalidation time.
+ # ModelCache.unlock() evicts the entry as soon as the last lock releases so a setting
+ # change (e.g. fp8_storage toggled during an in-flight generation) takes effect on the
+ # next load instead of silently being ignored.
+ is_stale: bool = False
def lock(self) -> None:
"""Lock this record."""
diff --git a/invokeai/backend/model_manager/load/model_cache/model_cache.py b/invokeai/backend/model_manager/load/model_cache/model_cache.py
index 022439331c..e3a0928e52 100644
--- a/invokeai/backend/model_manager/load/model_cache/model_cache.py
+++ b/invokeai/backend/model_manager/load/model_cache/model_cache.py
@@ -477,6 +477,26 @@ class ModelCache:
f"Unlocked model {cache_entry.key} (Type: {cache_entry.cached_model.model.__class__.__name__})"
)
+ # If `drop_model()` marked this entry stale (e.g. settings changed while a generation
+ # was using it), evict now so the next load rebuilds with the new settings rather than
+ # silently reusing the pre-change cached module.
+ if cache_entry.is_stale and not cache_entry.is_locked and cache_entry.key in self._cached_models:
+ bytes_freed = cache_entry.cached_model.total_bytes()
+ self._delete_cache_entry(cache_entry)
+ if self.stats:
+ self.stats.cleared = (self.stats.cleared or 0) + 1
+ snapshot = self._get_cache_snapshot()
+ for cb in self._on_cache_models_cleared_callbacks:
+ cb(
+ models_cleared=1,
+ bytes_requested=0,
+ bytes_freed=bytes_freed,
+ cache_snapshot=snapshot,
+ )
+ gc.collect()
+ TorchDevice.empty_cache()
+ self._logger.debug(f"Evicted stale cache entry {cache_entry.key} after unlock.")
+
def _load_locked_model(self, cache_entry: CacheRecord, working_mem_bytes: Optional[int] = None) -> None:
"""Helper function for self.lock(). Loads a locked model into VRAM."""
start_time = time.time()
@@ -866,3 +886,46 @@ class ModelCache:
"""Delete cache_entry from the cache if it exists. No exception is thrown if it doesn't exist."""
self._cache_stack = [key for key in self._cache_stack if key != cache_entry.key]
self._cached_models.pop(cache_entry.key, None)
+
+ @synchronized
+ 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`),
+ so a single model may have multiple entries. Locked entries are marked `is_stale` and
+ evicted by `unlock()` as soon as the last lock releases — without that, a setting
+ toggled during an in-flight generation would survive on the locked entry and quietly
+ get reused by the next generation.
+
+ Returns the number of entries immediately dropped (locked entries that are only marked
+ stale do not count).
+ """
+ prefix = f"{model_key}:"
+ matching: list[CacheRecord] = [
+ entry for key, entry in self._cached_models.items() if key == model_key or key.startswith(prefix)
+ ]
+
+ dropped: list[CacheRecord] = []
+ bytes_freed = 0
+ for entry in matching:
+ if entry.is_locked:
+ entry.is_stale = True
+ continue
+ bytes_freed += entry.cached_model.total_bytes()
+ self._delete_cache_entry(entry)
+ dropped.append(entry)
+
+ if dropped:
+ if self.stats:
+ self.stats.cleared = len(dropped)
+ snapshot = self._get_cache_snapshot()
+ for cb in self._on_cache_models_cleared_callbacks:
+ cb(
+ models_cleared=len(dropped),
+ bytes_requested=0,
+ bytes_freed=bytes_freed,
+ cache_snapshot=snapshot,
+ )
+ gc.collect()
+ TorchDevice.empty_cache()
+ return len(dropped)
diff --git a/invokeai/backend/model_manager/load/model_loaders/cogview4.py b/invokeai/backend/model_manager/load/model_loaders/cogview4.py
index ee8c6d4f41..6e8490912b 100644
--- a/invokeai/backend/model_manager/load/model_loaders/cogview4.py
+++ b/invokeai/backend/model_manager/load/model_loaders/cogview4.py
@@ -55,4 +55,5 @@ class CogView4DiffusersModel(GenericDiffusersLoader):
else:
raise e
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
diff --git a/invokeai/backend/model_manager/load/model_loaders/controlnet.py b/invokeai/backend/model_manager/load/model_loaders/controlnet.py
index 8fd1796b8f..e50e45849a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/controlnet.py
+++ b/invokeai/backend/model_manager/load/model_loaders/controlnet.py
@@ -45,9 +45,11 @@ class ControlNetLoader(GenericDiffusersLoader):
submodel_type: Optional[SubModelType] = None,
) -> AnyModel:
if isinstance(config, ControlNet_Checkpoint_Config_Base):
- return ControlNetModel.from_single_file(
+ result = ControlNetModel.from_single_file(
config.path,
torch_dtype=self._torch_dtype,
)
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
+ return result
else:
return super()._load_model(config, submodel_type)
diff --git a/invokeai/backend/model_manager/load/model_loaders/flux.py b/invokeai/backend/model_manager/load/model_loaders/flux.py
index c802154797..c385a5dd81 100644
--- a/invokeai/backend/model_manager/load/model_loaders/flux.py
+++ b/invokeai/backend/model_manager/load/model_loaders/flux.py
@@ -139,6 +139,7 @@ class Flux2VAEDiffusersLoader(ModelLoader):
local_files_only=True,
)
+ model = self._apply_fp8_layerwise_casting(model, config, submodel_type)
return model
@@ -232,6 +233,7 @@ class Flux2VAELoader(ModelLoader):
vae_dtype = self._torch_dtype
model.to(vae_dtype)
+ model = self._apply_fp8_layerwise_casting(model, config, submodel_type)
return model
def _convert_flux2_vae_bfl_to_diffusers(self, sd: dict) -> dict:
@@ -516,7 +518,9 @@ class FluxCheckpointModel(ModelLoader):
match submodel_type:
case SubModelType.Transformer:
- return self._load_from_singlefile(config)
+ model = self._load_from_singlefile(config)
+ model = self._apply_fp8_layerwise_casting(model, config, submodel_type)
+ return model
raise ValueError(
f"Only Transformer submodels are currently supported. Received: {submodel_type.value if submodel_type else 'None'}"
@@ -670,6 +674,7 @@ class FluxDiffusersModel(GenericDiffusersLoader):
else:
raise e
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
@@ -746,6 +751,7 @@ class Flux2DiffusersModel(GenericDiffusersLoader):
if guidance_emb.linear_2.bias is not None:
guidance_emb.linear_2.bias.data.zero_()
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
@@ -763,7 +769,9 @@ class Flux2CheckpointModel(ModelLoader):
match submodel_type:
case SubModelType.Transformer:
- return self._load_from_singlefile(config)
+ model = self._load_from_singlefile(config)
+ model = self._apply_fp8_layerwise_casting(model, config, submodel_type)
+ return model
raise ValueError(
f"Only Transformer submodels are currently supported. Received: {submodel_type.value if submodel_type else 'None'}"
diff --git a/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py b/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py
index 2a79f604ba..7e87869c9e 100644
--- a/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py
+++ b/invokeai/backend/model_manager/load/model_loaders/generic_diffusers.py
@@ -47,6 +47,7 @@ class GenericDiffusersLoader(ModelLoader):
result = model_class.from_pretrained(model_path, torch_dtype=self._torch_dtype, local_files_only=True)
else:
raise e
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
# TO DO: Add exception handling
diff --git a/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py b/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py
index 0e11cd4191..d19d647762 100644
--- a/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py
+++ b/invokeai/backend/model_manager/load/model_loaders/stable_diffusion.py
@@ -90,6 +90,7 @@ class StableDiffusionDiffusersModel(GenericDiffusersLoader):
else:
raise e
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
def _load_from_singlefile(
@@ -152,5 +153,8 @@ class StableDiffusionDiffusersModel(GenericDiffusersLoader):
if subtype == submodel_type:
continue
if submodel := getattr(pipeline, subtype.value, None):
+ self._apply_fp8_layerwise_casting(submodel, config, subtype)
self._ram_cache.put(get_model_cache_key(config.key, subtype), model=submodel)
- return getattr(pipeline, submodel_type.value)
+ result = getattr(pipeline, submodel_type.value)
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
+ return result
diff --git a/invokeai/backend/model_manager/load/model_loaders/z_image.py b/invokeai/backend/model_manager/load/model_loaders/z_image.py
index c381e02718..6c2102933a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/z_image.py
+++ b/invokeai/backend/model_manager/load/model_loaders/z_image.py
@@ -163,6 +163,7 @@ class ZImageDiffusersModel(GenericDiffusersLoader):
else:
raise e
+ result = self._apply_fp8_layerwise_casting(result, config, submodel_type)
return result
diff --git a/invokeai/frontend/web/public/locales/en.json b/invokeai/frontend/web/public/locales/en.json
index 70bc0571f1..d99bb04a63 100644
--- a/invokeai/frontend/web/public/locales/en.json
+++ b/invokeai/frontend/web/public/locales/en.json
@@ -1126,6 +1126,7 @@
"convertToDiffusersHelpText5": "Please make sure you have enough disk space. Models generally vary between 2GB-7GB in size.",
"convertToDiffusersHelpText6": "Do you wish to convert this model?",
"cpuOnly": "CPU Only",
+ "fp8Storage": "FP8 Storage (Save VRAM)",
"runOnCpu": "Run text encoder model on CPU only",
"noDefaultSettings": "No default settings configured for this model. Visit the Model Manager to add default settings.",
"defaultSettings": "Default Settings",
@@ -2389,6 +2390,13 @@
"When enabled, only the text encoder component will run on CPU instead of GPU.",
"This saves VRAM for the denoiser while only slightly impacting performance. The conditioning outputs are automatically moved to GPU for the denoiser."
]
+ },
+ "fp8Storage": {
+ "heading": "FP8 Storage",
+ "paragraphs": [
+ "Stores model weights in FP8 format in VRAM, reducing memory usage by approximately 50% compared to FP16.",
+ "During inference, weights are cast layer-by-layer to the compute precision (FP16/BF16), so image quality is preserved. Works on all CUDA GPUs."
+ ]
}
},
"workflows": {
diff --git a/invokeai/frontend/web/src/common/components/InformationalPopover/constants.ts b/invokeai/frontend/web/src/common/components/InformationalPopover/constants.ts
index 95fa75cfa3..e9d855648a 100644
--- a/invokeai/frontend/web/src/common/components/InformationalPopover/constants.ts
+++ b/invokeai/frontend/web/src/common/components/InformationalPopover/constants.ts
@@ -77,7 +77,8 @@ export type Feature =
| 'tileOverlap'
| 'optimizedDenoising'
| 'fluxDevLicense'
- | 'cpuOnly';
+ | 'cpuOnly'
+ | 'fp8Storage';
export type PopoverData = PopoverProps & {
image?: string;
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/hooks/useControlAdapterModelDefaultSettings.ts b/invokeai/frontend/web/src/features/modelManagerV2/hooks/useControlAdapterModelDefaultSettings.ts
index 1f14c08ded..9ab49ca889 100644
--- a/invokeai/frontend/web/src/features/modelManagerV2/hooks/useControlAdapterModelDefaultSettings.ts
+++ b/invokeai/frontend/web/src/features/modelManagerV2/hooks/useControlAdapterModelDefaultSettings.ts
@@ -11,6 +11,10 @@ export const useControlAdapterModelDefaultSettings = (
isEnabled: !isNil(modelConfig?.default_settings?.preprocessor),
value: modelConfig?.default_settings?.preprocessor || 'none',
},
+ fp8Storage: {
+ isEnabled: !isNil(modelConfig?.default_settings?.fp8_storage),
+ value: modelConfig?.default_settings?.fp8_storage ?? false,
+ },
};
}, [modelConfig?.default_settings]);
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/hooks/useMainModelDefaultSettings.ts b/invokeai/frontend/web/src/features/modelManagerV2/hooks/useMainModelDefaultSettings.ts
index dfab2d251f..10b66b7a25 100644
--- a/invokeai/frontend/web/src/features/modelManagerV2/hooks/useMainModelDefaultSettings.ts
+++ b/invokeai/frontend/web/src/features/modelManagerV2/hooks/useMainModelDefaultSettings.ts
@@ -41,6 +41,10 @@ export const useMainModelDefaultSettings = (modelConfig: MainModelConfig) => {
isEnabled: !isNil(modelConfig?.default_settings?.guidance),
value: modelConfig?.default_settings?.guidance ?? 4,
},
+ fp8Storage: {
+ isEnabled: !isNil(modelConfig?.default_settings?.fp8_storage),
+ value: modelConfig?.default_settings?.fp8_storage ?? false,
+ },
};
}, [modelConfig]);
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/ControlAdapterModelDefaultSettings.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/ControlAdapterModelDefaultSettings.tsx
index a5e8f10a4b..0bb177ddbe 100644
--- a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/ControlAdapterModelDefaultSettings.tsx
+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/ControlAdapterModelDefaultSettings.tsx
@@ -1,6 +1,7 @@
import { Button, Flex, Heading, SimpleGrid } from '@invoke-ai/ui-library';
import { useControlAdapterModelDefaultSettings } from 'features/modelManagerV2/hooks/useControlAdapterModelDefaultSettings';
import { useIsModelManagerEnabled } from 'features/modelManagerV2/hooks/useIsModelManagerEnabled';
+import { DefaultFp8StorageControlAdapter } from 'features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/DefaultFp8StorageControlAdapter';
import { DefaultPreprocessor } from 'features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/DefaultPreprocessor';
import type { FormField } from 'features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings';
import { toast } from 'features/toast/toast';
@@ -14,6 +15,7 @@ import type { ControlLoRAModelConfig, ControlNetModelConfig, T2IAdapterModelConf
export type ControlAdapterModelDefaultSettingsFormData = {
preprocessor: FormField<string>;
+ fp8Storage: FormField<boolean>;
};
type Props = {
@@ -40,6 +42,7 @@ export const ControlAdapterModelDefaultSettings = memo(({ modelConfig }: Props)
(data) => {
const body = {
preprocessor: data.preprocessor.isEnabled ? data.preprocessor.value : null,
+ fp8_storage: data.fp8Storage.isEnabled ? data.fp8Storage.value : null,
};
updateModel({
@@ -88,6 +91,7 @@ export const ControlAdapterModelDefaultSettings = memo(({ modelConfig }: Props)
<SimpleGrid columns={2} gap={8}>
<DefaultPreprocessor control={control} name="preprocessor" />
+ {modelConfig.type !== 'control_lora' && <DefaultFp8StorageControlAdapter control={control} name="fp8Storage" />}
</SimpleGrid>
</>
);
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/DefaultFp8StorageControlAdapter.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/DefaultFp8StorageControlAdapter.tsx
new file mode 100644
index 0000000000..812d081c35
--- /dev/null
+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/ControlAdapterModelDefaultSettings/DefaultFp8StorageControlAdapter.tsx
@@ -0,0 +1,45 @@
+import { FormControl, FormLabel, Switch } from '@invoke-ai/ui-library';
+import { InformationalPopover } from 'common/components/InformationalPopover/InformationalPopover';
+import type { ChangeEvent } from 'react';
+import { memo, useCallback, useMemo } from 'react';
+import type { UseControllerProps } from 'react-hook-form';
+import { useController } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import type { ControlAdapterModelDefaultSettingsFormData } from './ControlAdapterModelDefaultSettings';
+
+type DefaultFp8StorageType = ControlAdapterModelDefaultSettingsFormData['fp8Storage'];
+
+export const DefaultFp8StorageControlAdapter = memo(
+ (props: UseControllerProps<ControlAdapterModelDefaultSettingsFormData>) => {
+ const { t } = useTranslation();
+ const { field } = useController(props);
+
+ const onChange = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ const updatedValue = {
+ ...(field.value as DefaultFp8StorageType),
+ value: e.target.checked,
+ isEnabled: e.target.checked,
+ };
+ field.onChange(updatedValue);
+ },
+ [field]
+ );
+
+ const value = useMemo(() => {
+ return (field.value as DefaultFp8StorageType).value;
+ }, [field.value]);
+
+ return (
+ <FormControl>
+ <InformationalPopover feature="fp8Storage">
+ <FormLabel>{t('modelManager.fp8Storage')}</FormLabel>
+ </InformationalPopover>
+ <Switch isChecked={value} onChange={onChange} />
+ </FormControl>
+ );
+ }
+);
+
+DefaultFp8StorageControlAdapter.displayName = 'DefaultFp8StorageControlAdapter';
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/DefaultFp8Storage.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/DefaultFp8Storage.tsx
new file mode 100644
index 0000000000..d860846766
--- /dev/null
+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/DefaultFp8Storage.tsx
@@ -0,0 +1,43 @@
+import { FormControl, FormLabel, Switch } from '@invoke-ai/ui-library';
+import { InformationalPopover } from 'common/components/InformationalPopover/InformationalPopover';
+import type { ChangeEvent } from 'react';
+import { memo, useCallback, useMemo } from 'react';
+import type { UseControllerProps } from 'react-hook-form';
+import { useController } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import type { MainModelDefaultSettingsFormData } from './MainModelDefaultSettings';
+
+type DefaultFp8StorageType = MainModelDefaultSettingsFormData['fp8Storage'];
+
+export const DefaultFp8Storage = memo((props: UseControllerProps<MainModelDefaultSettingsFormData>) => {
+ const { t } = useTranslation();
+ const { field } = useController(props);
+
+ const onChange = useCallback(
+ (e: ChangeEvent<HTMLInputElement>) => {
+ const updatedValue = {
+ ...(field.value as DefaultFp8StorageType),
+ value: e.target.checked,
+ isEnabled: e.target.checked,
+ };
+ field.onChange(updatedValue);
+ },
+ [field]
+ );
+
+ const value = useMemo(() => {
+ return (field.value as DefaultFp8StorageType).value;
+ }, [field.value]);
+
+ return (
+ <FormControl>
+ <InformationalPopover feature="fp8Storage">
+ <FormLabel>{t('modelManager.fp8Storage')}</FormLabel>
+ </InformationalPopover>
+ <Switch isChecked={value} onChange={onChange} />
+ </FormControl>
+ );
+});
+
+DefaultFp8Storage.displayName = 'DefaultFp8Storage';
diff --git a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx
index dd944897b2..b69bf117bc 100644
--- a/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx
+++ b/invokeai/frontend/web/src/features/modelManagerV2/subpanels/ModelPanel/MainModelDefaultSettings/MainModelDefaultSettings.tsx
@@ -18,6 +18,7 @@ import type { MainModelConfig } from 'services/api/types';
import { DefaultCfgRescaleMultiplier } from './DefaultCfgRescaleMultiplier';
import { DefaultCfgScale } from './DefaultCfgScale';
+import { DefaultFp8Storage } from './DefaultFp8Storage';
import { DefaultGuidance } from './DefaultGuidance';
import { DefaultScheduler } from './DefaultScheduler';
import { DefaultSteps } from './DefaultSteps';
@@ -39,6 +40,7 @@ export type MainModelDefaultSettingsFormData = {
width: FormField<number>;
height: FormField<number>;
guidance: FormField<number>;
+ fp8Storage: FormField<boolean>;
};
type Props = {
@@ -54,6 +56,10 @@ export const MainModelDefaultSettings = memo(({ modelConfig }: Props) => {
return ['flux', 'flux2'].includes(modelConfig.base);
}, [modelConfig]);
+ const isZImage = useMemo(() => {
+ return modelConfig.base === 'z-image';
+ }, [modelConfig]);
+
const defaultSettingsDefaults = useMainModelDefaultSettings(modelConfig);
const optimalDimension = useMemo(() => {
const modelBase = modelConfig?.base;
@@ -85,6 +91,7 @@ export const MainModelDefaultSettings = memo(({ modelConfig }: Props) => {
width: data.width.isEnabled ? data.width.value : null,
height: data.height.isEnabled ? data.height.value : null,
guidance: data.guidance.isEnabled ? data.guidance.value : null,
+ fp8_storage: data.fp8Storage.isEnabled ? data.fp8Storage.value : null,
};
updateModel({
@@ -141,6 +148,7 @@ export const MainModelDefaultSettings = memo(({ modelConfig }: Props) => {
{!isFluxFamily && <DefaultCfgRescaleMultiplier control={control} name="cfgRescaleMultiplier" />}
<DefaultWidth control={control} optimalDimension={optimalDimension} />
<DefaultHeight control={control} optimalDimension={optimalDimension} />
+ {!isZImage && <DefaultFp8Storage control={control} name="fp8Storage" />}
</SimpleGrid>
</>
);
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index 99b7c0ea91..68f24a26ec 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -6510,6 +6510,11 @@ export type components = {
ControlAdapterDefaultSettings: {
/** Preprocessor */
preprocessor: string | null;
+ /**
+ * Fp8 Storage
+ * @description Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference.
+ */
+ fp8_storage?: boolean | null;
};
/** ControlField */
ControlField: {
@@ -19492,6 +19497,11 @@ export type components = {
* @description Whether this model should run on CPU only
*/
cpu_only?: boolean | null;
+ /**
+ * Fp8 Storage
+ * @description Store weights in FP8 to reduce VRAM usage (~50% savings). Weights are cast to compute dtype during inference.
+ */
+ fp8_storage?: boolean | null;
};
/**
* Main Model - SD1.5, SD2
diff --git a/tests/app/routers/test_update_model_record_cache_invalidation.py b/tests/app/routers/test_update_model_record_cache_invalidation.py
new file mode 100644
index 0000000000..ba4961f094
--- /dev/null
+++ b/tests/app/routers/test_update_model_record_cache_invalidation.py
@@ -0,0 +1,53 @@
+"""Tests for `_load_settings_changed` — the predicate that decides whether to evict cached
+model entries after an `update_model_record` call. Settings like `fp8_storage` and `cpu_only`
+are baked into the loaded nn.Module at load time, so toggling them silently has no effect
+until the cached entry is evicted. The predicate must catch changes to those settings while
+ignoring changes that don't affect how the model loads (e.g. name, description).
+"""
+
+from types import SimpleNamespace
+
+from invokeai.app.api.routers.model_manager import _load_settings_changed
+
+
+def _config(*, fp8: bool | None = None, cpu_only: bool | None = None):
+ return SimpleNamespace(
+ cpu_only=cpu_only,
+ default_settings=SimpleNamespace(fp8_storage=fp8),
+ )
+
+
+def test_no_change_returns_false():
+ assert _load_settings_changed(_config(fp8=True), _config(fp8=True)) is False
+ assert _load_settings_changed(_config(fp8=None), _config(fp8=None)) is False
+
+
+def test_fp8_storage_toggle_returns_true():
+ """The primary motivating case: a user toggling FP8 storage in the Model Manager must
+ drop the cached entry, otherwise inference keeps using the old (non-FP8) module."""
+ assert _load_settings_changed(_config(fp8=False), _config(fp8=True)) is True
+ assert _load_settings_changed(_config(fp8=True), _config(fp8=False)) is True
+ assert _load_settings_changed(_config(fp8=None), _config(fp8=True)) is True
+ assert _load_settings_changed(_config(fp8=True), _config(fp8=None)) is True
+
+
+def test_cpu_only_toggle_returns_true():
+ """`cpu_only` is also read by the loader (in `_get_execution_device`) and baked into the
+ cache entry's execution device — toggling it after load is a silent no-op without eviction."""
+ assert _load_settings_changed(_config(cpu_only=False), _config(cpu_only=True)) is True
+ assert _load_settings_changed(_config(cpu_only=True), _config(cpu_only=None)) is True
+
+
+def test_missing_default_settings_is_handled():
+ """default_settings can legitimately be None (e.g. a freshly identified config)."""
+ no_settings = SimpleNamespace(cpu_only=None, default_settings=None)
+ assert _load_settings_changed(no_settings, no_settings) is False
+ assert _load_settings_changed(no_settings, _config(fp8=True)) is True
+
+
+def test_unrelated_field_does_not_trigger_invalidation():
+ """A config missing the fp8/cpu_only attributes entirely (e.g. a model type with no such
+ fields) must not falsely report a change."""
+ bare_a = SimpleNamespace()
+ bare_b = SimpleNamespace()
+ assert _load_settings_changed(bare_a, bare_b) is False
diff --git a/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py b/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py
new file mode 100644
index 0000000000..1a2ba34c01
--- /dev/null
+++ b/tests/backend/model_manager/load/model_cache/test_model_cache_drop_model.py
@@ -0,0 +1,224 @@
+"""Tests for `ModelCache.drop_model` — used by the model_manager API to invalidate cached
+entries when a setting that changes how a model loads (e.g. `fp8_storage`, `cpu_only`) is
+toggled. Without this, the toggle is silently a no-op until the entry is evicted by other
+means (clear cache, eviction under memory pressure, restart).
+
+Also covers:
+- Locked entries are marked stale and evicted by `unlock()` — without that, a setting toggled
+ during an in-flight generation would survive on the locked entry and silently be reused.
+- `stats.cleared` and the `cleared` callbacks fire on invalidation, mirroring the eviction
+ path through `_make_room_internal`, so observers and stats stay accurate.
+"""
+
+import logging
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.load.model_cache.cache_stats import CacheStats
+from invokeai.backend.model_manager.load.model_cache.model_cache import ModelCache
+
+
+def mock_logger():
+ logger = MagicMock()
+ logger.getEffectiveLevel.return_value = logging.INFO
+ return logger
+
+
+def cache(mock_logger):
+ 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=mock_logger,
+ )
+ yield cache
+ cache.shutdown()
+
+
+def test_drop_model_removes_all_submodel_entries(cache: ModelCache):
+ """A model with multiple submodels has multiple cache keys (`<key>` and `<key>:<submodel>`);
+ drop_model must drop them all together so the next load rebuilds with the new settings.
+ """
+ model_key = "abc123"
+ cache.put(model_key, torch.randn(4))
+ cache.put(f"{model_key}:unet", torch.randn(4))
+ cache.put(f"{model_key}:text_encoder", torch.randn(4))
+ cache.put("other_model", torch.randn(4))
+ cache.put("other_model:unet", torch.randn(4))
+
+ dropped = cache.drop_model(model_key)
+
+ assert dropped == 3
+ assert model_key not in cache._cached_models
+ assert f"{model_key}:unet" not in cache._cached_models
+ assert f"{model_key}:text_encoder" not in cache._cached_models
+ # Unrelated model is left alone.
+ assert "other_model" in cache._cached_models
+ assert "other_model:unet" in cache._cached_models
+
+
+def test_drop_model_marks_locked_entries_stale_without_evicting(cache: ModelCache):
+ """Locked entries are in active use; we must not yank them out from under inference.
+ But we also must not silently retain them after the lock releases — otherwise a setting
+ toggle that happened during inference would survive and the next generation would reuse
+ the pre-change cached module. drop_model marks locked entries `is_stale=True`; unlock
+ evicts them as soon as the last lock releases.
+ """
+ model_key = "abc123"
+ cache.put(model_key, torch.randn(4))
+ cache.put(f"{model_key}:unet", torch.randn(4))
+
+ locked_entry = cache._cached_models[f"{model_key}:unet"]
+ locked_entry.lock()
+
+ dropped = cache.drop_model(model_key)
+
+ assert dropped == 1
+ assert model_key not in cache._cached_models
+ assert f"{model_key}:unet" in cache._cached_models
+ assert locked_entry.is_stale is True
+
+
+def test_unlock_evicts_stale_entry(cache: ModelCache):
+ """The flip side of `marks_locked_entries_stale`: the next `unlock` after a stale-marking
+ invalidation must actually remove the entry.
+ """
+ model_key = "abc123"
+ cache.put(model_key, torch.randn(4))
+ entry = cache._cached_models[model_key]
+ entry.lock()
+
+ cache.drop_model(model_key)
+
+ # Entry still here while locked.
+ assert model_key in cache._cached_models
+ assert entry.is_stale is True
+
+ cache.unlock(entry)
+
+ assert model_key not in cache._cached_models
+
+
+def test_unlock_does_not_evict_non_stale_entry(cache: ModelCache):
+ """The stale-eviction path must not affect ordinary unlock — only stale-marked entries
+ should be evicted on unlock.
+ """
+ model_key = "abc123"
+ cache.put(model_key, torch.randn(4))
+ entry = cache._cached_models[model_key]
+ entry.lock()
+
+ cache.unlock(entry)
+
+ # No drop_model was called, so entry should still be there.
+ assert model_key in cache._cached_models
+
+
+def test_unlock_only_evicts_when_last_lock_releases(cache: ModelCache):
+ """If the entry is held by multiple locks (the cache supports re-entrant locking via
+ `_locks`), eviction must wait until they all release. Otherwise we'd yank the entry out
+ from under a caller that still expects it loaded.
+ """
+ model_key = "abc123"
+ cache.put(model_key, torch.randn(4))
+ entry = cache._cached_models[model_key]
+ entry.lock()
+ entry.lock()
+
+ cache.drop_model(model_key)
+ assert entry.is_stale is True
+
+ cache.unlock(entry)
+ # Still locked by one holder — must remain.
+ assert model_key in cache._cached_models
+
+ cache.unlock(entry)
+ # Now fully released — eviction happens.
+ assert model_key not in cache._cached_models
+
+
+def test_drop_model_updates_stats_and_fires_callbacks(cache: ModelCache):
+ """drop_model is a real eviction path — observers watching for cache changes (stats,
+ cleared callbacks) must see it just like the make_room eviction path. Otherwise the UI
+ cache-stats panel and any external observer would miss invalidations.
+ """
+ model_key = "abc123"
+ # Use real nn.Modules so `total_bytes()` is non-zero (raw tensors are sized as 0 by
+ # `calc_model_size_by_data` since the cache doesn't know what they are).
+ cache.put(model_key, torch.nn.Linear(4, 4))
+ cache.put(f"{model_key}:unet", torch.nn.Linear(4, 4))
+
+ cache.stats = CacheStats()
+ callback = MagicMock()
+ cache.on_cache_models_cleared(callback)
+
+ dropped = cache.drop_model(model_key)
+
+ assert dropped == 2
+ assert cache.stats.cleared == 2
+ callback.assert_called_once()
+ kwargs = callback.call_args.kwargs
+ assert kwargs["models_cleared"] == 2
+ assert kwargs["bytes_requested"] == 0 # not a make-room call
+ assert kwargs["bytes_freed"] > 0
+
+
+def test_unlock_stale_eviction_updates_stats_and_fires_callbacks(cache: ModelCache):
+ """Stale-entry eviction is also a cache change observers care about."""
+ model_key = "abc123"
+ cache.put(model_key, torch.randn(4))
+ entry = cache._cached_models[model_key]
+ entry.lock()
+
+ cache.drop_model(model_key)
+
+ cache.stats = CacheStats()
+ callback = MagicMock()
+ cache.on_cache_models_cleared(callback)
+
+ cache.unlock(entry)
+
+ assert model_key not in cache._cached_models
+ assert cache.stats.cleared == 1
+ callback.assert_called_once()
+
+
+def test_drop_model_with_no_matches_does_not_fire_callbacks(cache: ModelCache):
+ """No-op invalidations should be silent — don't spam observers with empty events."""
+ cache.put("other_model", torch.randn(4))
+ callback = MagicMock()
+ cache.on_cache_models_cleared(callback)
+
+ dropped = cache.drop_model("does_not_exist")
+
+ assert dropped == 0
+ callback.assert_not_called()
+
+
+def test_drop_model_with_no_matches_is_noop(cache: ModelCache):
+ cache.put("other_model", torch.randn(4))
+
+ dropped = cache.drop_model("does_not_exist")
+
+ assert dropped == 0
+ assert "other_model" in cache._cached_models
+
+
+def test_drop_model_does_not_match_prefix_substring(cache: ModelCache):
+ """`drop_model("abc")` must not drop `abcd` — only the exact key or `abc:<submodel>`."""
+ cache.put("abc", torch.randn(4))
+ cache.put("abcd", torch.randn(4))
+ cache.put("abc:unet", torch.randn(4))
+
+ dropped = cache.drop_model("abc")
+
+ assert dropped == 2
+ assert "abc" not in cache._cached_models
+ assert "abc:unet" not in cache._cached_models
+ assert "abcd" in cache._cached_models
diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.py
new file mode 100644
index 0000000000..4a4491c6a0
--- /dev/null
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -0,0 +1,325 @@
+"""Tests for `ModelLoader` FP8 helpers.
+
+Covers:
+- `_should_use_fp8` excludes ControlLoRA (the LoRA loader never runs the layerwise
+ casting helper, and a LoRA isn't a standalone forward module — so a persisted
+ `fp8_storage=true` must be a no-op).
+- `_wrap_forward_with_fp8_cast` uses pre/post hooks with `always_call=True`, so it is
+ exception-safe AND survives `apply_custom_layers_to_model`'s instance swap. Without
+ hooks, an instance-level `forward` override would be carried into the new CustomLinear
+ via the shared `__dict__` and silently bypass `CustomLinear.forward` — breaking LoRA
+ patch dispatch for FP8 checkpoint models.
+- `_apply_fp8_to_nn_module` skips precision-sensitive layers (norm, pos_embed, etc.)
+ so FLUX RMSNorm.scale and friends aren't crushed to FP8.
+"""
+
+from logging import getLogger
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+import torch
+
+from invokeai.backend.model_manager.load.load_default import ModelLoader
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.custom_modules.custom_linear import (
+ CustomLinear,
+)
+from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (
+ apply_custom_layers_to_model,
+)
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelType
+
+
+def _make_loader(device: str = "cuda") -> ModelLoader:
+ """Build a ModelLoader without going through dependency injection.
+
+ `_should_use_fp8` and `_wrap_forward_with_fp8_cast` only depend on `_torch_device`,
+ so we instantiate via __new__ and set the minimum state directly.
+ """
+ loader = ModelLoader.__new__(ModelLoader)
+ loader._torch_device = torch.device(device)
+ loader._torch_dtype = torch.float16
+ loader._logger = getLogger("test")
+ return loader
+
+
+def _make_config(model_type: ModelType, fp8: bool, base: BaseModelType = BaseModelType.Flux):
+ return SimpleNamespace(
+ type=model_type,
+ base=base,
+ name="test",
+ default_settings=SimpleNamespace(fp8_storage=fp8),
+ )
+
+
+def test_should_use_fp8_excludes_control_lora():
+ """ControlLoRA gets the FP8 toggle in the UI history but the LoRA loader never applies
+ layerwise casting (the model isn't run as a standalone forward pass — it patches into a
+ base model). The loader must silently ignore a persisted `fp8_storage=true` to avoid
+ misleading users who toggled it under a prior version.
+ """
+ loader = _make_loader(device="cuda")
+ with patch("torch.cuda.is_available", return_value=True):
+ assert loader._should_use_fp8(_make_config(ModelType.ControlLoRa, fp8=True)) is False
+
+
+def test_should_use_fp8_excludes_lora():
+ loader = _make_loader(device="cuda")
+ assert loader._should_use_fp8(_make_config(ModelType.LoRA, fp8=True)) is False
+
+
+def test_should_use_fp8_returns_true_for_main_with_fp8():
+ loader = _make_loader(device="cuda")
+ assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=True)) is True
+
+
+def test_should_use_fp8_returns_false_for_main_without_fp8():
+ loader = _make_loader(device="cuda")
+ assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=False)) is False
+
+
+def test_should_use_fp8_returns_false_on_cpu():
+ loader = _make_loader(device="cpu")
+ assert loader._should_use_fp8(_make_config(ModelType.Main, fp8=True)) is False
+
+
+class _RaisingModule(torch.nn.Module):
+ """A module whose forward unconditionally raises — used to test that the FP8 wrapper's
+ storage-dtype cleanup runs even when forward fails."""
+
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(4))
+ self.bias = torch.nn.Parameter(torch.zeros(4))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ raise RuntimeError("boom")
+
+
+def _fp8_supported() -> bool:
+ return hasattr(torch, "float8_e4m3fn")
+
+
[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")
+def test_wrap_forward_restores_storage_dtype_on_exception():
+ """When forward raises, params must be returned to storage dtype. Otherwise FP8 storage
+ savings silently revert to fp16/bf16 and the cache's size accounting becomes stale.
+ """
+ storage_dtype = torch.float8_e4m3fn
+ compute_dtype = torch.bfloat16
+
+ module = _RaisingModule()
+ for p in module.parameters(recurse=False):
+ p.data = p.data.to(storage_dtype)
+
+ ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)
+
+ # Sanity: params start in storage dtype.
+ assert module.weight.dtype == storage_dtype
+ assert module.bias.dtype == storage_dtype
+
+ with pytest.raises(RuntimeError, match="boom"):
+ module(torch.zeros(4, dtype=compute_dtype))
+
+ # Critical assertion: cleanup ran despite the exception.
+ assert module.weight.dtype == storage_dtype
+ assert module.bias.dtype == storage_dtype
+
+
[email protected](not _fp8_supported(), reason="torch.float8_e4m3fn not available")
+def test_wrap_forward_casts_to_compute_then_back_on_success():
+ """Happy-path sanity check: params are in compute dtype during forward, storage dtype after."""
+ storage_dtype = torch.float8_e4m3fn
+ compute_dtype = torch.bfloat16
+
+ seen_dtypes: list[torch.dtype] = []
+
+ class _CaptureModule(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.weight = torch.nn.Parameter(torch.zeros(4))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ seen_dtypes.append(self.weight.dtype)
+ return x + self.weight
+
+ module = _CaptureModule()
+ for p in module.parameters(recurse=False):
+ p.data = p.data.to(storage_dtype)
+
+ ModelLoader._wrap_forward_with_fp8_cast(module, storage_dtype, compute_dtype)
+
+ module(torch.zeros(4, dtype=compute_dtype))
+
+ assert seen_dtypes == [compute_dtype]
+ assert module.weight.dtype == storage_dtype
+
+
+def test_apply_fp8_to_nn_module_uses_wrapper():
+ """`_apply_fp8_to_nn_module` should delegate per-module wrapping to
+ `_wrap_forward_with_fp8_cast`, which encapsulates the hook registration.
+ """
+ module = torch.nn.Linear(4, 4)
+ with patch.object(ModelLoader, "_wrap_forward_with_fp8_cast") as mock_wrap:
+ ModelLoader._apply_fp8_to_nn_module(module, torch.float16, torch.float32)
+ mock_wrap.assert_called_once_with(module, torch.float16, torch.float32)
+
+
+def test_apply_fp8_to_nn_module_skips_norm_modules():
+ """Modules whose path matches `norm` must not be cast — diffusers' `enable_layerwise_casting`
+ does the same. FLUX RMSNorm.scale is the canonical example: a tiny learned scalar that
+ breaks badly in FP8.
+ """
+
+ class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.norm1 = torch.nn.LayerNorm(4)
+ self.linear = torch.nn.Linear(4, 4)
+
+ storage_dtype = torch.float16
+ compute_dtype = torch.float32
+ model = _Model()
+ for p in model.parameters():
+ p.data = p.data.to(compute_dtype)
+
+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype, compute_dtype)
+
+ # Linear params get cast to storage dtype.
+ assert model.linear.weight.dtype == storage_dtype
+ # Norm params stay in compute dtype — they must not be cast.
+ assert model.norm1.weight.dtype == compute_dtype
+ assert model.norm1.bias.dtype == compute_dtype
+
+
+def test_apply_fp8_to_nn_module_skips_pos_embed_and_proj_in_out():
+ """Position embeddings and the in/out projection of transformer blocks are also on the
+ diffusers default skip list — they're precision-sensitive.
+ """
+
+ class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.pos_embed = torch.nn.Linear(4, 4)
+ self.proj_in = torch.nn.Linear(4, 4)
+ self.proj_out = torch.nn.Linear(4, 4)
+ self.attn = torch.nn.Linear(4, 4)
+
+ storage_dtype = torch.float16
+ compute_dtype = torch.float32
+ model = _Model()
+ for p in model.parameters():
+ p.data = p.data.to(compute_dtype)
+
+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype, compute_dtype)
+
+ assert model.attn.weight.dtype == storage_dtype
+ assert model.pos_embed.weight.dtype == compute_dtype
+ assert model.proj_in.weight.dtype == compute_dtype
+ assert model.proj_out.weight.dtype == compute_dtype
+
+
+def test_apply_fp8_to_nn_module_skips_unsupported_layer_types():
+ """Only the layer classes in `_FP8_SUPPORTED_PYTORCH_LAYERS` are cast — matches diffusers'
+ behavior. A custom RMSNorm-style module with a raw Parameter must be left alone, otherwise
+ its learned scalar gets clobbered.
+ """
+
+ class _ScaleModule(torch.nn.Module):
+ """Mimics FLUX RMSNorm — a tiny learned scalar that must not be cast to FP8."""
+
+ def __init__(self):
+ super().__init__()
+ self.scale = torch.nn.Parameter(torch.ones(4))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return x * self.scale
+
+ class _Model(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.rms = _ScaleModule()
+ self.linear = torch.nn.Linear(4, 4)
+
+ storage_dtype = torch.float16
+ compute_dtype = torch.float32
+ model = _Model()
+ for p in model.parameters():
+ p.data = p.data.to(compute_dtype)
+
+ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype, compute_dtype)
+
+ assert model.linear.weight.dtype == storage_dtype
+ # Critical: the RMS-style scalar lives on a custom module type, not in the supported list.
+ assert model.rms.scale.dtype == compute_dtype
+
+
+def test_wrap_forward_reaches_custom_linear_after_apply_custom_layers():
+ """Production order: `_load_model` applies FP8 wrapping, THEN `ModelCache.put()` calls
+ `apply_custom_layers_to_model` which constructs a NEW `CustomLinear` object via
+ `CustomLinear.__new__` and points its `__dict__` at the original `Linear.__dict__`
+ (see `wrap_custom_layer`). The new object is installed on the parent in place of the
+ original Linear.
+
+ An instance-level `forward` override would be carried into the new CustomLinear via the
+ shared dict but would close over the OLD Linear instance — so calls to the new
+ CustomLinear would silently route to `Linear.forward(old_instance, ...)` and bypass
+ `CustomLinear.forward`, where LoRA/ControlLoRA patches are applied. This is the bug a
+ reviewer reproduced on a fresh worktree.
+
+ Hooks fix this because `nn.Module._call_impl` dispatches them with the *actual* called
+ instance, and `self.forward(...)` is resolved by normal class lookup — reaching
+ `CustomLinear.forward`. This test exercises the production wrapping path (real
+ `apply_custom_layers_to_model`) and asserts CustomLinear.forward is reached by attaching
+ a sentinel patch list and observing that the patch-aware branch runs.
+ """
+
+ class Parent(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.child = torch.nn.Linear(4, 4, bias=False)
+
+ parent = Parent()
+ original_linear = parent.child
+
+ ModelLoader._wrap_forward_with_fp8_cast(original_linear, torch.float16, torch.float32)
+
+ apply_custom_layers_to_model(parent)
+ new_child = parent.child
+
+ # Sanity: production wrapping replaced the child with a NEW CustomLinear instance.
+ assert isinstance(new_child, CustomLinear)
+ assert new_child is not original_linear
+
+ # Attach a sentinel patch so CustomLinear.forward routes through the LoRA-aware branch
+ # (see custom_linear.py: `if len(self._patches_and_weights) > 0`). If that branch fires,
+ # our FP8 wrapping is correctly dispatched through CustomLinear.forward.
+ patch_was_invoked = {"hit": False}
+
+ class _SentinelPatch:
+ def __init__(self):
+ self.hit = patch_was_invoked
+
+ def __call__(self, *_args, **_kwargs): # not actually called
+ pass
+
+ # Patch the CustomLinear's patch-handling branch to record that it was reached.
+ original_patch_branch = CustomLinear._autocast_forward_with_patches
+
+ def tracked_patch_branch(self, input):
+ patch_was_invoked["hit"] = True
+ # Return a same-shape tensor so the outer caller doesn't choke.
+ return torch.zeros_like(input @ self.weight.t())
+
+ new_child._patches_and_weights = [(_SentinelPatch(), 1.0)]
+ try:
+ CustomLinear._autocast_forward_with_patches = tracked_patch_branch
+ _ = new_child(torch.zeros(1, 4, dtype=torch.float32))
+ finally:
+ CustomLinear._autocast_forward_with_patches = original_patch_branch
+ new_child._patches_and_weights = []
+
+ assert patch_was_invoked["hit"] is True, (
+ "FP8-wrapped forward did not reach CustomLinear.forward — LoRA/ControlLoRA patches "
+ "would be silently bypassed on FP8 checkpoint models."
+ )