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.

fix(models): derive FP8 Storage's compute dtype without the model's fp32 modules (#10295)

Alexander Eichhornbcac28ae38a1
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.py
index 89c15e7d00..825313a715 100644
--- a/invokeai/backend/model_manager/load/load_default.py
+++ b/invokeai/backend/model_manager/load/load_default.py
@@ -231,6 +231,15 @@ def _is_quantized_param(param: torch.nn.Parameter) -> bool:
return not param.data.is_floating_point() or type(param.data) is not torch.Tensor
+def _declared_patterns(model: torch.nn.Module, attr: str) -> tuple[str, ...]:
+ """The string entries of a class attribute that lists module-name patterns, tolerating odd declarations."""
+ declared = getattr(model, attr, None) or ()
+ # Diffusers stores these as lists of strings, but a subclass could set a bare string.
+ if isinstance(declared, str):
+ declared = (declared,)
+ return tuple(p for p in declared if isinstance(p, str))
+
+
def _model_declared_skip_patterns(model: torch.nn.Module) -> tuple[str, ...]:
"""The precision-sensitive modules a model declares for itself, as skip patterns.
@@ -251,11 +260,7 @@ def _model_declared_skip_patterns(model: torch.nn.Module) -> tuple[str, ...]:
"""
patterns: list[str] = []
for attr in ("_skip_layerwise_casting_patterns", "_keep_in_fp32_modules"):
- declared = getattr(model, attr, None) or ()
- # Diffusers stores these as lists of strings, but a subclass could set a bare string.
- if isinstance(declared, str):
- declared = (declared,)
- patterns.extend(p for p in declared if isinstance(p, str) and p not in patterns)
+ patterns.extend(p for p in _declared_patterns(model, attr) if p not in patterns)
return tuple(patterns)
@@ -643,10 +648,22 @@ class ModelLoader(ModelLoaderBase):
# widen every other layer to `uint8` and `get_model_compute_dtype` would hand `uint8` to the
# denoise loop — finite garbage, nothing logged. A float8 leading param is skipped for the
# same reason `set_fp8_compute_dtype` rejects one: it is storage, not arithmetic.
+ #
+ # Parameters of `_keep_in_fp32_modules` are skipped too, by the same name rule as diffusers'
+ # `get_parameter_dtype`: they stay float32 on purpose and say nothing about the dtype the
+ # other layers compute in (Wan's `scale_shift_table` is registered first and would make
+ # every fp8 weight widen to float32).
if isinstance(model, torch.nn.Module):
+ keep_fp32 = _declared_patterns(model, "_keep_in_fp32_modules")
+ float_params = [
+ (name, p)
+ for name, p in model.named_parameters()
+ if p.is_floating_point() and p.dtype not in FP8_STORAGE_DTYPES
+ ]
+ # When every float is kept in float32 there is nothing else to read; like diffusers, take the first.
compute_dtype = next(
- (p.dtype for p in model.parameters() if p.is_floating_point() and p.dtype not in FP8_STORAGE_DTYPES),
- compute_dtype,
+ (p.dtype for name, p in float_params if not any(m in name for m in keep_fp32)),
+ float_params[0][1].dtype if float_params else compute_dtype,
)
# We use our own hook-based path for every nn.Module — including diffusers ModelMixin —
diff --git a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
index a80aaec915..55962dd0c2 100644
--- a/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
+++ b/invokeai/backend/model_manager/load/model_loaders/minimax_h3.py
@@ -85,8 +85,8 @@ def _raise_if_no_weight_shards(submodel_path: Path, submodel_label: str) -> None
type=ModelType.Main,
format=ModelFormat.Diffusers,
fp8_storage=Unimplemented(
- "the transformer keeps fp32 patch projections and output heads beside bf16 blocks, and the cast "
- "derives one compute dtype from the first float parameter; that has to be checked here first"
+ "the transformer reads `context_embedder.weight.dtype` and the AdaLN `linear.weight.dtype` to cast "
+ "its inputs, so an fp8 weight would turn those inputs into fp8 before the cast hook widens it"
),
)
class MiniMaxH3DiffusersModel(ModelLoader):
diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.py
index 7ac54ffe64..e227da322e 100644
--- a/tests/backend/model_manager/load/test_load_default_fp8.py
+++ b/tests/backend/model_manager/load/test_load_default_fp8.py
@@ -38,6 +38,20 @@ from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch
from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.util.fp8 import FP8_COMPUTE_DTYPE_ATTR
+_MISSING = object()
+
+# `WanTransformer3DModel` at a size that builds in milliseconds; the structure is the real one.
+WAN_TINY_KWARGS = {
+ "patch_size": (1, 2, 2),
+ "in_channels": 16,
+ "out_channels": 16,
+ "num_layers": 2,
+ "attention_head_dim": 128,
+ "num_attention_heads": 1,
+ "ffn_dim": 64,
+ "text_dim": 32,
+}
+
def _make_loader(device: str = "cuda") -> ModelLoader:
"""Build a ModelLoader without going through dependency injection.
@@ -929,6 +943,74 @@ class TestComputeDtypeIsAlwaysAFloat:
assert model.attn.weight.dtype is torch.float8_e4m3fn
+class TestComputeDtypeIgnoresKeepInFp32Parameters:
+ """A parameter kept in float32 on purpose says nothing about the dtype the other layers compute in.
+
+ Wan registers `scale_shift_table` (float32, in `_keep_in_fp32_modules`) before any submodule, so the
+ first float parameter is not the compute dtype: fp8 weights would be widened to float32 on every forward.
+ """
+
+ @staticmethod
+ def _cast(model: torch.nn.Module) -> None:
+ loader = _make_loader(device="cuda")
+ with patch.object(ModelLoader, "_should_use_fp8", return_value=True):
+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))
+
+ @staticmethod
+ def _model(keep) -> torch.nn.Module:
+ model = torch.nn.Module()
+ if keep is not _MISSING:
+ model._keep_in_fp32_modules = keep
+ model.register_parameter("scale_shift_table", torch.nn.Parameter(torch.zeros(1, 2, 4), requires_grad=False))
+ model.add_module("attn", torch.nn.Linear(4, 4).to(torch.bfloat16))
+ return model
+
+ def test_a_leading_fp32_keep_parameter_is_not_the_compute_dtype(self) -> None:
+ model = self._model(["scale_shift_table"])
+ self._cast(model)
+
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16
+ assert model.attn.weight.dtype is torch.float8_e4m3fn
+
+ def test_a_bare_string_declaration_is_a_name_not_a_set_of_characters(self) -> None:
+ model = self._model("scale_shift_table")
+ self._cast(model)
+
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16
+
+ @pytest.mark.parametrize("keep", [_MISSING, None, [], ["other"], [None, 3]])
+ def test_without_a_usable_declaration_the_first_float_parameter_decides(self, keep) -> None:
+ model = self._model(keep)
+ self._cast(model)
+
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.float32
+
+ def test_a_model_whose_only_floats_are_kept_computes_in_the_first_of_them(self) -> None:
+ model = torch.nn.Module()
+ model._keep_in_fp32_modules = ["scale_shift_table"]
+ model.register_parameter("scale_shift_table", torch.nn.Parameter(torch.zeros(1, 2, 4), requires_grad=False))
+ self._cast(model)
+
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.float32
+
+ def test_the_real_wan_transformer_computes_in_bf16_and_keeps_its_fp32_islands(self, tmp_path) -> None:
+ from diffusers import WanTransformer3DModel
+
+ WanTransformer3DModel(**WAN_TINY_KWARGS).save_pretrained(tmp_path)
+ model = WanTransformer3DModel.from_pretrained(tmp_path, torch_dtype=torch.bfloat16)
+ first_name, first_param = next(iter(model.named_parameters()))
+ assert first_name == "scale_shift_table"
+ assert first_param.dtype is torch.float32
+
+ self._cast(model)
+
+ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16
+ assert model.blocks[0].attn1.to_q.weight.dtype is torch.float8_e4m3fn
+ # The fp32 island survives the cast (Wan protects it through both `_keep_in_fp32_modules` and
+ # `_skip_layerwise_casting_patterns`; `test_keep_in_fp32_modules_are_not_cast` covers the keep list alone).
+ assert model.condition_embedder.time_embedder.linear_1.weight.dtype is torch.float32
+
+
class TestAlreadyFp8StorageGuard:
"""FP8 storage must not run over weights that are already fp8 and headed for the tensor cores.