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
docs(fp8): correct why pattern-skipped fp8 weights must be restored
Alexander Eichhorn980c9cbe7cd3
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex bfd6818cfb..1755f4b85b 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -621,11 +621,23 @@ class ModelLoader(ModelLoaderBase):if any(re.search(pattern, module_name) for pattern in skip_patterns):# A pattern skip means "this module computes in `compute_dtype`", so a weight that# arrived already float8 contradicts it: nothing casts it back and no pre-hook is- # installed here, leaving the forward to run on raw fp8 codes. That is reachable+ # installed here. What that costs depends on the layer class, because only some of+ # them get an fp8-capable wrapper from `apply_custom_layers_to_model`:+ #+ # - `Linear` and `Conv2d` need nothing. `CustomLinear` dequantizes an unscaled fp8+ # weight and `CustomConv2d` casts it; both round-trips are value-exact.+ # - `Conv1d`'s wrapper only moves the weight to the device, and `Conv3d` plus the+ # three `ConvTranspose` classes have no wrapper at all. Their forward raises+ # "Input type ... and weight type ... should be the same", mid-generation.+ # - `CustomEmbedding` never touches the dtype, so the lookup hands a float8 tensor+ # to the next op, which has no kernel for it.+ #+ # So six of the eight classes in `_FP8_SUPPORTED_PYTORCH_LAYERS` do need the weights+ # put back, and the default patterns name exactly where they live: `patch_embed.proj`+ # is a `Conv3d` in video and VL towers, `pos_embed` an `Embedding`. Reachable# whenever a loader keeps checkpoint fp8 weights and then asks for fp8 storage on- # the remainder (the Qwen3-VL encoder does exactly this), and it depends on a- # coincidence — that the loader's own skip list and this one never name the same- # Linear. Upcast instead of relying on that.+ # the remainder (the Qwen3-VL encoder does exactly this), so restore here rather+ # than rely on the loader's own skip list never naming the same module as this one.ModelLoader._restore_compute_dtype(module, compute_dtype)continueif skip is not None and skip(module_name, module):@@ -653,6 +665,11 @@ class ModelLoader(ModelLoaderBase):bitsandbytes) is left to its own kernels. A scaled-fp8 layer (fp8 weight plus `weight_scale`)is not raw codes either: `CustomLinear` dequantizes it with its scale, while a plain upcasthere would drop the scale.++ The widened params cost more than `predict_cast_state_dict_size(keep_fp8=True)` reserved for+ them, since a caller that keeps checkpoint fp8 does not know this pass will give some of it+ back. It is bounded by the pattern-skipped modules, and it buys a forward that runs at all+ for the layer classes with no fp8-capable wrapper — see the call site for which those are."""if getattr(module, "weight_scale", None) is not None:returndiff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 436b2f687e..de050dc365 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -967,9 +967,10 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEncofp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model)# No `skip_patterns` here on purpose: this model declares none, and the storage pass below# applies `_FP8_DEFAULT_SKIP_PATTERNS` itself. Those two lists used to have to not intersect- # on a 2-D Linear -- such a weight would arrive fp8 from the state dict, be skipped by the- # cast pass, and forward on raw fp8 codes. `_apply_fp8_to_nn_module` now restores the compute- # dtype on the modules it skips, so the two lists are independent again.+ # on a layer class with no fp8-capable wrapper -- a `pos_embed` or a `patch_embed.proj`+ # would arrive fp8 from the state dict, be skipped by the cast pass, and then raise on the+ # first forward. `_apply_fp8_to_nn_module` now restores the compute dtype on the modules it+ # skips, so the two lists are independent again.cast_state_dict(sd, model_dtype, keep_fp8=keep_fp8, model=model)load_state_dict_ignoring_extras(@@ -996,7 +997,7 @@ class Qwen3VLEncoderCheckpointLoader(_Qwen3VLEncoderSingleFileLoader[Qwen3VLEnco# `set_fp8_compute_dtype`, without which `get_model_compute_dtype` falls back to scanning# for a non-fp8 float parameter -- which happens to work only because the embedding is# excluded here and stays bf16. And it installs the backstop that restores the compute- # dtype on Linears its skip list and the default one both name, which is the documented+ # dtype on the modules its skip list and the default one both name, which is the documented# guard against those two lists ever overlapping. Two exclusions:## - anything carrying a `weight_scale`: those keep their scale and go throughdiff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex 78b474dbd8..8de6661337 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -13,6 +13,7 @@ Covers:so FLUX RMSNorm.scale and friends aren't crushed to FP8."""+import copyfrom logging import getLoggerfrom types import SimpleNamespacefrom unittest.mock import patch@@ -853,11 +854,13 @@ class TestSkippedModulesNeverKeepCheckpointFp8:"""A pattern-skipped module must not be left holding float8 weights.The cast pass installs the upcast pre-hook only on modules it casts. A module it *skips* keeps- whatever dtype it arrived with — fine when that is the compute dtype, silently fatal when the- loader kept the checkpoint's fp8 weights: no hook, no cast back, and the forward runs on raw fp8- codes. Reachable wherever a loader combines `keep_fp8` with fp8 storage on the remainder (the- Qwen3-VL encoder), and otherwise dependent on the loader's skip list and- `_FP8_DEFAULT_SKIP_PATTERNS` never naming the same Linear.+ whatever dtype it arrived with — fine when that is the compute dtype, broken when the loader+ kept the checkpoint's fp8 weights: no hook and no cast back. Whether that shows up depends on+ the layer class, since `apply_custom_layers_to_model` only gives some of them an fp8-capable+ wrapper; `test_every_supported_layer_class_forwards_after_a_pattern_skip` pins which. Reachable+ wherever a loader combines `keep_fp8` with fp8 storage on the remainder (the Qwen3-VL encoder),+ and otherwise dependent on the loader's skip list and `_FP8_DEFAULT_SKIP_PATTERNS` never naming+ the same module."""def _model(self) -> torch.nn.Module:@@ -897,6 +900,15 @@ class TestSkippedModulesNeverKeepCheckpointFp8:assert model.proj_out.weight.dtype is torch.float8_e4m3fnassert torch.equal(model.proj_out.weight.float(), codes.float())+ # The dtype alone does not settle it: what matters is that the forward still applies the+ # scale. A cast that dropped it would leave the projection at 1/scale of the right answer.+ model.proj_out.bias = torch.nn.Parameter(torch.zeros(32, dtype=torch.bfloat16), requires_grad=False)+ apply_custom_layers_to_model(model)+ inp = torch.randn(4, 16, dtype=torch.bfloat16)+ dequantized = codes.to(torch.bfloat16) * 2.0++ assert torch.equal(model.proj_out(inp), torch.nn.functional.linear(inp, dequantized))+def test_an_extra_skip_pattern_gets_the_same_treatment(self) -> None:model = self._model()model.attn.weight = torch.nn.Parameter(@@ -939,3 +951,68 @@ class TestSkippedModulesNeverKeepCheckpointFp8:)assert model.attn.weight.dtype is torch.float8_e4m3fn++ @pytest.mark.parametrize(+ ("make_module", "make_input"),+ [+ pytest.param(+ lambda: torch.nn.Linear(16, 32), lambda: torch.randn(4, 16, dtype=torch.bfloat16), id="Linear"+ ),+ pytest.param(+ lambda: torch.nn.Conv1d(4, 8, 3), lambda: torch.randn(1, 4, 16, dtype=torch.bfloat16), id="Conv1d"+ ),+ pytest.param(+ lambda: torch.nn.Conv2d(4, 8, 3), lambda: torch.randn(1, 4, 8, 8, dtype=torch.bfloat16), id="Conv2d"+ ),+ pytest.param(+ lambda: torch.nn.Conv3d(4, 8, 3), lambda: torch.randn(1, 4, 6, 6, 6, dtype=torch.bfloat16), id="Conv3d"+ ),+ pytest.param(+ lambda: torch.nn.ConvTranspose1d(4, 8, 3),+ lambda: torch.randn(1, 4, 16, dtype=torch.bfloat16),+ id="ConvTranspose1d",+ ),+ pytest.param(+ lambda: torch.nn.ConvTranspose2d(4, 8, 3),+ lambda: torch.randn(1, 4, 8, 8, dtype=torch.bfloat16),+ id="ConvTranspose2d",+ ),+ pytest.param(+ lambda: torch.nn.ConvTranspose3d(4, 8, 3),+ lambda: torch.randn(1, 4, 6, 6, 6, dtype=torch.bfloat16),+ id="ConvTranspose3d",+ ),+ pytest.param(lambda: torch.nn.Embedding(16, 32), lambda: torch.tensor([1, 2, 3]), id="Embedding"),+ ],+ )+ def test_every_supported_layer_class_forwards_after_a_pattern_skip(self, make_module, make_input) -> None:+ """One case per class in `_FP8_SUPPORTED_PYTORCH_LAYERS`, run the way the cache leaves them.++ This is what makes the restore load-bearing rather than belt-and-braces. Only `Linear` and+ `Conv2d` get a wrapper from `apply_custom_layers_to_model` that can consume an fp8 weight;+ `Conv1d`'s only moves the weight to the device, `Conv3d` and the three `ConvTranspose`+ classes get none, and `CustomEmbedding` hands the next op a float8 tensor. Drop the restore+ and six of these eight fail — five by raising mid-forward.+ """+ torch.manual_seed(0)+ module = make_module().to(torch.bfloat16)+ # Round-trip first, so the reference is what the fp8 codes actually represent rather than+ # the full-precision weight they were quantized from.+ module.weight = torch.nn.Parameter(+ module.weight.data.to(torch.float8_e4m3fn).to(torch.bfloat16), requires_grad=False+ )+ reference = copy.deepcopy(module)+ module.weight = torch.nn.Parameter(module.weight.data.to(torch.float8_e4m3fn), requires_grad=False)++ model = torch.nn.Module()+ # `^proj_out$` is in `_FP8_DEFAULT_SKIP_PATTERNS`, so this module is never cast or hooked.+ model.add_module("proj_out", module)++ ModelLoader._apply_fp8_to_nn_module(model, storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)+ apply_custom_layers_to_model(model)++ inp = make_input()+ out = model.proj_out(inp)++ assert out.dtype is torch.bfloat16+ assert torch.equal(out, reference(inp))