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(ernie-image): stop warning about a missing scheduler for GGUF files
Alexander Eichhorn4aa87f57a1c4
diff --git a/invokeai/app/invocations/ernie_image/ernie_image_denoise.py b/invokeai/app/invocations/ernie_image/ernie_image_denoise.pyindex cbe0dc8d63..ae8b8e4f58 100644--- a/invokeai/app/invocations/ernie_image/ernie_image_denoise.py+++ b/invokeai/app/invocations/ernie_image/ernie_image_denoise.py@@ -232,12 +232,12 @@ class ErnieImageDenoiseInvocation(BaseInvocation):model_path = (context.config.get().models_path / config.path).resolve()scheduler_dir = model_path / "scheduler"if not scheduler_dir.is_dir():- # A single-file checkpoint has no `scheduler/` by construction -- `config.path` is the- # file itself -- so there is nothing to read and nothing worth warning about. What+ # A single file (safetensors or GGUF) has no `scheduler/` by construction -- `config.path`+ # is the file itself -- so only a Diffusers folder missing one is worth warning about. What# matters is the value: both released pipelines ship `shift=4.0`, and the driver hands# the scheduler raw sigmas expecting it to apply that shift, so default-constructing# would silently denoise on the unshifted schedule. Turbo feels it worst at 8 steps.- if config.format is not ModelFormat.Checkpoint:+ if config.format is ModelFormat.Diffusers:context.logger.warning(f"No scheduler config found at {scheduler_dir}; using {scheduler_cls.__name__} "f"with the released ERNIE-Image shift={ERNIE_IMAGE_SHIFT}."diff --git a/tests/app/invocations/test_ernie_image_scheduler.py b/tests/app/invocations/test_ernie_image_scheduler.pyindex 3cebf992f7..7baa784407 100644--- a/tests/app/invocations/test_ernie_image_scheduler.py+++ b/tests/app/invocations/test_ernie_image_scheduler.py@@ -39,10 +39,14 @@ def test_the_released_shift_is_what_we_carry() -> None:assert ERNIE_IMAGE_SHIFT == RELEASED_SHIFT-def test_a_single_file_denoises_on_the_released_schedule(tmp_path: Path) -> None:- """No `scheduler/` exists for a checkpoint, so this is every single-file generation."""- (tmp_path / "ernie-image.safetensors").touch()- context = _context(ModelFormat.Checkpoint, tmp_path, "ernie-image.safetensors")+ ("format", "filename"),+ [(ModelFormat.Checkpoint, "ernie-image.safetensors"), (ModelFormat.GGUFQuantized, "ernie-image-Q4_K_M.gguf")],+)+def test_a_single_file_denoises_on_the_released_schedule(tmp_path: Path, format: ModelFormat, filename: str) -> None:+ """No `scheduler/` exists for a single file, so this is every safetensors and GGUF generation."""+ (tmp_path / filename).touch()+ context = _context(format, tmp_path, filename)scheduler = _node()._build_scheduler(context) # type: ignore[arg-type]diff --git a/tests/backend/model_manager/load/ernie_image_gguf_fixture.py b/tests/backend/model_manager/load/ernie_image_gguf_fixture.pyindex 9fe9583669..a7ef278a6e 100644--- a/tests/backend/model_manager/load/ernie_image_gguf_fixture.py+++ b/tests/backend/model_manager/load/ernie_image_gguf_fixture.py@@ -10,6 +10,7 @@ here is told to use one of those.from pathlib import Pathimport gguf+import numpy as npimport torchfrom gguf.quants import dequantize, quantize@@ -30,6 +31,30 @@ TINY_CONFIG = {"qk_layernorm": True,}+# The published builds are K-quants, whose 256-element super-blocks the 64-wide config cannot hold: every quantized+# Linear input here is a multiple of 256 (`text_in_dim` differs from `hidden_size` so `text_proj` stays a Linear).+K_QUANT_CONFIG = {+ **TINY_CONFIG,+ "hidden_size": 256,+ "ffn_hidden_size": 512,+ "text_in_dim": 512,+ "rope_axes_dim": (32, 48, 48),+}++# gguf-py can read K-quants but not write them. A super-block's bytes are all valid codes, so random ones with sane+# fp16 super-scales make a real Q4_K tensor; what it means comes from gguf-py's reference reader, not from us.+_Q4_K_BLOCK_BYTES = 144 # d (fp16), dmin (fp16), 12 bytes of 6-bit scales and mins, 128 bytes of 4-bit codes+_Q4_K_SUPER_SCALE = np.float16(1e-3).tobytes()+++def _random_q4_k(shape: tuple[int, ...], rng: np.random.Generator) -> np.ndarray:+ rows, cols = shape+ blocks = rng.integers(0, 256, size=(rows, cols // 256, _Q4_K_BLOCK_BYTES), dtype=np.uint8)+ blocks[..., 0:2] = np.frombuffer(_Q4_K_SUPER_SCALE, dtype=np.uint8)+ blocks[..., 2:4] = np.frombuffer(_Q4_K_SUPER_SCALE, dtype=np.uint8)+ return blocks.reshape(rows, -1)++# The six weights every unsloth release keeps in BF16 (read from the Q2_K to Q8_0 headers)._BF16 = ("x_embedder.proj.weight",@@ -47,12 +72,20 @@ def write_ernie_image_gguf(architecture: str = "wan",qtype: gguf.GGMLQuantizationType = gguf.GGMLQuantizationType.Q8_0,seed: int = 0,+ config: dict = TINY_CONFIG,) -> dict[str, torch.Tensor]:"""Write a randomly initialised tiny transformer to ``path``; return what each tensor dequantizes to."""from diffusers import ErnieImageTransformer2DModeltorch.manual_seed(seed)- model = ErnieImageTransformer2DModel(**TINY_CONFIG)+ model = ErnieImageTransformer2DModel(**config)+ # diffusers zero-initializes the adaLN modulation and the final projection (the DiT recipe), which zeroes the+ # output whatever the other weights hold, so a forward comparison would pass for any kernel. Fill them in.+ with torch.no_grad():+ for param in model.parameters():+ if not param.any():+ param.normal_(std=0.02)+ rng = np.random.default_rng(seed)writer = gguf.GGUFWriter(str(path), architecture)meant: dict[str, torch.Tensor] = {}@@ -64,11 +97,15 @@ def write_ernie_image_gguf(stored_as = qtypeelse:stored_as = gguf.GGMLQuantizationType.F32- raw = data if stored_as is gguf.GGMLQuantizationType.F32 else quantize(data, stored_as)if stored_as is gguf.GGMLQuantizationType.F32:- writer.add_tensor(name, raw)- meant[name] = torch.from_numpy(raw.copy())+ writer.add_tensor(name, data)+ meant[name] = torch.from_numpy(data.copy())else:+ raw = (+ _random_q4_k(data.shape, rng)+ if stored_as is gguf.GGMLQuantizationType.Q4_K+ else quantize(data, stored_as)+ )# `raw_shape` is the packed byte shape; gguf derives the logical one from it.writer.add_tensor(name, raw, raw_shape=raw.shape, raw_dtype=stored_as)meant[name] = torch.from_numpy(dequantize(raw, stored_as)).reshape(tensor.shape)diff --git a/tests/backend/model_manager/load/test_ernie_image_gguf_loader.py b/tests/backend/model_manager/load/test_ernie_image_gguf_loader.pyindex ae94acef4d..b7559faf86 100644--- a/tests/backend/model_manager/load/test_ernie_image_gguf_loader.py+++ b/tests/backend/model_manager/load/test_ernie_image_gguf_loader.py@@ -23,7 +23,11 @@ from invokeai.backend.model_manager.load.model_loaders.ernie_image import ErnieIfrom invokeai.backend.model_manager.model_on_disk import ModelOnDiskfrom invokeai.backend.model_manager.taxonomy import SubModelTypefrom invokeai.backend.quantization.gguf.ggml_tensor import GGMLTensor-from tests.backend.model_manager.load.ernie_image_gguf_fixture import TINY_CONFIG, write_ernie_image_gguf+from tests.backend.model_manager.load.ernie_image_gguf_fixture import (+ K_QUANT_CONFIG,+ TINY_CONFIG,+ write_ernie_image_gguf,+)from tests.fixtures.loader_seams import Seam, prepareSEAM = Seam(@@ -65,46 +69,52 @@ def test_a_safetensors_single_file_is_not_claimed_as_gguf(tmp_path: Path) -> Nonassert isinstance(result.config, Main_Checkpoint_ErnieImage_Config)-def _load(monkeypatch, tmp_path: Path, qtype: gguf.GGMLQuantizationType):+def _load(monkeypatch, tmp_path: Path, qtype: gguf.GGMLQuantizationType, geometry: dict = TINY_CONFIG):path = tmp_path / f"ernie-image-turbo-{qtype.name}.gguf"- meant = write_ernie_image_gguf(path, qtype=qtype)+ meant = write_ernie_image_gguf(path, qtype=qtype, config=geometry)config = Main_GGUF_ErnieImage_Config.model_construct(path=str(path), name="ernie-image-turbo")run = prepare(SEAM,monkeypatch,- geometry=lambda patch: patch.setattr(ernie_image, "ERNIE_IMAGE_TRANSFORMER_CONFIG", TINY_CONFIG),+ geometry=lambda patch: patch.setattr(ernie_image, "ERNIE_IMAGE_TRANSFORMER_CONFIG", geometry),)return run.load(config, SubModelType.Transformer), meant, run-def _forward(model: torch.nn.Module) -> torch.Tensor:+def _forward(model: torch.nn.Module, geometry: dict = TINY_CONFIG) -> torch.Tensor:generator = torch.Generator().manual_seed(1)with torch.no_grad():return model(- hidden_states=torch.randn(1, TINY_CONFIG["in_channels"], 2, 2, generator=generator),+ hidden_states=torch.randn(1, geometry["in_channels"], 2, 2, generator=generator),timestep=torch.tensor([500.0]),- text_bth=torch.randn(1, 3, TINY_CONFIG["text_in_dim"], generator=generator),+ text_bth=torch.randn(1, 3, geometry["text_in_dim"], generator=generator),text_lens=torch.tensor([3]),return_dict=False,)[0]@pytest.mark.parametrize(- "qtype",- [gguf.GGMLQuantizationType.Q8_0, gguf.GGMLQuantizationType.Q5_1, gguf.GGMLQuantizationType.Q4_0],- ids=lambda qtype: qtype.name,+ ("qtype", "geometry"),+ [+ (gguf.GGMLQuantizationType.Q8_0, TINY_CONFIG),+ (gguf.GGMLQuantizationType.Q5_1, TINY_CONFIG),+ (gguf.GGMLQuantizationType.Q4_0, TINY_CONFIG),+ # What the Q4_K_M starters mostly hold; its super-blocks need the 256-wide geometry.+ (gguf.GGMLQuantizationType.Q4_K, K_QUANT_CONFIG),+ ],+ ids=["Q8_0", "Q5_1", "Q4_0", "Q4_K"],)-def test_the_gguf_transformer_computes_what_its_file_means(monkeypatch, tmp_path, qtype) -> None:+def test_the_gguf_transformer_computes_what_its_file_means(monkeypatch, tmp_path, qtype, geometry) -> None:"""Not bit-exact: the torch kernels multiply codes by their fp16 block scale in fp16, the referencereader in float32. A dropped norm, an unconverted convolution or a wrong key is off by far more."""from diffusers import ErnieImageTransformer2DModel- model, meant, _ = _load(monkeypatch, tmp_path, qtype)+ model, meant, _ = _load(monkeypatch, tmp_path, qtype, geometry)apply_custom_layers_to_model(model)- reference = ErnieImageTransformer2DModel(**TINY_CONFIG)+ reference = ErnieImageTransformer2DModel(**geometry)reference.load_state_dict(meant)- assert torch.allclose(_forward(model), _forward(reference), atol=1e-3, rtol=1e-3)+ assert torch.allclose(_forward(model, geometry), _forward(reference, geometry), atol=1e-3, rtol=1e-3)def test_only_the_quantized_linears_stay_packed(monkeypatch, tmp_path) -> None: