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(image-index): make the text-encoder probe airtight and its verdict stick

Lincoln Stein7d95406670c3
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 1350d6d447..535bad14a1 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -94,21 +94,41 @@ def _text_encoder_defect(tokenizer: Any, model: Any, is_siglip: bool) -> Optiona
float noise among identical scores, and text search still returns a ranking.
One forward pass at load time is what separates that from a working encoder.
"""
- with torch.no_grad():
- # Same padding rule as _embed_texts: SigLIP was trained pad-to-max-length.
- inputs = tokenizer(
- list(_TEXT_PROBE_PAIR),
- padding="max_length" if is_siglip else True,
- return_tensors="pt",
- truncation=True,
- )
- outputs = model(**inputs)
- embeddings = outputs.pooler_output if is_siglip else outputs.text_embeds
- matrix = embeddings.float().cpu().numpy()
+ try:
+ with torch.no_grad():
+ # Same padding rule as _embed_texts: SigLIP was trained pad-to-max-length.
+ inputs = tokenizer(
+ list(_TEXT_PROBE_PAIR),
+ padding="max_length" if is_siglip else True,
+ return_tensors="pt",
+ truncation=True,
+ )
+ outputs = model(**inputs)
+ embeddings = outputs.pooler_output if is_siglip else outputs.text_embeds
+ matrix = embeddings.float().cpu().numpy()
+ except Exception as e:
+ # A probe that cannot complete has not cleared the encoder, and the
+ # shapes it dies on are the same broken installs it exists to catch: a
+ # tokenizer whose ids overrun the tower's vocabulary raises IndexError
+ # inside nn.Embedding, and one that loaded without a model_max_length
+ # raises ValueError on the SigLIP pad-to-max-length path. Reported as a
+ # defect rather than left to escape, which would reach the router untyped
+ # — a 500 instead of the 409 this path exists to produce — and, being
+ # remembered by nothing, reload the tower on the next keystroke.
+ return f"could not be exercised ({type(e).__name__}: {e})"
if not np.isfinite(matrix).all():
return "produced a non-finite embedding"
+ # float64 for the same reason _normalize_query_vector uses it, and here it is
+ # load-bearing rather than defensive: in float32 a pair of *identical* rows
+ # big enough to overflow the sum of squares gives infinite norms and a NaN
+ # cosine, and `NaN >= threshold` is False — so the exact degeneracy this
+ # function exists to catch was waved through as healthy. Every float32 value
+ # is finite here (checked above), so widening puts both the norms and the dot
+ # product out of overflow and underflow range for good.
+ matrix = matrix.astype(np.float64)
+
norms = np.linalg.norm(matrix, axis=1)
if float(norms.min()) == 0.0:
# Checked before the cosine, which would divide by zero here — and an
@@ -232,6 +252,20 @@ class ImageIndexService(ImageIndexServiceBase):
# Lazily-loaded (tokenizer, text_model, is_siglip); None until first text search.
self._text_encoder: Optional[tuple[Any, Any, bool]] = None
self._text_encoder_lock = threading.Lock()
+ # Why the load-time probe rejected this text encoder. Reloading cannot
+ # change the verdict — the invoker owns one service instance per run and
+ # a new one is built from scratch, so the same directory is probed every
+ # time — and each attempt pulls the whole text
+ # tower (hundreds of MB) through MODEL_LOAD_LOCK, contending with
+ # generation's model loads, only to reject it again. Without this that
+ # happens once per search keystroke, because the encoder is never assigned
+ # and so nothing downstream of the probe is cached. _vocab_failure does
+ # the same job for cluster labels, which is the only path it covers.
+ #
+ # The message rather than the exception: a stored exception grows two
+ # traceback frames per re-raise, forever, and the frames it captured at
+ # the rejection keep the rejected tower itself alive.
+ self._text_encoder_failure: Optional[str] = None
# A vocabulary build that already failed. Without this, the very common
# vision-only install retries AutoTokenizer.from_pretrained — inside
# MODEL_LOAD_LOCK, contending with generation's model loads — once per
@@ -314,7 +348,14 @@ class ImageIndexService(ImageIndexServiceBase):
if self._vocab_cache is not None:
return self._vocab_cache
if self._vocab_failure is not None:
- raise self._vocab_failure
+ # Cleared again on the way out, not just when it was stored:
+ # re-raising a persistent exception re-attaches a fresh traceback
+ # to it, so without this the frames grow by one propagation per
+ # labels request, forever, each set holding that request's caller
+ # frame — whose `record` is the whole projection, coordinates
+ # included. Clearing here bounds it to the one propagation in
+ # flight instead, which the next request replaces.
+ raise self._vocab_failure.with_traceback(None)
if self._invoker is None or self._model_id is None:
raise TextSearchUnavailableError("The image index is not running")
@@ -362,10 +403,23 @@ class ImageIndexService(ImageIndexServiceBase):
try:
embeddings = ensemble_phrase_embeddings(self._embed_texts, vocabulary)
except Exception as e:
+ self._invoker.services.logger.warning("Could not build the cluster vocabulary", exc_info=True)
# Remembered, so a vision-only install answers the next request
# from memory instead of reloading the absent text tower.
- self._vocab_failure = e
- self._invoker.services.logger.warning("Could not build the cluster vocabulary", exc_info=True)
+ #
+ # Stripped of every frame it captured, and logged first because
+ # stripping also empties the `exc_info=True` above. Those frames
+ # reach the locals of whatever raised: since the text encoder is
+ # now probed after loading rather than failing during it, a
+ # rejection is raised with the loaded tower still bound, and
+ # keeping the frames would keep hundreds of MB alive for the life
+ # of the process. __cause__ is dropped for the same reason and is
+ # not information: a load failure already names the underlying
+ # error in its own message. The full detail is in the log above;
+ # only type and message are ever re-raised.
+ e.__cause__ = None
+ e.__context__ = None
+ self._vocab_failure = e.with_traceback(None)
return
@@ -392,6 +446,8 @@ class ImageIndexService(ImageIndexServiceBase):
def _get_text_encoder(self) -> tuple[Any, Any, bool]:
with self._text_encoder_lock:
+ if self._text_encoder_failure is not None:
+ raise TextSearchUnavailableError(self._text_encoder_failure)
if self._text_encoder is None:
if self._model_config is None:
raise TextSearchUnavailableError("The image index has no embedding model loaded")
@@ -428,14 +484,16 @@ class ImageIndexService(ImageIndexServiceBase):
model.eval()
defect = _text_encoder_defect(tokenizer, model, is_siglip)
if defect is not None:
- # Cached by the caller as _vocab_failure, so this costs one
- # probe per process rather than one per request.
- raise TextSearchUnavailableError(
+ # Remembered, not just raised: this costs one load and one
+ # probe per process rather than one per request. See
+ # _text_encoder_failure.
+ self._text_encoder_failure = (
f"The configured embedding model's text encoder {defect}, so cluster labels and "
"text search would be meaningless. The usual cause is a model directory with no "
"tokenizer files (vocab.json, merges.txt): reinstall the embedding model to get "
- "them, or configure image_index_model to a model that has them"
+ "them, or configure image_index_model to a model that has them, then restart"
)
+ raise TextSearchUnavailableError(self._text_encoder_failure)
self._text_encoder = (tokenizer, model, is_siglip)
return self._text_encoder
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 5c5a7a70cc..e98609658a 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -3,6 +3,7 @@
import inspect
import threading
import time
+import weakref
from types import SimpleNamespace
from typing import Callable
from unittest.mock import patch
@@ -1630,12 +1631,54 @@ def test_a_degenerate_text_encoder_is_detected(matrix: torch.Tensor, expected: s
assert expected in defect
+def test_a_degenerate_text_encoder_is_detected_even_when_its_norms_overflow_float32() -> None:
+ # Identical rows are the failure this guard exists for, but in float32 a
+ # large enough pair overflows the sum of squares: the norms come back inf,
+ # the cosine NaN, and `NaN >= threshold` is False — so the guard used to wave
+ # this through as healthy. The matrix itself is finite, so the non-finite
+ # branch above does not catch it either. Reachable whenever the tower's
+ # weights are garbage rather than absent (see skip_torch_weight_init in
+ # _get_text_encoder, whose monkey-patch can leak process-wide).
+ from invokeai.app.services.image_index.image_index_default import _text_encoder_defect
+
+ matrix = torch.full((2, 4), 1e20)
+ assert torch.equal(matrix[0], matrix[1])
+ assert torch.isfinite(matrix).all()
+
+ defect = _text_encoder_defect(_FakeTokenizer(distinct=False), _FakeTextModel(matrix), False)
+
+ assert defect is not None
+ assert "same embedding" in defect
+
+
+def test_a_probe_that_raises_is_reported_as_a_defect_rather_than_escaping() -> None:
+ # A probe that cannot complete has not cleared the encoder. Left to escape it
+ # reaches the router untyped and becomes a 500 instead of the 409 this path
+ # exists to produce. The trigger is a real broken install: a tokenizer whose
+ # ids overrun the tower's vocabulary raises IndexError inside nn.Embedding.
+ from invokeai.app.services.image_index.image_index_default import _text_encoder_defect
+
+ class _ExplodingModel:
+ def eval(self) -> "_ExplodingModel":
+ return self
+
+ def __call__(self, **inputs):
+ raise IndexError("index out of range in self")
+
+ defect = _text_encoder_defect(_FakeTokenizer(distinct=True), _ExplodingModel(), False)
+
+ assert defect is not None
+ assert "could not be exercised" in defect
+ assert "IndexError" in defect
+
+
def test_embed_text_refuses_a_text_encoder_that_cannot_tell_phrases_apart(
tmp_path, monkeypatch: pytest.MonkeyPatch
) -> None:
# End to end through the lazy loader: the typed error is what the router
# maps to a 409, so labels and search report unavailable rather than
# serving results computed from identical vectors.
+ import gc
import json
import transformers
@@ -1645,26 +1688,118 @@ def test_embed_text_refuses_a_text_encoder_that_cannot_tell_phrases_apart(
(tmp_path / "config.json").write_text(json.dumps({"model_type": "clip", "architectures": ["CLIPModel"]}))
constant = torch.ones((2, DIM))
+ loads: list[weakref.ReferenceType] = []
+
+ def _load_model(cls, *args, **kwargs):
+ model = _FakeTextModel(constant)
+ loads.append(weakref.ref(model))
+ return model
+
monkeypatch.setattr(
transformers.AutoTokenizer, "from_pretrained", classmethod(lambda cls, *a, **k: _FakeTokenizer(distinct=False))
)
- monkeypatch.setattr(
- transformers.CLIPTextModelWithProjection,
- "from_pretrained",
- classmethod(lambda cls, *a, **k: _FakeTextModel(constant)),
- )
+ monkeypatch.setattr(transformers.CLIPTextModelWithProjection, "from_pretrained", classmethod(_load_model))
service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)
service._invoker = SimpleNamespace(services=SimpleNamespace(configuration=SimpleNamespace(models_path=tmp_path))) # type: ignore[assignment]
service._model_config = SimpleNamespace(type=ModelType.CLIPVision, path=str(tmp_path)) # type: ignore[assignment]
service._model_id = MODEL_ID
- with pytest.raises(TextSearchUnavailableError, match="same embedding"):
- service.embed_text("a query")
+ for _ in range(3):
+ with pytest.raises(TextSearchUnavailableError, match="same embedding"):
+ service.embed_text("a query")
- # Nothing was cached, so a later request re-probes rather than serving the
- # encoder this one rejected.
+ # The rejected encoder is not served...
assert service._text_encoder is None
+ # ...and not reloaded either. Reloading cannot change the verdict, and every
+ # attempt drags the whole text tower through MODEL_LOAD_LOCK, contending with
+ # generation's model loads — once per search keystroke on a broken install.
+ assert len(loads) == 1
+ # What is remembered is the message. A remembered *exception* would keep the
+ # rejected tower alive through the frames its traceback captured — the leak
+ # test below covers that end; here it is enough that nothing holds a tower.
+ assert isinstance(service._text_encoder_failure, str)
+ gc.collect()
+ assert loads[0]() is None
+
+
+def test_a_failed_vocabulary_build_does_not_pin_the_rejected_text_encoder(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # The vocabulary build remembers its failure so a broken install answers the
+ # next request from memory. It must not remember the traceback with it: the
+ # probe rejects the encoder *after* loading it, so those frames hold the
+ # loaded tower — hundreds of MB kept alive for the life of the process.
+ import gc
+ import json
+
+ import transformers
+
+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
+ from invokeai.backend.model_manager.taxonomy import ModelType
+
+ (tmp_path / "config.json").write_text(json.dumps({"model_type": "clip", "architectures": ["CLIPModel"]}))
+ towers: list[weakref.ReferenceType] = []
+
+ def _load_model(cls, *args, **kwargs):
+ model = _FakeTextModel(torch.ones((2, DIM)))
+ towers.append(weakref.ref(model))
+ return model
+
+ monkeypatch.setattr(
+ transformers.AutoTokenizer, "from_pretrained", classmethod(lambda cls, *a, **k: _FakeTokenizer(distinct=False))
+ )
+ monkeypatch.setattr(transformers.CLIPTextModelWithProjection, "from_pretrained", classmethod(_load_model))
+
+ service = ImageIndexService(encode_fn=_fake_encode, model_id=MODEL_ID)
+ service._invoker = SimpleNamespace( # type: ignore[assignment]
+ services=SimpleNamespace(
+ configuration=SimpleNamespace(models_path=tmp_path, db_path=tmp_path / "db.sqlite"),
+ # Not a real Logger: pytest's logging plugin retains every LogRecord
+ # for the test, and a record carrying exc_info holds the very
+ # traceback whose release is being asserted.
+ logger=SimpleNamespace(warning=lambda *args, **kwargs: None),
+ )
+ )
+ service._model_config = SimpleNamespace(type=ModelType.CLIPVision, path=str(tmp_path)) # type: ignore[assignment]
+ service._model_id = MODEL_ID
+
+ service._build_vocab_embeddings()
+
+ assert service._vocab_failure is not None
+ assert service._vocab_failure.__traceback__ is None
+ assert service._vocab_failure.__cause__ is None
+ gc.collect()
+ assert towers and towers[0]() is None
+
+ # And it does not regrow. Re-raising a persistent exception re-attaches a
+ # traceback to it, so a stored failure cleared only once accumulates a frame
+ # set per labels request, each holding that request's caller frame.
+ holders: list[weakref.ReferenceType] = []
+
+ def one_labels_request() -> None:
+ # Stands in for the router frame, whose `record` is the whole projection.
+ record = np.zeros((50_000, 2), dtype=np.float32)
+ holders.append(weakref.ref(record))
+ with pytest.raises(TextSearchUnavailableError):
+ service.get_vocab_embeddings()
+
+ def frame_count() -> int:
+ count, traceback = 0, service._vocab_failure.__traceback__
+ while traceback is not None:
+ count, traceback = count + 1, traceback.tb_next
+ return count
+
+ one_labels_request()
+ after_one = frame_count()
+ for _ in range(9):
+ one_labels_request()
+
+ # Bounded at the one propagation in flight rather than growing with traffic,
+ # so every caller frame but the current one is released.
+ assert frame_count() == after_one
+ gc.collect()
+ assert [index for index, ref in enumerate(holders) if ref() is not None] == [len(holders) - 1]
def test_search_similar_returns_empty_when_not_running(service: ImageIndexService) -> None: