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
feat(krea2): keep ComfyUI scaled-fp8 checkpoints quantized and run them on fp8 tensor cores
Alexander Eichhorn580813cd1808
diff --git a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.py b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.pyindex f8b80a9b4d..e910d330cc 100644--- a/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.py+++ b/invokeai/backend/model_manager/load/model_cache/torch_module_autocast/custom_modules/custom_linear.py@@ -135,25 +135,38 @@ class CustomLinear(torch.nn.Linear, CustomModuleMixin):# Partial loading may leave the weight on the CPU; _scaled_mm needs both operands co-located.return self.weight.device == input.device+ def _maybe_fp8_forward(self, input: torch.Tensor) -> torch.Tensor | None:+ """Run the fp8 matmul if this module and input allow it, else None so callers fall back."""+ if not self._can_use_fp8_matmul(input):+ return None+ return scaled_mm_linear(+ input,+ self.weight,+ self._fp8_weight_scale(input.device),+ cast_to_device(self.bias, input.device),+ input_scale=cast_to_device(getattr(self, "input_scale", None), input.device),+ )+def _autocast_forward_with_patches(self, input: torch.Tensor) -> torch.Tensor:return autocast_linear_forward_sidecar_patches(self, input, self._patches_and_weights)def _autocast_forward(self, input: torch.Tensor) -> torch.Tensor:- if self._can_use_fp8_matmul(input):- return scaled_mm_linear(- input,- self.weight,- self._fp8_weight_scale(input.device),- cast_to_device(self.bias, input.device),- input_scale=cast_to_device(getattr(self, "input_scale", None), input.device),- )+ out = self._maybe_fp8_forward(input)+ if out is not None:+ return outweight, bias = self._cast_weight_bias_for_input(input)return torch.nn.functional.linear(input, weight, bias)def forward(self, input: torch.Tensor) -> torch.Tensor:if len(self._patches_and_weights) > 0:return self._autocast_forward_with_patches(input)- elif self._device_autocasting_enabled:+ # Checked before the autocasting branch on purpose: `apply_custom_layers_to_model` leaves+ # device autocasting *disabled* whenever the model is fully resident, so a check that only+ # lived in `_autocast_forward` would silently never run in the common case.+ fp8_out = self._maybe_fp8_forward(input)+ if fp8_out is not None:+ return fp8_out+ if self._device_autocasting_enabled:return self._autocast_forward(input)elif input.is_floating_point() and ((self.weight.is_floating_point() and self.weight.dtype != input.dtype)diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex d5abc22bb2..fa5ff88728 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -196,7 +196,7 @@ class TestScaledMm:class TestCustomLinearIntegration:"""The fp8 matmul must be opt-in and must degrade to the dequantized path, never raise."""- def _module(self, device: torch.device, in_f=64, out_f=128):+ def _module(self, device: torch.device, in_f=64, out_f=128, device_autocasting: bool = False):from invokeai.backend.model_manager.load.model_cache.torch_module_autocast.torch_module_autocast import (apply_custom_layers_to_model,)@@ -206,9 +206,42 @@ class TestCustomLinearIntegration:lin.weight = torch.nn.Parameter(q.to(device), requires_grad=False)lin.register_buffer("weight_scale", scale.to(device), persistent=False)model = torch.nn.Sequential(lin).to(device)- apply_custom_layers_to_model(model)+ apply_custom_layers_to_model(model, device_autocasting_enabled=device_autocasting)return model+ @cuda_fp8+ @pytest.mark.parametrize("device_autocasting", [False, True])+ def test_fp8_path_runs_regardless_of_device_autocasting(self, device_autocasting: bool):+ """`apply_custom_layers_to_model` leaves autocasting off for fully-resident models.++ A fp8 check that only lives in `_autocast_forward` is therefore skipped in the common case:+ `forward` falls through to the dtype-mismatch branch and silently dequantizes instead. This+ regression cost the entire speedup while every other test stayed green.+ """+ dev = torch.device("cuda")+ model = self._module(dev, device_autocasting=device_autocasting)+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)+ custom = model[0]++ calls = []+ original = custom._maybe_fp8_forward+ custom._maybe_fp8_forward = lambda inp: (calls.append(1), original(inp))[1]++ set_fp8_matmul_enabled(True)+ try:+ out = model(x)+ finally:+ set_fp8_matmul_enabled(False)+ custom._maybe_fp8_forward = original++ assert calls, "the fp8 branch was never consulted"+ assert out.shape == (32, 128)+ # And it must actually have taken the fp8 path, not just been asked.+ w_ref = dequantize_weight(custom.weight, custom.weight_scale, torch.bfloat16)+ assert not torch.equal(out, torch.nn.functional.linear(x, w_ref)), (+ "output is bit-identical to the dequantized path, so _scaled_mm did not run"+ )+def test_disabled_by_default_uses_scaled_dequant(self):"""With the matmul off, the weight must still be dequantized *with* its scale."""set_fp8_matmul_enabled(False)