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): reject a text encoder that cannot tell phrases apart

Lincoln Stein0aaaadb97b9b
diff --git a/invokeai/app/services/image_index/cluster_labels.py b/invokeai/app/services/image_index/cluster_labels.py
index 95b9a20549..090f37d5c9 100644
--- a/invokeai/app/services/image_index/cluster_labels.py
+++ b/invokeai/app/services/image_index/cluster_labels.py
@@ -47,7 +47,10 @@ def load_vocabulary() -> list[str]:
# Bump when the text-embedding recipe changes (tokenization/padding/pooling):
# cached phrase embeddings computed under an old recipe must be discarded.
-_EMBEDDING_RECIPE = "pad-per-model-v2"
+# v3 also retires caches written before the text encoder was probed at load
+# time: a tokenizer-less model dir produced a cache in which every phrase holds
+# the same vector, and nothing about the file itself says so.
+_EMBEDDING_RECIPE = "pad-per-model-v3"
def vocab_fingerprint(phrases: list[str]) -> str:
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index dbf46f8e33..1350d6d447 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -74,6 +74,54 @@ def _normalize_query_vector(vector: np.ndarray) -> np.ndarray:
return (vector / norm).astype(EMBEDDING_DTYPE)
+# Two phrases that share no content words. Any working text tower puts them well
+# apart (~0.6 cosine for CLIP); a broken one maps them to the same vector.
+_TEXT_PROBE_PAIR = ("a photograph of a cat", "an engineering diagram")
+# Not 1.0: the failure is exact degeneracy, but float paths and fp16 towers can
+# land a hair below it, and no usable encoder comes anywhere near this.
+_TEXT_PROBE_MAX_COSINE = 0.999
+
+
+def _text_encoder_defect(tokenizer: Any, model: Any, is_siglip: bool) -> Optional[str]:
+ """Why this text encoder is unusable, or None if it tells two phrases apart.
+
+ A model directory with no tokenizer files does not fail to load: transformers
+ resolves the tokenizer class from config.json and builds it with an empty
+ vocabulary, which maps every word to the same unknown token. The tower then
+ faithfully encodes that, so every phrase - every vocabulary label, every
+ search query - comes back as the same vector. Nothing downstream can detect
+ it: cluster labelling still returns a label for every cluster, chosen by
+ 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()
+
+ if not np.isfinite(matrix).all():
+ return "produced a non-finite embedding"
+
+ 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
+ # all-zero pair would otherwise score 0.0 and pass as "discriminating".
+ return "produced an all-zero embedding"
+
+ cosine = float(matrix[0] @ matrix[1] / (norms[0] * norms[1]))
+ if cosine >= _TEXT_PROBE_MAX_COSINE:
+ return f"maps unrelated phrases to the same embedding (cosine {cosine:.3f})"
+
+ return None
+
+
def _normalize_batch(matrix: np.ndarray) -> np.ndarray:
"""L2-normalize each row, zeroing the ones that cannot be normalized.
@@ -378,6 +426,16 @@ class ImageIndexService(ImageIndexServiceBase):
"tokenizer files, to enable semantic text search"
) from e
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(
+ 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"
+ )
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 01e3d155a2..5c5a7a70cc 100644
--- a/tests/app/services/image_index/test_image_index_service.py
+++ b/tests/app/services/image_index/test_image_index_service.py
@@ -1572,6 +1572,101 @@ def test_embed_text_unavailable_when_tokenizer_files_missing(tmp_path) -> None:
service.embed_text("a query")
+class _FakeTokenizer:
+ """Stands in for a transformers tokenizer: only the call shape matters here."""
+
+ def __init__(self, distinct: bool) -> None:
+ self._distinct = distinct
+
+ def __call__(self, texts, padding=True, return_tensors="pt", truncation=True):
+ # A vocabulary-less tokenizer emits the same unknown token for every
+ # word, so two unrelated phrases differ in nothing but length.
+ rows = [[0, 2, 2, 2] if not self._distinct else [0, index + 3, index + 9, 1] for index in range(len(texts))]
+ return {"input_ids": torch.tensor(rows, dtype=torch.long)}
+
+
+class _FakeTextModel:
+ """Returns rows straight from a fixture matrix, keyed by batch size."""
+
+ def __init__(self, matrix: torch.Tensor) -> None:
+ self._matrix = matrix
+
+ def eval(self) -> "_FakeTextModel":
+ return self
+
+ def __call__(self, **inputs):
+ count = inputs["input_ids"].shape[0]
+ return SimpleNamespace(text_embeds=self._matrix[:count], pooler_output=self._matrix[:count])
+
+
+def test_a_text_encoder_that_discriminates_reports_no_defect() -> None:
+ from invokeai.app.services.image_index.image_index_default import _text_encoder_defect
+
+ matrix = torch.tensor([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]])
+
+ assert _text_encoder_defect(_FakeTokenizer(distinct=True), _FakeTextModel(matrix), False) is None
+
+
+ "matrix, expected",
+ [
+ (torch.tensor([[0.5, 0.25, 0.0, 0.0], [0.5, 0.25, 0.0, 0.0]]), "same embedding"),
+ (torch.zeros((2, 4)), "all-zero"),
+ (torch.tensor([[float("nan"), 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]]), "non-finite"),
+ ],
+)
+def test_a_degenerate_text_encoder_is_detected(matrix: torch.Tensor, expected: str) -> None:
+ # The failure this exists for: a model directory with no tokenizer files
+ # still loads, because transformers builds a tokenizer with an empty
+ # vocabulary that maps every word to the same unknown token. Every phrase
+ # then embeds identically, and both cluster labels and text search go on
+ # returning confident nonsense — labels chosen by float noise among equal
+ # scores — with nothing downstream able to tell.
+ from invokeai.app.services.image_index.image_index_default import _text_encoder_defect
+
+ defect = _text_encoder_defect(_FakeTokenizer(distinct=False), _FakeTextModel(matrix), False)
+
+ assert defect is not None
+ assert expected 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 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"]}))
+ constant = torch.ones((2, DIM))
+ 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)),
+ )
+
+ 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")
+
+ # Nothing was cached, so a later request re-probes rather than serving the
+ # encoder this one rejected.
+ assert service._text_encoder is None
+
+
def test_search_similar_returns_empty_when_not_running(service: ImageIndexService) -> None:
assert service.search_similar(None, np.ones(DIM, dtype=np.float32), limit=5) == []