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 krea2 GGUF dequant dtype on mps (#9573)

Grunblatt8d6ffb2111e0
diff --git a/invokeai/app/invocations/krea2/krea2_denoise.py b/invokeai/app/invocations/krea2/krea2_denoise.py
index 3855318756..c4af011701 100644
--- a/invokeai/app/invocations/krea2/krea2_denoise.py
+++ b/invokeai/app/invocations/krea2/krea2_denoise.py
@@ -56,7 +56,7 @@ from invokeai.backend.krea2.sampling_utils import (
from invokeai.backend.krea2.style_reference_extension import Krea2StyleReferenceExtension
from invokeai.backend.krea2.text_encoding import KREA2_MAX_REFERENCE_IMAGES
from invokeai.backend.model_manager.load.load_base import LoadedModel
-from invokeai.backend.model_manager.taxonomy import BaseModelType
+from invokeai.backend.model_manager.taxonomy import BaseModelType, ModelFormat
from invokeai.backend.patches.layer_patcher import LayerPatcher
from invokeai.backend.patches.lora_conversions.krea2_lora_constants import KREA2_LORA_TRANSFORMER_PREFIX
from invokeai.backend.patches.model_patch_raw import ModelPatchRaw
@@ -489,7 +489,10 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
self._validate_inputs()
device = TorchDevice.choose_torch_device()
- inference_dtype = TorchDevice.choose_bfloat16_safe_dtype(device)
+ transformer_config = context.models.get_config(self.transformer.transformer)
+ inference_dtype = TorchDevice.choose_krea2_transformer_dtype(
+ is_gguf=transformer_config.format is ModelFormat.GGUFQuantized, device=device
+ )
# Before the transformer loads, so a malformed reference fails before anything is spent on the model.
self._validate_reference_counts(context)
@@ -657,7 +660,6 @@ class Krea2DenoiseInvocation(BaseInvocation, WithMetadata, WithBoard):
),
)
- transformer_config = context.models.get_config(self.transformer.transformer)
num_train_timesteps = scheduler.config.num_train_timesteps
# Loaded once: the estimate prices these patches and the patcher applies the same ones. Each load reports its
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.py
index aa47fa3d3f..67231e7869 100644
--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py
+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py
@@ -812,7 +812,7 @@ class Krea2GGUFCheckpointModel(ModelLoader):
model_path = Path(config.path)
target_device = TorchDevice.choose_torch_device()
- compute_dtype = TorchDevice.choose_bfloat16_safe_dtype(target_device)
+ compute_dtype = TorchDevice.choose_krea2_transformer_dtype(is_gguf=True, device=target_device)
# GGMLTensor wrappers (kept on CPU; dequantized on-the-fly by the cache during inference).
sd = gguf_sd_loader(model_path, compute_dtype=compute_dtype, convrot="decode")
diff --git a/invokeai/backend/util/devices.py b/invokeai/backend/util/devices.py
index 3e77b82ef7..44812a63e4 100644
--- a/invokeai/backend/util/devices.py
+++ b/invokeai/backend/util/devices.py
@@ -689,6 +689,21 @@ class TorchDevice:
return cls.choose_bfloat16_safe_dtype(device)
return NAME_TO_PRECISION[config.precision]
+ @classmethod
+ def choose_krea2_transformer_dtype(cls, is_gguf: bool, device: Optional[torch.device] = None) -> torch.dtype:
+ """Choose the dtype a Krea-2 transformer runs in. Its loader and the denoise step must agree.
+
+ GGUF on MPS runs in float32: with bfloat16 it produces noise there. The GGUF compute dtype is
+ not only the dequantization target -- on MPS every GGUF Linear casts its input to it, so the
+ whole transformer, and therefore the latents, conditioning and LoRA sidecar weights fed to it,
+ must use the same dtype. Everything else keeps the bfloat16-safe default. ``config.precision``
+ is deliberately not consulted, since the Krea-2 text encoder and other loaders ignore it too.
+ """
+ device = device or cls.choose_torch_device()
+ if is_gguf and device.type == "mps":
+ return torch.float32
+ return cls.choose_bfloat16_safe_dtype(device)
+
_PEER_AWARE_SENTINEL = "_invokeai_peer_aware"
diff --git a/tests/app/invocations/test_krea2_denoise.py b/tests/app/invocations/test_krea2_denoise.py
index f1209ab9d3..24281c0460 100644
--- a/tests/app/invocations/test_krea2_denoise.py
+++ b/tests/app/invocations/test_krea2_denoise.py
@@ -31,6 +31,7 @@ from invokeai.backend.quantization.dequantizing_linear import peak_dequant_trans
from invokeai.backend.quantization.int8_convrot import Int8ConvrotLinear
from invokeai.backend.rectified_flow.rectified_flow_inpaint_extension import RectifiedFlowInpaintExtension
from invokeai.backend.stable_diffusion.diffusion.conditioning_data import ConditioningFieldData, Krea2ConditioningInfo
+from invokeai.backend.util.devices import TorchDevice
@pytest.mark.parametrize(("denoising_start", "denoising_end"), [(0.75, 0.25), (0.5, 0.5)])
@@ -430,7 +431,13 @@ def _runtime_invocation(
)
-def _runtime_context(tmp_path, transformer: _Transformer, *, negative_text_seq_len: int = 2):
+def _runtime_context(
+ tmp_path,
+ transformer: _Transformer,
+ *,
+ negative_text_seq_len: int = 2,
+ model_format: ModelFormat = ModelFormat.Checkpoint,
+):
conditionings = {
"positive": ConditioningFieldData(conditionings=[Krea2ConditioningInfo(prompt_embeds=torch.ones(1, 2, 12, 8))]),
"negative": ConditioningFieldData(
@@ -449,7 +456,7 @@ def _runtime_context(tmp_path, transformer: _Transformer, *, negative_text_seq_l
"style-ref": torch.zeros(1, KREA2_LATENT_CHANNELS, 1, 2, 2),
"style-ref-wrong-size": torch.zeros(1, KREA2_LATENT_CHANNELS, 1, 4, 4),
}
- config = SimpleNamespace(format=ModelFormat.Checkpoint, variant=Krea2VariantType.Turbo)
+ config = SimpleNamespace(format=model_format, variant=Krea2VariantType.Turbo)
return SimpleNamespace(
models=SimpleNamespace(
load=lambda _identifier: _TransformerInfo(transformer),
@@ -578,6 +585,70 @@ def test_run_diffusion_keeps_fp32_sampler_state_with_bf16_model_input(
assert inpaint_merge_output_dtypes == [torch.float32] * active_steps
+ ("model_format", "expected_dtype"),
+ [(ModelFormat.GGUFQuantized, torch.float32), (ModelFormat.Checkpoint, torch.bfloat16)],
+)
+def test_run_diffusion_on_mps_feeds_transformer_and_loras_in_the_loader_dtype(
+ monkeypatch, tmp_path, model_format: ModelFormat, expected_dtype: torch.dtype
+) -> None:
+ """Latents, conditioning, timesteps and LoRA sidecar weights must match the dtype the transformer loaded in.
+
+ A GGUF transformer on MPS runs in float32 (every GGUF Linear casts its input to the compute dtype),
+ so bfloat16 LoRA weights, or bfloat16 inputs reaching a bias-free Linear, fail a matmul dtype check.
+ """
+ _patch_runtime(monkeypatch)
+ monkeypatch.setattr(
+ "invokeai.app.invocations.krea2.krea2_denoise.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.bfloat16,
+ )
+ # The real policy, asked about MPS, while the run itself stays on the CPU.
+ choose_dtype = TorchDevice.choose_krea2_transformer_dtype
+ monkeypatch.setattr(
+ "invokeai.app.invocations.krea2.krea2_denoise.TorchDevice.choose_krea2_transformer_dtype",
+ lambda is_gguf, device: choose_dtype(is_gguf=is_gguf, device=torch.device("mps")),
+ )
+ patch_dtypes: list[torch.dtype] = []
+
+ def _record_patches(**kwargs):
+ patch_dtypes.append(kwargs["dtype"])
+ return nullcontext()
+
+ monkeypatch.setattr(
+ "invokeai.app.invocations.krea2.krea2_denoise.LayerPatcher.apply_smart_model_patches", _record_patches
+ )
+ import invokeai.app.invocations.krea2.krea2_denoise as denoise_module
+
+ estimate = denoise_module.estimate_krea2_denoise_working_memory
+ estimate_dtypes: list[torch.dtype] = []
+
+ def _record_estimate(*args, **kwargs):
+ estimate_dtypes.append(kwargs["dtype"])
+ return estimate(*args, **kwargs)
+
+ monkeypatch.setattr(denoise_module, "estimate_krea2_denoise_working_memory", _record_estimate)
+
+ class _DtypeRecordingTransformer(_Transformer):
+ def __init__(self) -> None:
+ super().__init__()
+ self.input_dtypes: set[tuple[torch.dtype, ...]] = set()
+
+ def __call__(self, *, hidden_states, encoder_hidden_states, timestep, **kwargs):
+ self.input_dtypes.add((hidden_states.dtype, encoder_hidden_states.dtype, timestep.dtype))
+ return super().__call__(
+ hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, timestep=timestep, **kwargs
+ )
+
+ transformer = _DtypeRecordingTransformer()
+ _runtime_invocation(cfg_scale=1.0)._run_diffusion(
+ _runtime_context(tmp_path, transformer, model_format=model_format)
+ )
+
+ assert patch_dtypes == [expected_dtype]
+ assert estimate_dtypes == [expected_dtype]
+ assert transformer.input_dtypes == {(expected_dtype, expected_dtype, expected_dtype)}
+
+
def test_run_diffusion_applies_mixed_cfg_only_at_enabled_steps(monkeypatch, tmp_path) -> None:
_patch_runtime(monkeypatch)
transformer = _Transformer()
diff --git a/tests/app/invocations/test_upscale_index_clipped_starts.py b/tests/app/invocations/test_upscale_index_clipped_starts.py
index c6830a029e..570626710e 100644
--- a/tests/app/invocations/test_upscale_index_clipped_starts.py
+++ b/tests/app/invocations/test_upscale_index_clipped_starts.py
@@ -40,7 +40,13 @@ from invokeai.app.invocations.qwen_image.qwen_image_denoise import QwenImageDeno
from invokeai.app.invocations.z_image.z_image_denoise import ZImageDenoiseInvocation
from invokeai.backend.anima.scheduler_driver import AnimaSchedulerDriver
from invokeai.backend.flux.schedulers import ANIMA_SCHEDULER_MAP, FLUX_SCHEDULER_MAP, ZIMAGE_SCHEDULER_MAP
-from invokeai.backend.model_manager.taxonomy import BaseModelType, Flux2VariantType, Krea2VariantType, ModelType
+from invokeai.backend.model_manager.taxonomy import (
+ BaseModelType,
+ Flux2VariantType,
+ Krea2VariantType,
+ ModelFormat,
+ ModelType,
+)
FIXTURE = (
Path(__file__).parents[3]
@@ -288,7 +294,9 @@ def krea2_entry(case: dict) -> tuple[list[float], float]:
context = MagicMock()
context.tensors.load.return_value = torch.zeros(1, 16, 8, 8)
- context.models.get_config.return_value = SimpleNamespace(variant=Krea2VariantType(case["variant"]))
+ context.models.get_config.return_value = SimpleNamespace(
+ format=ModelFormat.Diffusers, variant=Krea2VariantType(case["variant"])
+ )
context.models.get_absolute_path.return_value = Path("no-such-krea2-model")
# A text-only prompt: encoded with no reference images, as the node has no reference latents.
context.conditioning.load.return_value = SimpleNamespace(conditionings=[SimpleNamespace(num_reference_images=0)])
diff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
index ea58b80800..1c3592fa8c 100644
--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py
@@ -300,6 +300,35 @@ def test_gguf_loader_constructs_and_materializes_model(monkeypatch, tmp_path) ->
assert torch.equal(model.weight, torch.ones(2, 2))
[email protected](("device_type", "expected"), [("mps", torch.float32), ("cpu", torch.bfloat16)])
+def test_gguf_loader_dequantizes_to_the_dtype_denoise_feeds_it(monkeypatch, tmp_path, device_type, expected) -> None:
+ """Denoise picks its inference dtype from the same policy; a GGUF loader that disagrees breaks every matmul."""
+ config = Main_GGUF_Krea2_Config.model_construct(path=str(tmp_path / "krea2.gguf"), variant=Krea2VariantType.Turbo)
+ compute_dtypes: list[torch.dtype] = []
+
+ class _Stop(Exception):
+ pass
+
+ def _record(_path, *, compute_dtype, **_kwargs):
+ compute_dtypes.append(compute_dtype)
+ raise _Stop
+
+ monkeypatch.setattr("invokeai.backend.model_manager.load.model_loaders.krea2.gguf_sd_loader", _record)
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",
+ lambda: torch.device(device_type),
+ )
+ monkeypatch.setattr(
+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",
+ lambda _device: torch.bfloat16,
+ )
+
+ with pytest.raises(_Stop):
+ object.__new__(Krea2GGUFCheckpointModel)._load_from_gguf(config)
+
+ assert compute_dtypes == [expected]
+
+
def _gguf_driver(monkeypatch, path, model_class):
import diffusers
diff --git a/tests/backend/util/test_devices.py b/tests/backend/util/test_devices.py
index baf571bf60..e95c0c56fc 100644
--- a/tests/backend/util/test_devices.py
+++ b/tests/backend/util/test_devices.py
@@ -1142,3 +1142,23 @@ def test_naming_the_igpu_beside_a_radeon_on_windows_rocm_is_refused():
)
def test_an_explicit_device_is_kept_unless_it_is_that_igpu(integrated_map, requested, platform, hip):
assert _explicit_cuda_devices(integrated_map, requested, platform, hip) == [torch.device(requested[0])]
+
+
+# ===== choose_krea2_transformer_dtype ============
+
+
[email protected]("precision", ["auto", "float16", "bfloat16"])
+def test_choose_krea2_transformer_dtype_runs_gguf_on_mps_in_float32(monkeypatch, precision):
+ monkeypatch.setattr(get_config(), "precision", precision)
+ assert TorchDevice.choose_krea2_transformer_dtype(is_gguf=True, device=torch.device("mps")) is torch.float32
+
+
[email protected](("is_gguf", "device_type"), [(False, "mps"), (True, "cpu"), (True, "cuda"), (False, "cuda")])
[email protected]("precision", ["auto", "float16", "float32"])
+def test_choose_krea2_transformer_dtype_otherwise_ignores_precision(monkeypatch, is_gguf, device_type, precision):
+ """The loader and denoise both ask this; precision must not split them (Krea-2 text encoding ignores it too)."""
+ monkeypatch.setattr(get_config(), "precision", precision)
+ device = torch.device(device_type)
+ with patch.object(TorchDevice, "choose_bfloat16_safe_dtype", return_value=torch.bfloat16) as mock_safe:
+ assert TorchDevice.choose_krea2_transformer_dtype(is_gguf=is_gguf, device=device) is torch.bfloat16
+ mock_safe.assert_called_once_with(device)