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
perf(tests): stop materializing model-sized tensors in probe tests
Alexander Eichhorn7f3326a13ffd
diff --git a/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.py b/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.pyindex c8481978f8..d1cd35237d 100644--- a/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.py+++ b/tests/backend/model_manager/configs/test_minimax_h3_lora_probe_independence.py@@ -25,6 +25,15 @@ from invokeai.backend.model_manager.configs.lora import (from invokeai.backend.model_manager.taxonomy import BaseModelType+def _z(*shape: int) -> torch.Tensor:+ """A zero tensor with the real layout but a single element of storage.++ The probes under test read key names and shapes, never an element. Materializing these LoRA+ widths costs GBs across the file, which parallel CI test processes cannot hold at once.+ """+ return torch.zeros((), dtype=torch.float32).expand(shape)++def _make_mod(path: Path, sd: dict) -> MagicMock:mod = MagicMock()mod.path = path@@ -64,20 +73,20 @@ def _h3_turbo_keys(prefix: str = "") -> dict[str, torch.Tensor]:sd: dict[str, torch.Tensor] = {}for block in range(2):base = f"{prefix}blocks.{block}"- sd[f"{base}.attn.qkv_proj.lora_A.weight"] = torch.zeros(64, 5376)- sd[f"{base}.attn.qkv_proj.lora_B.weight"] = torch.zeros(3 * 5376, 64)- sd[f"{base}.attn.out_proj.lora_A.weight"] = torch.zeros(64, 7168)- sd[f"{base}.attn.out_proj.lora_B.weight"] = torch.zeros(5376, 64)- sd[f"{base}.mlp.fc1.lora_A.weight"] = torch.zeros(64, 5376)- sd[f"{base}.mlp.fc1.lora_B.weight"] = torch.zeros(2 * 14336, 64)- sd[f"{base}.mlp.fc2.lora_A.weight"] = torch.zeros(64, 14336)- sd[f"{base}.mlp.fc2.lora_B.weight"] = torch.zeros(5376, 64)- sd[f"{base}.adaln_proj.linear.lora_A.weight"] = torch.zeros(16, 2688)- sd[f"{base}.adaln_proj.linear.lora_B.weight"] = torch.zeros(96768, 16)- sd[f"{prefix}token_refiner.blocks.0.attn.qkv_proj.lora_A.weight"] = torch.zeros(64, 5376)- sd[f"{prefix}token_refiner.blocks.0.attn.qkv_proj.lora_B.weight"] = torch.zeros(3 * 5376, 64)- sd[f"{prefix}final_layer.adaln_proj.linear.lora_A.weight"] = torch.zeros(16, 2688)- sd[f"{prefix}final_layer.adaln_proj.linear.lora_B.weight"] = torch.zeros(10752, 16)+ sd[f"{base}.attn.qkv_proj.lora_A.weight"] = _z(64, 5376)+ sd[f"{base}.attn.qkv_proj.lora_B.weight"] = _z(3 * 5376, 64)+ sd[f"{base}.attn.out_proj.lora_A.weight"] = _z(64, 7168)+ sd[f"{base}.attn.out_proj.lora_B.weight"] = _z(5376, 64)+ sd[f"{base}.mlp.fc1.lora_A.weight"] = _z(64, 5376)+ sd[f"{base}.mlp.fc1.lora_B.weight"] = _z(2 * 14336, 64)+ sd[f"{base}.mlp.fc2.lora_A.weight"] = _z(64, 14336)+ sd[f"{base}.mlp.fc2.lora_B.weight"] = _z(5376, 64)+ sd[f"{base}.adaln_proj.linear.lora_A.weight"] = _z(16, 2688)+ sd[f"{base}.adaln_proj.linear.lora_B.weight"] = _z(96768, 16)+ sd[f"{prefix}token_refiner.blocks.0.attn.qkv_proj.lora_A.weight"] = _z(64, 5376)+ sd[f"{prefix}token_refiner.blocks.0.attn.qkv_proj.lora_B.weight"] = _z(3 * 5376, 64)+ sd[f"{prefix}final_layer.adaln_proj.linear.lora_A.weight"] = _z(16, 2688)+ sd[f"{prefix}final_layer.adaln_proj.linear.lora_B.weight"] = _z(10752, 16)return sd@@ -87,18 +96,18 @@ def _wan_native_keys() -> dict[str, torch.Tensor]:for sub in ("self_attn", "cross_attn"):for proj in ("q", "k", "v", "o"):base = f"diffusion_model.blocks.{block}.{sub}.{proj}"- sd[f"{base}.lora_down.weight"] = torch.zeros(64, 5120)- sd[f"{base}.lora_up.weight"] = torch.zeros(5120, 64)+ sd[f"{base}.lora_down.weight"] = _z(64, 5120)+ sd[f"{base}.lora_up.weight"] = _z(5120, 64)return sddef _anima_kohya_keys() -> dict[str, torch.Tensor]:sd: dict[str, torch.Tensor] = {}for block in range(2):- sd[f"lora_unet_blocks_{block}_cross_attn_q_proj.lora_down.weight"] = torch.zeros(16, 2048)- sd[f"lora_unet_blocks_{block}_cross_attn_q_proj.lora_up.weight"] = torch.zeros(2048, 16)- sd[f"lora_unet_blocks_{block}_mlp_layer1.lora_down.weight"] = torch.zeros(16, 2048)- sd[f"lora_unet_blocks_{block}_mlp_layer1.lora_up.weight"] = torch.zeros(8192, 16)+ sd[f"lora_unet_blocks_{block}_cross_attn_q_proj.lora_down.weight"] = _z(16, 2048)+ sd[f"lora_unet_blocks_{block}_cross_attn_q_proj.lora_up.weight"] = _z(2048, 16)+ sd[f"lora_unet_blocks_{block}_mlp_layer1.lora_down.weight"] = _z(16, 2048)+ sd[f"lora_unet_blocks_{block}_mlp_layer1.lora_up.weight"] = _z(8192, 16)return sd@@ -135,8 +144,8 @@ def test_anima_lora_rejected_by_h3_probe():def test_h3_probe_requires_lora_suffixes():# A base-model checkpoint fragment (plain weights, no LoRA suffixes) must not probe as a LoRA.sd = {- "blocks.0.attn.qkv_proj.weight": torch.zeros(3 * 5376, 5376),- "blocks.0.adaln_proj.linear.weight": torch.zeros(96768, 2688),+ "blocks.0.attn.qkv_proj.weight": _z(3 * 5376, 5376),+ "blocks.0.adaln_proj.linear.weight": _z(96768, 2688),}accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)assert not accepted, f"H3 probe wrongly accepted a non-LoRA state dict: {result}"@@ -146,14 +155,14 @@ def test_h3_probe_rejects_lycoris_variants():# LoKR/LoHA/DoRA cannot be applied across H3's fused qkv/SwiGLU tensors — admitting them# would install a model that crashes (or silently corrupts) at generation time.lokr = {- "blocks.0.attn.qkv_proj.lokr_w1": torch.zeros(64, 64),- "blocks.0.attn.qkv_proj.lokr_w2": torch.zeros(252, 84),+ "blocks.0.attn.qkv_proj.lokr_w1": _z(64, 64),+ "blocks.0.attn.qkv_proj.lokr_w2": _z(252, 84),}accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, lokr)assert not accepted, f"H3 probe wrongly accepted a LoKR file: {result}"dora = _h3_turbo_keys()- dora["blocks.0.attn.qkv_proj.dora_scale"] = torch.zeros(3 * 5376, 1)+ dora["blocks.0.attn.qkv_proj.dora_scale"] = _z(3 * 5376, 1)accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, dora)assert not accepted, f"H3 probe wrongly accepted a DoRA file: {result}"@@ -171,8 +180,8 @@ def test_h3_probe_rejects_already_diffusers_keys():# v1 supports the published native layout only; diffusers-style transformer_blocks keys# are deliberately rejected rather than half-converted.sd = {- "transformer_blocks.0.attn.to_q.lora_A.weight": torch.zeros(64, 5376),- "transformer_blocks.0.attn.to_q.lora_B.weight": torch.zeros(5376, 64),+ "transformer_blocks.0.attn.to_q.lora_A.weight": _z(64, 5376),+ "transformer_blocks.0.attn.to_q.lora_B.weight": _z(5376, 64),}accepted, result = _probe(LoRA_LyCORIS_MiniMaxH3_Config, sd)assert not accepted, f"H3 probe wrongly accepted diffusers-naming keys: {result}"diff --git a/tests/backend/model_manager/configs/test_wan_checkpoint_config.py b/tests/backend/model_manager/configs/test_wan_checkpoint_config.pyindex 67d4f887eb..ed18f655cb 100644--- a/tests/backend/model_manager/configs/test_wan_checkpoint_config.py+++ b/tests/backend/model_manager/configs/test_wan_checkpoint_config.py@@ -28,7 +28,19 @@ TI2V_DIM = 3072def _t(*shape: int, dtype: torch.dtype = torch.bfloat16) -> torch.Tensor:- return torch.zeros(shape, dtype=dtype)+ """A tensor with the real layout but a single element of storage.++ The probe classifies Wan checkpoints by shape and dtype -- the width separates A14B from+ TI2V -- and `_make_mod` hands the dict over without serializing it, so nothing needs real+ zeros at these widths. Materializing them costs ~5GB per run, which several CI test+ processes cannot afford at once, so one element is expanded to the full shape instead.+ """+ return torch.zeros((), dtype=dtype).expand(shape)+++def _for_saving(sd: dict) -> dict:+ """Materializes `_t`'s expanded views; safetensors rejects non-contiguous tensors."""+ return {key: value.contiguous() for key, value in sd.items()}def _native_sd(in_channels: int = 16, dim: int = A14B_DIM, prefix: str = "") -> dict:@@ -303,7 +315,7 @@ class TestEndToEndIdentification:from safetensors.torch import save_filepath = tmp_path / filename- save_file(sd, path)+ save_file(_for_saving(sd), path)return path@pytest.mark.parametrize(@@ -479,7 +491,7 @@ class TestExpertFilenameHeuristic:# A name with no marker at all, so only the metadata can settle the expert.path = tmp_path / "my-wan-model.safetensors"- save_file(_native_sd(36), path, metadata={k: str(v) for k, v in declared.items()})+ save_file(_for_saving(_native_sd(36)), path, metadata={k: str(v) for k, v in declared.items()})config = Main_Checkpoint_Wan_Config.from_model_on_disk(ModelOnDisk(path), _build_overrides(path, path.stem))assert config.expert == expected@@ -491,7 +503,7 @@ class TestExpertFilenameHeuristic:from safetensors.torch import save_filepath = tmp_path / "Wan2.2-A14B-I2V-high_noise.safetensors"- save_file(_native_sd(36), path, metadata={"model_type": "Wan22-I2V-A14B-low"})+ save_file(_for_saving(_native_sd(36)), path, metadata={"model_type": "Wan22-I2V-A14B-low"})config = Main_Checkpoint_Wan_Config.from_model_on_disk(ModelOnDisk(path), _build_overrides(path, path.stem))assert config.expert == "high"diff --git a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.pyindex 05f7c597e8..cd0412f9b1 100644--- a/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py+++ b/tests/backend/model_manager/load/test_anima_scaled_fp8_keys.py@@ -36,6 +36,15 @@ from tests.backend.model_manager.load.state_dicts.anima_transformer_scaled_fp8_k_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16, "U8": torch.uint8}+def _capped(shape: list[int]) -> list[int]:+ """Token extents for a captured layout.++ Only key names, dtypes, values and rank are asserted here, never a size, so the real extents+ buy nothing and cost GBs -- more than parallel CI test processes can hold at once.+ """+ return [min(extent, 4) for extent in shape]++def _build_state_dict() -> dict[str, torch.Tensor]:"""Rebuild the checkpoint. `comfy_quant` markers are real JSON blobs, not placeholders.@@ -52,12 +61,12 @@ def _build_state_dict() -> dict[str, torch.Tensor]:# parses the blob. Python's `False` would not parse and the flag would vanish.sd[key] = torch.frombuffer(bytearray(json.dumps(blob).encode()), dtype=torch.uint8).clone()elif torch_dtype is FP8_DTYPE:- sd[key] = torch.zeros(shape, dtype=torch.float32).to(FP8_DTYPE)+ sd[key] = torch.zeros(_capped(shape), dtype=FP8_DTYPE)elif key.endswith((".weight_scale", ".input_scale")):# 1.0 is the placeholder `_usable_input_scale` rejects, so it must not be used here.- sd[key] = torch.full(shape, 2.5, dtype=torch_dtype)+ sd[key] = torch.full(_capped(shape), 2.5, dtype=torch_dtype)else:- sd[key] = torch.zeros(shape, dtype=torch_dtype)+ sd[key] = torch.zeros(_capped(shape), dtype=torch_dtype)return _filter_non_model_keys(_strip_anima_bundle_prefix(sd))diff --git a/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.pyindex 5dba27a672..98abe792e3 100644--- a/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py+++ b/tests/backend/model_manager/load/test_flux1_scaled_fp8_keys.py@@ -25,18 +25,27 @@ from tests.backend.model_manager.load.state_dicts.flux1_transformer_scaled_fp8_k_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}+def _capped(shape: list[int]) -> list[int]:+ """Token extents for a captured layout.++ Only key names, dtypes, values and rank are asserted here, never a size, so the real extents+ buy nothing and cost GBs -- more than parallel CI test processes can hold at once.+ """+ return [min(extent, 4) for extent in shape]++def _build_state_dict() -> dict[str, torch.Tensor]:sd: dict[str, torch.Tensor] = {}for key, (shape, dtype) in scaled_keys.items():torch_dtype = _DTYPES[dtype]if torch_dtype is FP8_DTYPE:- sd[key] = torch.zeros(shape, dtype=torch.float32).to(FP8_DTYPE)+ sd[key] = torch.zeros(_capped(shape), dtype=FP8_DTYPE)elif key.endswith((".scale_weight", ".scale_input")):# Real checkpoints carry calibrated scales; 1.0 is the placeholder value that# `_usable_input_scale` deliberately rejects, so it must not be used here.- sd[key] = torch.full(shape, 2.5, dtype=torch_dtype)+ sd[key] = torch.full(_capped(shape), 2.5, dtype=torch_dtype)else:- sd[key] = torch.zeros(shape, dtype=torch_dtype)+ sd[key] = torch.zeros(_capped(shape), dtype=torch_dtype)return sddiff --git a/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py b/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.pyindex 1ab3165eb6..9653c5fe6a 100644--- a/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py+++ b/tests/backend/model_manager/load/test_flux2_fp8mixed_keys.py@@ -21,12 +21,20 @@ SCALE_VALUE = 0.25def _mock_state_dict() -> dict[str, torch.Tensor]:+ """Builds the captured layout at a token size.++ The assertions below read key names, dtypes, values and -- in one case -- rank; none reads an+ extent. Materializing the real extents means 2.3 billion elements, which peaks at ~15GB per+ call and cannot be afforded once CI runs several test processes at once, so every dimension is+ capped while rank and dtype are kept exactly as captured.+ """sd: dict[str, torch.Tensor] = {}for key, (shape, dtype) in mixed_keys.items():if key.endswith((".weight_scale", ".input_scale")):sd[key] = torch.tensor(SCALE_VALUE, dtype=torch.float32)else:- sd[key] = torch.ones(shape, dtype=torch.float32).to(_DTYPES[dtype])+ token_shape = [min(extent, 4) for extent in shape]+ sd[key] = torch.ones(token_shape, dtype=_DTYPES[dtype])return sddiff --git a/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py b/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.pyindex 2665255e6d..2d02104012 100644--- a/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py+++ b/tests/backend/model_manager/load/test_z_image_scaled_fp8_keys.py@@ -24,13 +24,22 @@ from tests.backend.model_manager.load.state_dicts.z_image_transformer_scaled_fp8_DTYPES = {"F8_E4M3": FP8_DTYPE, "F32": torch.float32, "BF16": torch.bfloat16}+def _capped(shape: list[int]) -> list[int]:+ """Token extents for a captured layout.++ Only key names, dtypes, values and rank are asserted here, never a size, so the real extents+ buy nothing and cost GBs -- more than parallel CI test processes can hold at once.+ """+ return [min(extent, 4) for extent in shape]++def _mock_state_dict(scale_value: float = 4.0) -> dict[str, torch.Tensor]:sd: dict[str, torch.Tensor] = {}for key, (shape, dtype) in scaled_keys.items():if key.endswith(".scale_weight"):- sd[key] = torch.full(shape, scale_value, dtype=torch.float32)+ sd[key] = torch.full(_capped(shape), scale_value, dtype=torch.float32)else:- sd[key] = torch.ones(shape, dtype=torch.float32).to(_DTYPES[dtype])+ sd[key] = torch.ones(_capped(shape), dtype=_DTYPES[dtype])return sd