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
test(fp8): verify LoRA sidecar patching over fp8 weights, harden metadata read
Alexander Eichhornefdf552b21fc
diff --git a/invokeai/backend/model_manager/load/model_loaders/krea2.py b/invokeai/backend/model_manager/load/model_loaders/krea2.pyindex 47fb401e06..730c5d0c29 100644--- a/invokeai/backend/model_manager/load/model_loaders/krea2.py+++ b/invokeai/backend/model_manager/load/model_loaders/krea2.py@@ -120,6 +120,24 @@ def _dequantize_scaled_fp8(sd: dict[str, Any]) -> dict[str, Any]:return out+def _read_safetensors_metadata(path: Path, logger: Any = None) -> dict[str, str] | None:+ """Read the safetensors header metadata, or None if it cannot be read.++ Only used to enrich fp8 handling (per-layer ``full_precision_matrix_mult`` hints), so an+ unreadable header must not fail the model load. It is warned about rather than swallowed: without+ the hints, layers the quantizer marked as unsafe would silently be multiplied in fp8.+ """+ try:+ from safetensors import safe_open++ with safe_open(path, framework="pt") as f:+ return f.metadata()+ except Exception as e:+ if logger is not None:+ logger.warning(f"Could not read safetensors metadata from {path.name} ({e}); fp8 layer hints unavailable.")+ return None++def _remap_native_layer_paths(layer_names: Any) -> dict[str, str]:"""Map native/ComfyUI layer paths to their diffusers equivalents.@@ -364,11 +382,8 @@ class Krea2CheckpointModel(ModelLoader):raise TypeError(f"Expected Main_Checkpoint_Krea2_Config, got {type(config).__name__}.")model_path = Path(config.path)- from safetensors import safe_open-sd = load_file(model_path)- with safe_open(model_path, framework="pt") as f:- metadata = f.metadata()+ metadata = _read_safetensors_metadata(model_path, self._logger)sd = _strip_comfyui_prefix(sd)# Native/ComfyUI key naming → diffusers Krea2Transformer2DModel keys. Done *before* the fp8# scales are pulled out: the renames are substring-based on ".weight", so a siblingdiff --git a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py b/tests/backend/model_manager/load/test_krea2_loader_boundaries.pyindex ba618ab03b..90eed6cbdb 100644--- a/tests/backend/model_manager/load/test_krea2_loader_boundaries.py+++ b/tests/backend/model_manager/load/test_krea2_loader_boundaries.py@@ -36,6 +36,8 @@ def test_single_file_loader_constructs_and_materializes_model(monkeypatch, tmp_pram_cache = SimpleNamespace(make_room=MagicMock())loader = object.__new__(Krea2CheckpointModel)loader._ram_cache = ram_cache+ # ModelLoader.__init__ always sets a logger; this test bypasses __init__, so supply one.+ loader._logger = MagicMock()loader._apply_fp8_layerwise_casting = lambda model, _config, _submodel: modelmonkeypatch.setattr(diffusers, "Krea2Transformer2DModel", _TinyKrea2Transformer, raising=False)diff --git a/tests/backend/quantization/test_fp8_scaled.py b/tests/backend/quantization/test_fp8_scaled.pyindex fa5ff88728..15e2ef1492 100644--- a/tests/backend/quantization/test_fp8_scaled.py+++ b/tests/backend/quantization/test_fp8_scaled.py@@ -269,6 +269,45 @@ class TestCustomLinearIntegration:finally:set_fp8_matmul_enabled(False)+ @cuda_fp8+ def test_sidecar_patched_fp8_layer_uses_the_fp8_matmul(self):+ """LoRAs on fp8 weights are force-routed to sidecar patching (layer_patcher), and the+ sidecar wrapper calls `_autocast_forward`. The fp8 branch must survive that route, and the+ LoRA residual must still be added on top."""+ from invokeai.backend.patches.layers.lora_layer import LoRALayer++ dev = torch.device("cuda")+ model = self._module(dev)+ custom = model[0]+ rank = 8+ lora = LoRALayer(+ up=torch.randn(custom.out_features, rank, device=dev, dtype=torch.bfloat16) * 0.05,+ mid=None,+ down=torch.randn(rank, custom.in_features, device=dev, dtype=torch.bfloat16) * 0.05,+ alpha=float(rank),+ bias=None,+ )+ custom.add_patch(lora, 1.0)+ x = torch.randn(32, 64, device=dev, dtype=torch.bfloat16)++ set_fp8_matmul_enabled(True)+ try:+ patched = model(x)+ finally:+ set_fp8_matmul_enabled(False)+ unpatched_ref = torch.nn.functional.linear(+ x, dequantize_weight(custom.weight, custom.weight_scale, torch.bfloat16)+ )++ assert patched.shape == (32, 128)+ # The patch must actually change the output...+ assert not torch.allclose(patched, unpatched_ref, atol=1e-2)+ # ...and the base contribution must still be roughly the fp8 linear, not garbage.+ residual = (lora.get_weight(1.0) * lora.scale()).to(torch.bfloat16)+ expected = unpatched_ref + torch.nn.functional.linear(x, residual)+ rel = ((patched.float() - expected.float()).norm() / expected.float().norm()).item()+ assert rel < 0.1, f"sidecar-patched fp8 output diverges by {rel:.4f}"+@cuda_fp8def test_unaligned_features_fall_back(self):set_fp8_matmul_enabled(True)