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(app): quiet the CLIP tower load report during image indexing

Lincoln Stein0cf195ab32f2
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 969a3468b0..60cd11bd18 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -23,6 +23,7 @@ from invokeai.backend.model_manager.load.model_cache.model_cache import MODEL_LO
from invokeai.backend.model_manager.load.optimizations import skip_torch_weight_init
from invokeai.backend.model_manager.taxonomy import ModelType
from invokeai.backend.util.devices import TorchDevice
+from invokeai.backend.util.load_report import suppress_load_report
if TYPE_CHECKING:
from logging import Logger
@@ -243,6 +244,12 @@ class ImageIndexService(ImageIndexServiceBase):
self._systemic_failures = 0
self._stop_event = threading.Event()
self._backfill_pending = threading.Event()
+ # True once a backfill pass has announced itself in the log, so the pass reports its
+ # outcome exactly once however many times it is re-armed by a failed batch on the way
+ # through, paired with the size of `_failed` when it started. Written by the worker and
+ # by _launch_worker, which runs only while no worker is alive.
+ self._backfill_announced = False
+ self._backfill_failed_at_start = 0
# Set by the image-service callbacks when counts changed; the worker
# (the only emitter) turns it into one status event per sweep.
self._status_dirty = threading.Event()
@@ -610,7 +617,9 @@ class ImageIndexService(ImageIndexServiceBase):
# makes it safe, and also excludes the concurrent VRAM move whose
# load_state_dict(assign=True) would hijack these parameters onto
# the meta device. Same reasoning as ModelLoader._load_and_cache.
- with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init():
+ # suppress_load_report: the vision tower in the same checkpoint is
+ # unexpected here, by design.
+ with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init(), suppress_load_report():
model = text_cls.from_pretrained(model_path, local_files_only=True, **extra_kwargs)
except Exception as e:
# Vision-only or partial installs (e.g. the IP-Adapter image
@@ -856,6 +865,8 @@ class ImageIndexService(ImageIndexServiceBase):
invoker.services.images.on_deleted(self._on_image_deleted)
self._backfill_pending.set()
+ # A previous run stopped mid-pass leaves this set; this run's pass announces itself.
+ self._backfill_announced = False
self._stop_event.clear()
self._worker = threading.Thread(target=self._worker_loop, name="image_index_worker", daemon=True)
self._worker.start()
@@ -1056,8 +1067,16 @@ class ImageIndexService(ImageIndexServiceBase):
)
batch = [name for name in candidates if name not in self._failed][:batch_size]
if batch:
+ if not self._backfill_announced and self._announce_backfill_start():
+ self._backfill_announced = True
+ # `_failed` is cumulative over the process, so the outcome line can only
+ # speak for this pass by diffing against where it started.
+ self._backfill_failed_at_start = len(self._failed)
return batch
self._backfill_pending.clear()
+ if self._backfill_announced:
+ self._backfill_announced = False
+ self._report_backfill_outcome()
self._emit_status()
try:
@@ -1072,6 +1091,58 @@ class ImageIndexService(ImageIndexServiceBase):
break
return batch
+ def _announce_backfill_start(self) -> bool:
+ """Log that images without an embedding are being indexed. False if it could not.
+
+ This and `_report_backfill_outcome` bracket one backfill pass — work the log
+ previously showed only as a transformers load report for the encoder, with no
+ indication of what was being done or whether it worked. The pair is best-effort: a
+ pass that is stopped, or that never drains because the encoder is down, leaves the
+ start line unanswered (the outage warns on its own).
+
+ Returns whether the line was logged, so a count that could not be read leaves the
+ announcement to a later batch instead of costing this one — this runs on the path
+ that returns work, where a raise would discard the batch and reach the worker's
+ handler as an unexpected error.
+ """
+ assert self._invoker is not None
+ try:
+ status = self.get_status()
+ except Exception:
+ return False
+ if status is None:
+ return False
+ # The running encoder, not the configured name, which can be edited mid-run. The
+ # injected-encoder seam runs without a model config, and then has no name to give.
+ named = f" with embedding model '{self._model_config.name}'" if self._model_config is not None else ""
+ self._invoker.services.logger.info(f"Image index: indexing {status.pending} image(s){named}")
+ return True
+
+ def _report_backfill_outcome(self) -> None:
+ """Log the result of the backfill pass that just drained.
+
+ Reached with nothing left to embed, so the pass is over one way or the other: either
+ every eligible image has an embedding, or the rest exhausted their attempts and are
+ excluded from `pending` (which is why the pass ends rather than retrying forever).
+
+ Only failures charged during this pass are reported as its outcome. `_failed` is
+ cumulative, so reporting it whole would warn about images that retired hours ago on
+ every later pass, for the life of the process.
+ """
+ assert self._invoker is not None
+ status = self.get_status()
+ if status is None:
+ return
+ logger = self._invoker.services.logger
+ retired = len(self._failed) - self._backfill_failed_at_start
+ if retired > 0:
+ logger.warning(
+ f"Image index: indexing finished with {retired} image(s) that could not be embedded "
+ f"({status.embedded} of {status.total} indexed)"
+ )
+ else:
+ logger.info(f"Image index: indexing complete ({status.embedded} of {status.total} images indexed)")
+
def _process_batch(self, image_names: list[str]) -> bool:
"""Embed one batch. Returns False when anything in it failed."""
assert self._invoker is not None
@@ -1619,7 +1690,9 @@ class ImageIndexService(ImageIndexServiceBase):
extra_kwargs = {} if tower_config is None else {"config": tower_config}
# Process-global patch, so it needs the process-global lock —
# see _get_text_encoder for what goes wrong without it.
- with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init():
+ # suppress_load_report: the text tower in the same checkpoint is
+ # unexpected here, by design.
+ with MODEL_LOAD_LOCK.write_lock(), skip_torch_weight_init(), suppress_load_report():
model = model_cls.from_pretrained(model_path, local_files_only=True, **extra_kwargs)
model.eval()
self._cpu_model = model
diff --git a/invokeai/backend/model_manager/load/model_loaders/clip_vision.py b/invokeai/backend/model_manager/load/model_loaders/clip_vision.py
index c0ef3fc87d..dc91b5c95d 100644
--- a/invokeai/backend/model_manager/load/model_loaders/clip_vision.py
+++ b/invokeai/backend/model_manager/load/model_loaders/clip_vision.py
@@ -9,6 +9,7 @@ from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
from invokeai.backend.model_manager.util.clip_tower_config import clip_tower_config_override
+from invokeai.backend.util.load_report import suppress_load_report
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.CLIPVision, format=ModelFormat.Diffusers)
@@ -32,9 +33,12 @@ class ClipVisionLoader(ModelLoader):
# disagrees with the weights; see clip_tower_config_override.
tower_config = clip_tower_config_override(model_path, "vision")
extra_kwargs = {} if tower_config is None else {"config": tower_config}
- model = CLIPVisionModelWithProjection.from_pretrained(
- model_path, torch_dtype=self._torch_dtype, local_files_only=True, **extra_kwargs
- )
+ # A full-CLIP checkpoint carries the text tower this class does not build; see
+ # suppress_load_report.
+ with suppress_load_report():
+ model = CLIPVisionModelWithProjection.from_pretrained(
+ model_path, torch_dtype=self._torch_dtype, local_files_only=True, **extra_kwargs
+ )
assert isinstance(model, CLIPVisionModelWithProjection)
return model
diff --git a/invokeai/backend/model_manager/load/model_loaders/sig_lip.py b/invokeai/backend/model_manager/load/model_loaders/sig_lip.py
index 16b8e6c88d..338dfd972a 100644
--- a/invokeai/backend/model_manager/load/model_loaders/sig_lip.py
+++ b/invokeai/backend/model_manager/load/model_loaders/sig_lip.py
@@ -7,6 +7,7 @@ from invokeai.backend.model_manager.configs.factory import AnyModelConfig
from invokeai.backend.model_manager.load.load_default import ModelLoader
from invokeai.backend.model_manager.load.model_loader_registry import ModelLoaderRegistry
from invokeai.backend.model_manager.taxonomy import AnyModel, BaseModelType, ModelFormat, ModelType, SubModelType
+from invokeai.backend.util.load_report import suppress_load_report
@ModelLoaderRegistry.register(base=BaseModelType.Any, type=ModelType.SigLIP, format=ModelFormat.Diffusers)
@@ -22,5 +23,8 @@ class SigLIPModelLoader(ModelLoader):
raise ValueError("Unexpected submodel requested for LLaVA OneVision model.")
model_path = Path(config.path)
- model = SiglipVisionModel.from_pretrained(model_path, local_files_only=True, torch_dtype=self._torch_dtype)
+ # A full-SigLIP checkpoint carries the text tower this class does not build; see
+ # suppress_load_report.
+ with suppress_load_report():
+ model = SiglipVisionModel.from_pretrained(model_path, local_files_only=True, torch_dtype=self._torch_dtype)
return model
diff --git a/invokeai/backend/util/load_report.py b/invokeai/backend/util/load_report.py
new file mode 100644
index 0000000000..bb9c6ae5af
--- /dev/null
+++ b/invokeai/backend/util/load_report.py
@@ -0,0 +1,62 @@
+"""Suppression of the transformers state-dict load report where it reports only expected keys."""
+
+import logging
+import threading
+from contextlib import contextmanager
+from typing import Iterator
+
+# transformers emits the report from `modeling_utils`, at warning level, through this logger.
+_REPORT_LOGGER_NAME = "transformers.modeling_utils"
+# Its first line is "<ClassName> LOAD REPORT from: <path>" (the class name ANSI-styled),
+# followed by one table of every key that did not line up.
+_REPORT_MARKER = "LOAD REPORT"
+# The table's "Notes" block explains one category per kind of row it contains. UNEXPECTED is
+# the only one a tower load is entitled to; the others mean weights were randomly initialized,
+# reinitialized at a different shape, or failed to convert — i.e. a checkpoint that is not what
+# the class being built expects, which is exactly what must stay in the log. The markers carry
+# the colon only in that block, so a key named like a status cannot be mistaken for one.
+_DIAGNOSTIC_MARKERS = ("MISSING:", "MISMATCH:", "CONVERSION:")
+
+_state = threading.local()
+
+
+class _LoadReportFilter(logging.Filter):
+ def filter(self, record: logging.LogRecord) -> bool:
+ if not getattr(_state, "active", False):
+ return True
+ message = record.getMessage()
+ if _REPORT_MARKER not in message:
+ return True
+ return any(marker in message for marker in _DIAGNOSTIC_MARKERS)
+
+
+# Installed once, on the emitting logger rather than on a handler: transformers keeps its own
+# handler and sets `propagate = False` on its root logger, so a filter installed anywhere on
+# InvokeAI's side would never see these records.
+logging.getLogger(_REPORT_LOGGER_NAME).addFilter(_LoadReportFilter())
+
+
+@contextmanager
+def suppress_load_report() -> Iterator[None]:
+ """Drop transformers' all-expected state-dict load report for a load made on this thread.
+
+ Building a vision or text tower out of a full CLIP/SigLIP checkpoint always mismatches —
+ every key of the tower that is not being built is unexpected, by design — so the report is
+ a two-dozen-line table of keys that are supposed to be there, logged as a warning, on a
+ load that worked. A report that also names missing, mismatched or unconvertible keys is
+ kept: those say the checkpoint is not the one the class expects (a tower silently built
+ with randomly initialized weights embeds and conditions on noise), and transformers refers
+ to the report from the errors it raises for the latter two.
+
+ Scoped to the calling thread rather than lowering `transformers` verbosity, because that is
+ process-global: model loads run concurrently with generation and with the image index
+ worker, so a verbosity toggle here would silence another thread's warnings, and its restore
+ would un-silence a load still in flight. Every other transformers message, including one
+ from the load inside this block, still reaches the log.
+ """
+ previously_active = getattr(_state, "active", False)
+ _state.active = True
+ try:
+ yield
+ finally:
+ _state.active = previously_active
diff --git a/tests/app/services/image_index/test_image_index_service.py b/tests/app/services/image_index/test_image_index_service.py
index 47bd39bfb2..15ca3ccbd6 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -251,6 +251,86 @@ def test_unloadable_image_is_skipped_and_backfill_completes(
assert "bad.png" in service._failed
+def test_backfill_logs_what_it_indexed_and_that_it_finished(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ for i in range(3):
+ _save_image(image_records, f"img-{i}.png")
+
+ with caplog.at_level("INFO", logger="InvokeAI"):
+ service.start(_make_invoker(images_service, index_records))
+ # Waited on the log line itself: the pass reports its outcome after clearing the flag
+ # that says it is running, so waiting on the flag races the message.
+ _wait_until(lambda: "Image index: indexing complete (3 of 3 images indexed)" in caplog.text)
+ assert "Image index: indexing 3 image(s)" in caplog.text
+
+ # An image arriving afterwards is embedded from the queue, not by a backfill pass,
+ # so it does not re-announce one.
+ caplog.clear()
+ _save_image(image_records, "new.png")
+ images_service._on_changed(_dto_for(image_records, "new.png"))
+ _wait_until(lambda: index_records.get_embeddings(["new.png"], MODEL_ID)[0] == ["new.png"])
+ assert "Image index: indexing" not in caplog.text
+
+
+def test_restart_over_an_indexed_gallery_logs_nothing(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ # The common case on every restart: a pass with nothing to do must not announce itself,
+ # or the log gains a line per server start that says nothing happened.
+ _save_image(image_records, "already.png")
+ index_records.upsert_embedding("already.png", MODEL_ID, _unit_vec())
+ invoker = _make_invoker(images_service, index_records)
+
+ with caplog.at_level("INFO", logger="InvokeAI"):
+ service.start(invoker)
+ # The sweep that found nothing emits the status event, so this is the observable that
+ # the pass has been and gone.
+ _wait_until(lambda: any(e.embedded == 1 and e.pending == 0 for e in _status_events(invoker)))
+ assert "Image index: indexing" not in caplog.text
+
+
+def test_backfill_reports_images_it_could_not_embed(
+ image_records: SqliteImageRecordStorage,
+ images_service: ImageService,
+ index_records: ImageIndexRecordsSqlite,
+ service: ImageIndexService,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ _save_image(image_records, "good.png")
+ _save_image(image_records, "bad.png")
+
+ def get_pil_image(image_name: str) -> Image.Image:
+ if image_name == "bad.png":
+ raise FileNotFoundError(image_name)
+ return Image.new("RGB", (16, 16), "purple")
+
+ images_service.get_pil_image = get_pil_image # type: ignore[method-assign]
+
+ with caplog.at_level("INFO", logger="InvokeAI"):
+ service.start(_make_invoker(images_service, index_records))
+ # The pass ends because the failure retired, so the outcome has to say so rather than
+ # claiming a complete index.
+ _wait_until(lambda: "Image index: indexing finished with 1 image(s) that could not be embedded" in caplog.text)
+ assert "indexing complete" not in caplog.text
+
+ # A later pass speaks for itself: the image that retired earlier is still in the
+ # cumulative failure set, but nothing failed this time.
+ caplog.clear()
+ _save_image(image_records, "later.png")
+ service._backfill_pending.set()
+ _wait_until(lambda: "Image index: indexing complete (2 of 3 images indexed)" in caplog.text)
+ assert "could not be embedded" not in caplog.text
+
+
def test_transient_encode_failure_is_retried_to_success(
image_records: SqliteImageRecordStorage,
images_service: ImageService,
diff --git a/tests/backend/util/test_load_report.py b/tests/backend/util/test_load_report.py
new file mode 100644
index 0000000000..12c8d84580
--- /dev/null
+++ b/tests/backend/util/test_load_report.py
@@ -0,0 +1,134 @@
+"""Tests for the transformers state-dict load report suppression.
+
+The report is built and logged entirely inside transformers, so the cases that matter are
+exercised against a real (tiny) checkpoint rather than a hand-written log record: what breaks
+the mechanism is transformers moving the emit site, renaming the table, or restructuring it —
+none of which a synthetic message would notice.
+"""
+
+import logging
+import threading
+from pathlib import Path
+from typing import Iterator
+
+import pytest
+from transformers import CLIPConfig, CLIPModel, CLIPVisionConfig, CLIPVisionModelWithProjection
+
+from invokeai.backend.util.load_report import _REPORT_LOGGER_NAME, suppress_load_report
+
+TOWER_KWARGS = {"hidden_size": 32, "intermediate_size": 37, "num_hidden_layers": 1, "num_attention_heads": 2}
+VISION_KWARGS = {**TOWER_KWARGS, "image_size": 16, "patch_size": 4, "projection_dim": 8}
+
+
[email protected](scope="module")
+def full_clip_checkpoint(tmp_path_factory: pytest.TempPathFactory) -> Path:
+ """A full CLIP checkpoint: loading either tower out of it leaves the other unexpected."""
+ path = tmp_path_factory.mktemp("full-clip")
+ config = CLIPConfig(
+ text_config={**TOWER_KWARGS, "vocab_size": 99, "max_position_embeddings": 16, "projection_dim": 8},
+ vision_config=VISION_KWARGS,
+ projection_dim=8,
+ )
+ CLIPModel(config).save_pretrained(path)
+ return path
+
+
+def reports() -> Iterator[list[logging.LogRecord]]:
+ """Load reports that survive the filter, as the log would receive them."""
+ logger = logging.getLogger(_REPORT_LOGGER_NAME)
+ records: list[logging.LogRecord] = []
+
+ class Capture(logging.Handler):
+ def emit(self, record: logging.LogRecord) -> None:
+ if "LOAD REPORT" in record.getMessage():
+ records.append(record)
+
+ handler = Capture()
+ previous_level = logger.level
+ logger.setLevel(logging.WARNING)
+ logger.addHandler(handler)
+ try:
+ yield records
+ finally:
+ logger.removeHandler(handler)
+ logger.setLevel(previous_level)
+
+
+def test_expected_report_is_dropped_only_inside_the_context(
+ full_clip_checkpoint: Path, reports: list[logging.LogRecord]
+) -> None:
+ with suppress_load_report():
+ CLIPVisionModelWithProjection.from_pretrained(full_clip_checkpoint, local_files_only=True)
+ assert reports == []
+
+ CLIPVisionModelWithProjection.from_pretrained(full_clip_checkpoint, local_files_only=True)
+ assert len(reports) == 1
+ # The text tower is what the dropped report was about.
+ assert "text_model" in reports[0].getMessage()
+
+
+def test_report_naming_missing_weights_survives(full_clip_checkpoint: Path, reports: list[logging.LogRecord]) -> None:
+ # A tower the checkpoint cannot fill: transformers initializes the second layer randomly
+ # and says so in the same report as the expected keys. Silencing that would leave an
+ # encoder embedding on noise with nothing in the log.
+ deeper = CLIPVisionConfig(**{**VISION_KWARGS, "num_hidden_layers": 2})
+
+ with suppress_load_report():
+ CLIPVisionModelWithProjection.from_pretrained(full_clip_checkpoint, config=deeper, local_files_only=True)
+
+ assert len(reports) == 1
+ assert "MISSING" in reports[0].getMessage()
+ assert reports[0].levelno == logging.WARNING
+
+
+def test_other_messages_from_the_same_load_are_kept() -> None:
+ logger = logging.getLogger(_REPORT_LOGGER_NAME)
+ messages: list[str] = []
+
+ class Capture(logging.Handler):
+ def emit(self, record: logging.LogRecord) -> None:
+ messages.append(record.getMessage())
+
+ handler = Capture()
+ logger.addHandler(handler)
+ try:
+ with suppress_load_report():
+ logger.warning("Some weights of the model checkpoint were not used")
+ finally:
+ logger.removeHandler(handler)
+
+ assert messages == ["Some weights of the model checkpoint were not used"]
+
+
+def test_suppression_does_not_reach_other_threads(full_clip_checkpoint: Path, reports: list[logging.LogRecord]) -> None:
+ # Loads run concurrently: the image index worker embeds while a generation loads models.
+ suppressing = threading.Event()
+ loaded = threading.Event()
+
+ def other_thread() -> None:
+ suppressing.wait(timeout=10)
+ CLIPVisionModelWithProjection.from_pretrained(full_clip_checkpoint, local_files_only=True)
+ loaded.set()
+
+ thread = threading.Thread(target=other_thread)
+ thread.start()
+ try:
+ with suppress_load_report():
+ suppressing.set()
+ assert loaded.wait(timeout=30)
+ finally:
+ thread.join(timeout=10)
+
+ assert len(reports) == 1
+
+
+def test_nested_suppression_leaves_the_outer_scope_suppressing(
+ full_clip_checkpoint: Path, reports: list[logging.LogRecord]
+) -> None:
+ with suppress_load_report():
+ with suppress_load_report():
+ pass
+ CLIPVisionModelWithProjection.from_pretrained(full_clip_checkpoint, local_files_only=True)
+
+ assert reports == []