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(fp8): decide keep_fp8 once, derive the compute dtype from a float param
Alexander Eichhorn834cc9fbb603
diff --git a/invokeai/backend/model_manager/load/load_default.py b/invokeai/backend/model_manager/load/load_default.pyindex bfd6818cfb..ec380403d1 100644--- a/invokeai/backend/model_manager/load/load_default.py+++ b/invokeai/backend/model_manager/load/load_default.py@@ -542,10 +542,19 @@ class ModelLoader(ModelLoaderBase):# 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).+ #+ # The first *floating-point* param, and never a float8 one. A bare `next(model.parameters())`+ # reads whatever comes first, and `_is_quantized_param` below exists precisely because a+ # checkpoint quantized by an external tool can reach here with packed `uint8` weights. One of+ # those as the leading param would be recorded as the compute dtype, so the cast hooks would+ # 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.if isinstance(model, torch.nn.Module):- first_param = next(model.parameters(), None)- if first_param is not None:- compute_dtype = first_param.dtype+ 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,+ )# We use our own hook-based path for every nn.Module — including diffusers ModelMixin —# rather than `model.enable_layerwise_casting()`. Diffusers' LayerwiseCastingHook installsdiff --git a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.pyindex 75be97bbf9..8377092808 100644--- a/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py+++ b/invokeai/backend/model_manager/load/model_loaders/mistral_encoder.py@@ -1278,6 +1278,13 @@ class MistralEncoderCheckpointLoader(ModelLoader):}fp8_layers = {_bare_mistral_path(path): layer for path, layer in fp8_layers.items()}+ # Decided once, here, and handed to both the prediction and the cast. Reading `bool(fp8_layers)`+ # at each call site is not the same expression twice: `split_fp8_scaled_layers` rebinds the name+ # below, so the cast would see the *post-split* mapping. An encoder whose scaled layers are all+ # block-wise (or all skip-patterned) empties it, the cast would flip to `keep_fp8=False` and widen+ # every *raw* fp8 weight too -- each charged one byte per element in the reservation above.+ keep_raw_fp8 = bool(fp8_layers)+# One reservation, before the dequantizing branch or the split widens a single weight -- `make_room` makes# that much room rather than adding to an earlier one. The state dict is sized by the predicate the split and# the cast below decide with, the nvfp4 layers as they will be held.@@ -1285,7 +1292,7 @@ class MistralEncoderCheckpointLoader(ModelLoader):predict_cast_state_dict_size(sd,model_dtype,- keep_fp8=bool(fp8_layers),+ keep_fp8=keep_raw_fp8,model=model,skip_patterns=skip_patterns,scaled_layers=fp8_layers,@@ -1307,7 +1314,7 @@ class MistralEncoderCheckpointLoader(ModelLoader):# Layers the cast would dequantize anyway are folded here, scale applied, so the cast never# strips a scale that can no longer be put back.fp8_layers = split_fp8_scaled_layers(sd, fp8_layers, model_dtype, model=model, skip_patterns=skip_patterns)- cast_state_dict(sd, model_dtype, keep_fp8=bool(fp8_layers), model=model, skip_patterns=skip_patterns)+ cast_state_dict(sd, model_dtype, keep_fp8=keep_raw_fp8, model=model, skip_patterns=skip_patterns)if nvfp4_payloads:packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)diff --git a/invokeai/backend/quantization/fp8_scaled.py b/invokeai/backend/quantization/fp8_scaled.pyindex 95433742fd..964d00744c 100644--- a/invokeai/backend/quantization/fp8_scaled.py+++ b/invokeai/backend/quantization/fp8_scaled.py@@ -1111,6 +1111,11 @@ def dequantize_weight(weight: torch.Tensor, weight_scale: torch.Tensor | None, dout = weight.to(dtype)if weight_scale is None:return out+ # Refuse an MX grid here, before the cast. `expand_weight_scale` makes the same check, but it+ # keys on the scale's dtype, and casting to the compute dtype is exactly what erases that+ # evidence — so the guard below would be unreachable on this path and an undecoded exponent+ # byte would be multiplied in as a linear factor (~127x, and paired with the wrong rows).+ reject_undecoded_mx_scale("<weight_scale>", weight_scale)scale = weight_scale.to(device=out.device, dtype=dtype)return out * expand_weight_scale(out, scale)diff --git a/tests/backend/model_manager/load/test_load_default_fp8.py b/tests/backend/model_manager/load/test_load_default_fp8.pyindex 78b474dbd8..51dbe2efce 100644--- a/tests/backend/model_manager/load/test_load_default_fp8.py+++ b/tests/backend/model_manager/load/test_load_default_fp8.py@@ -738,6 +738,37 @@ def test_keep_in_fp32_modules_are_not_cast():assert model.attn.weight.dtype == torch.float8_e4m3fn+class TestComputeDtypeIsAlwaysAFloat:+ """The compute dtype is read off the model's parameters, and not every parameter is arithmetic.++ `_is_quantized_param` exists because a checkpoint quantized by an external tool can reach the+ cast with packed `uint8` weights that `_should_use_fp8`'s format check cannot see. Taking the+ *first* parameter's dtype would record one of those as the dtype the model computes in: the+ pre-hook would widen every other layer to `uint8`, and `get_model_compute_dtype` would hand+ `uint8` to the denoise loop. Finite garbage, nothing logged.+ """++ def _model(self, leading: torch.Tensor) -> torch.nn.Module:+ model = torch.nn.Module()+ # Registered first, so `model.parameters()` yields it first.+ model.register_parameter("packed", torch.nn.Parameter(leading, requires_grad=False))+ model.add_module("attn", torch.nn.Linear(4, 4).to(torch.bfloat16))+ return model++ def test_a_packed_leading_param_is_not_taken_as_the_compute_dtype(self) -> None:+ """A leading *float8* param is covered by a different guard — `count_fp8_weights` returns+ before the dtype is derived at all — so only the packed-integer case reaches this code."""+ loader = _make_loader(device="cuda")+ model = self._model(torch.zeros(4, 4, dtype=torch.uint8))++ with patch.object(ModelLoader, "_should_use_fp8", return_value=True):+ loader._apply_fp8_layerwise_casting(model, _make_config(ModelType.Main, fp8=True))++ assert getattr(model, FP8_COMPUTE_DTYPE_ATTR) is torch.bfloat16+ # And the cast actually ran against that dtype rather than skipping the model.+ assert model.attn.weight.dtype is torch.float8_e4m3fn++class TestAlreadyFp8StorageGuard:"""FP8 storage must not run over weights that are already fp8 and headed for the tensor cores.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 3c257cf1ab..b38f65e8ea 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@@ -220,6 +220,40 @@ def test_an_int8_convrot_layer_is_refused_rather_than_folded_unrotated(assert run.reserved == []+def test_a_raw_fp8_weight_survives_a_split_that_empties_the_scaled_mapping(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """The reservation and the cast have to decide with the same value, not the same expression.++ `split_fp8_scaled_layers` rebinds `fp8_layers`, so reading `bool(fp8_layers)` at the cast reads+ the *post-split* mapping while the reservation read the pre-split one. This checkpoint makes the+ two disagree: its only scaled layer carries a block-wise scale that `scaled_mm` cannot apply, so+ the split folds it and hands back nothing -- and a cast that re-derives its flag from that would+ widen the *raw* fp8 weight too, after charging it one byte per element.+ """+ checkpoint, _, _ = _write_checkpoint(tmp_path, evidence="none")+ tensors = load_file(checkpoint)+ for layer in range(LAYERS):+ # A layout the matmul cannot consume, so the split dequantizes this layer and drops it.+ scaled = f"model.layers.{layer}.{FP8_PROJECTION}"+ tensors[f"{scaled}.weight_scale"] = torch.full((KV_ROWS, HIDDEN // 16), 0.5)+ # And one weight that arrives fp8 with no scale at all, which is what `keep_fp8` governs.+ raw = f"model.layers.{layer}.self_attn.o_proj"+ tensors[f"{raw}.weight"] = torch.randint(-8, 9, (HIDDEN, HIDDEN)).float().to(torch.float8_e4m3fn)+ save_file(tensors, checkpoint)+ run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(True), observe=WIDENING)++ model = run.load(_config(checkpoint))++ for layer in range(LAYERS):+ attn = model.layers[layer].self_attn+ # The premise: the split really did fold the only scaled layer, so `fp8_layers` came back empty.+ assert attn.v_proj.weight.dtype is COMPUTE_DTYPE, "the block-wise layer was expected to be folded"+ # The claim: the raw fp8 weight is still held the way the reservation was told it would be.+ assert attn.o_proj.weight.dtype is torch.float8_e4m3fn+ assert len(run.reserved) == 1++def test_a_checkpoint_without_nvfp4_layers_loads_as_before(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:checkpoint, expected, _ = _write_checkpoint(tmp_path, evidence="none")run = prepare(SEAM, monkeypatch, geometry=_fp8_matmul(False), observe=WIDENING)diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex 364d4dcfc6..ad96eb5215 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -546,6 +546,18 @@ class TestDequantize:dequantize_fp8_scaled(sd, layers)assert torch.equal(sd["lin.weight"], dequantize_weight(q, scale, torch.bfloat16))+ @pytest.mark.parametrize("grid_dtype", [torch.uint8, getattr(torch, "float8_e8m0fnu", torch.uint8)])+ def test_an_undecoded_mx_grid_is_refused_not_multiplied(self, grid_dtype: torch.dtype):+ """`reject_undecoded_mx_scale` keys on the scale's dtype, and this is the one caller that+ used to cast the scale to the compute dtype first — which erases the evidence. An exponent+ byte multiplied in as a linear factor is ~127x, paired with the wrong rows besides: the+ finite-but-wrong noise the whole MX decode exists to prevent."""+ q = torch.randn(256, 8, dtype=torch.bfloat16).to(FP8_DTYPE)+ grid = torch.full((256, 8), 127, dtype=grid_dtype)++ with pytest.raises(NotImplementedError, match="MXFP8"):+ dequantize_weight(q, grid, torch.bfloat16)+class TestAttach:def test_registers_non_persistent_buffers(self):