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(krea2): hold RMSNorm weights in fp32 for GGUF and single-file loads (#10318)
Lincoln Steina04b25f3e934
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex dfd61944b4..c85ad461fd 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -65,6 +65,7 @@ from invokeai.backend.quantization.fp8_scaled import (strip_layer_path_prefix,warn_on_unattached_scales,)+from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensorfrom invokeai.backend.quantization.gguf.loaders import gguf_sd_loaderfrom invokeai.backend.quantization.int8_convrot import (drop_unconsumed_quantization_sidecars,@@ -131,6 +132,45 @@ def _int4_int8_split(markers: dict[str, dict[str, Any]]) -> str:return f"{int4} int4, {len(markers) - int4} int8"+def _keep_rms_norms_in_fp32(model: torch.nn.Module) -> None:+ """Hold every `Krea2RMSNorm` weight in float32, as diffusers' `_keep_in_fp32_modules` does on a folder load.++ The norm upcasts its input to float32; a bf16 weight there both rounds `1 + weight` and makes torch skip the fused+ rms_norm kernel for the dtype mismatch (#10117). A GGUF stores these unquantized, so they are taken as stored+ rather than through the bf16 compute dtype.+ """+ from diffusers.models.transformers.transformer_krea2 import Krea2RMSNorm++ for module in model.modules():+ if not isinstance(module, Krea2RMSNorm):+ continue+ weight = module.weight+ if isinstance(weight, GGMLTensor):+ stored = weight.quantized_data+ weight = (+ stored+ if stored.is_floating_point() and stored.shape == weight.shape+ else weight.get_dequantized_tensor()+ )+ module.weight = torch.nn.Parameter(weight.detach().to(torch.float32), requires_grad=False)+++def _stored_rms_norm_weights(model: torch.nn.Module, sd: dict[str, Any], dtype: torch.dtype) -> dict[str, torch.Tensor]:+ """Float32 copies of the `Krea2RMSNorm` weights in `sd` that a cast to `dtype` would round: 16- or 32-bit floats of+ another dtype. Copies, because an mmap-backed view would pin the whole checkpoint file for the model's lifetime."""+ from diffusers.models.transformers.transformer_krea2 import Krea2RMSNorm++ keys = (f"{name}.weight" for name, module in model.named_modules() if isinstance(module, Krea2RMSNorm))+ return {+ key: tensor.to(torch.float32, copy=True)+ for key in keys+ if isinstance(tensor := sd.get(key), torch.Tensor)+ and tensor.is_floating_point()+ and tensor.element_size() >= 2+ and tensor.dtype != dtype+ }++def _is_native_krea2_format(sd: dict[str, Any]) -> bool:"""Detect the native/ComfyUI Krea-2 key naming (e.g. GGUF) vs. the diffusers naming."""return any(@@ -655,6 +695,9 @@ class Krea2CheckpointModel(ModelLoader):modules = {name for name, _ in model.named_children()}nvfp4_payloads = {path: payload for path, payload in nvfp4_payloads.items() if path.split(".", 1)[0] in modules}nvfp4_bytes = predict_nvfp4_install_size(model, nvfp4_payloads, model_dtype, skip_patterns)+ # The casts below round every float to `model_dtype` before `_keep_rms_norms_in_fp32` widens the norms, so+ # hold back their stored copies or they arrive rounded (#10117). They are vectors; no reservation needed.+ stored_norms = _stored_rms_norm_weights(model, sd, model_dtype)if int8_markers:# A merged file's bundled submodels are in `sd` too -- this loader does not@@ -724,6 +767,7 @@ class Krea2CheckpointModel(ModelLoader):packed = install_nvfp4_layers(model, sd, nvfp4_payloads, model_dtype, skip_patterns)self._logger.info(f"Krea-2: kept {packed} of {len(nvfp4_payloads)} nvfp4 layer(s) packed.")+ sd.update(stored_norms)load_state_dict_ignoring_extras(model, sd, source="Krea-2 single-file checkpoint", assign=True, allow_missing=True)@@ -776,8 +820,10 @@ class Krea2CheckpointModel(ModelLoader):# The layerwise-casting path exists to *produce* fp8 weights from full-precision ones. The# checkpoint already is fp8, and its hooks would cast back to the compute dtype without# applying weight_scale, so it must not run here.+ _keep_rms_norms_in_fp32(model)return model+ _keep_rms_norms_in_fp32(model)# Honor the fp8-storage setting (re-quantizes the dequantized weights to fp8-resident on CUDA).model = self._apply_fp8_layerwise_casting(model, config, SubModelType.Transformer)return model@@ -860,6 +906,7 @@ class Krea2GGUFCheckpointModel(ModelLoader):# ComfyUI GGUFs may use key names needing conversion). Failing here beats a confusing meta-tensor# crash mid-inference._reject_incomplete_load(model, what="Krea-2 GGUF checkpoint")+ _keep_rms_norms_in_fp32(model)return modeldiff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex daa2c3037f..686e8dfbc5 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -1095,6 +1095,92 @@ def test_an_nvfp4_layer_missing_its_global_scale_is_refused_before_the_cache_is_assert run.reserved == []+def test_gguf_loader_holds_rms_norm_weights_in_fp32_as_stored(monkeypatch, tmp_path) -> None:+ """#10117: a bf16 norm weight against Krea2RMSNorm's float32 input rounds `1 + weight` and skips the fused kernel."""+ import gguf+ from diffusers.models.transformers.transformer_krea2 import Krea2RMSNorm++ from invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor++ class _NormHost(torch.nn.Module):+ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.norm = Krea2RMSNorm(4)++ stored = torch.tensor([0.1234567, -0.0101, 0.5, 3e-4]) # not representable in bf16+ checkpoint_path = tmp_path / "krea2.gguf"+ loader, config = _gguf_driver(monkeypatch, checkpoint_path, _NormHost)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_krea2_transformer_dtype",+ lambda **_kwargs: torch.bfloat16,+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.gguf_sd_loader",+ lambda _path, *, compute_dtype, **_kwargs: {+ "norm.weight": GGMLTensor(+ stored.clone(),+ ggml_quantization_type=gguf.GGMLQuantizationType.F32,+ tensor_shape=stored.shape,+ compute_dtype=compute_dtype,+ )+ },+ )++ model = loader._load_from_gguf(config)++ assert type(model.norm.weight.data) is torch.Tensor+ assert model.norm.weight.dtype == torch.float32+ assert torch.equal(model.norm.weight.data, stored)++[email protected]("stored_dtype", [torch.float32, torch.float16], ids=["fp32", "fp16"])+def test_single_file_loader_holds_rms_norm_weights_in_fp32_as_stored(monkeypatch, tmp_path, stored_dtype) -> None:+ """#10117: the bf16 state-dict cast must not round a norm weight before it is widened to float32."""+ import diffusers+ from diffusers.models.transformers.transformer_krea2 import Krea2RMSNorm++ class _NormHost(torch.nn.Module):+ def __init__(self, **_kwargs) -> None:+ super().__init__()+ self.norm = Krea2RMSNorm(4)+ self.proj = torch.nn.Linear(4, 4, bias=False)++ stored = torch.tensor([0.1234567, -0.0101, 0.5, 3e-4]).to(stored_dtype) # not representable in bf16+ assert not torch.equal(stored.to(torch.bfloat16).to(stored_dtype), stored)+ served_norm = stored.clone()+ checkpoint_path = tmp_path / "krea2.safetensors"+ checkpoint_path.touch()+ config = Main_Checkpoint_Krea2_Config.model_construct(+ path=str(checkpoint_path), variant=Krea2VariantType.Turbo, fp8_storage=None+ )+ loader = object.__new__(Krea2CheckpointModel)+ loader._ram_cache = SimpleNamespace(make_room=MagicMock())+ loader._logger = MagicMock()+ loader._torch_device = torch.device("cpu")+ loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: model+ monkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _NormHost, raising=False)+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.load_safetensors_checkpoint",+ served_checkpoint({"norm.weight": served_norm, "proj.weight": torch.ones(4, 4, dtype=stored_dtype)}),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_torch_device",+ lambda: torch.device("cpu"),+ )+ monkeypatch.setattr(+ "invokeai.backend.model_manager.load.model_loaders.krea2.TorchDevice.choose_bfloat16_safe_dtype",+ lambda _device: torch.bfloat16,+ )++ model = loader._load_from_singlefile(config)++ assert model.norm.weight.dtype == torch.float32+ assert torch.equal(model.norm.weight.data, stored.to(torch.float32))+ assert model.proj.weight.dtype == torch.bfloat16+ # A checkpoint tensor is an mmap view of the file; keeping it would pin the file for the model's lifetime.+ assert model.norm.weight.untyped_storage().data_ptr() != served_norm.untyped_storage().data_ptr()++@pytest.mark.parametrize("prefix", ["", "model.diffusion_model."], ids=["bare", "comfyui-prefixed"])def test_the_final_layers_the_conversion_discards_are_never_read(monkeypatch, tmp_path, prefix: str) -> None:"""`last.up` and `last.down` of a native checkpoint have no module in the diffusers model. Read through ``pread``